auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public synchronized void start() throws Exception { if (state == State.RUNNING) { LOG.debug("Ignore start() call on HTTP service since it has already been started.", serviceName); return; } if (state != State.NOT_STARTED) { if (state == State.STOPPED) { throw new IllegalStateException("Cannot start the HTTP service " + serviceName + " again since it has been stopped"); } throw new IllegalStateException("Cannot start the HTTP service " + serviceName + " because it was failed earlier"); } try { LOG.info("Starting HTTP Service at address {}", serviceName, bindAddress); channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); resourceHandler.init(handlerContext); eventExecutorGroup = createEventExecutorGroup(execThreadPoolSize); bootstrap = createBootstrap(channelGroup); Channel serverChannel = bootstrap.bind(bindAddress).sync().channel(); channelGroup.add(serverChannel); bindAddress = (InetSocketAddress) serverChannel.localAddress(); LOG.debug("Started HTTP Service at address {}", serviceName, bindAddress); state = State.RUNNING; } catch (Throwable t) { channelGroup.close().awaitUninterruptibly(); try { if (bootstrap != null) { shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup); } else { shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, eventExecutorGroup); } } catch (Throwable t2) { } state = State.FAILED; throw (Exception) t; } }

Target:
public synchronized void start() throws Throwable { if (state == State.RUNNING) { LOG.debug("Ignore start() call on HTTP service since it has already been started.", serviceName); return; } if (state != State.NOT_STARTED) { if (state == State.STOPPED) { throw new IllegalStateException("Cannot start the HTTP service " + serviceName + " again since it has been stopped"); } throw new IllegalStateException("Cannot start the HTTP service " + serviceName + " because it was failed earlier"); } try { LOG.info("Starting HTTP Service at address {}", serviceName, bindAddress); channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); resourceHandler.init(handlerContext); eventExecutorGroup = createEventExecutorGroup(execThreadPoolSize); bootstrap = createBootstrap(channelGroup); Channel serverChannel = bootstrap.bind(bindAddress).sync().channel(); channelGroup.add(serverChannel); bindAddress = (InetSocketAddress) serverChannel.localAddress(); LOG.debug("Started HTTP Service at address {}", serviceName, bindAddress); state = State.RUNNING; } catch (Throwable t) { channelGroup.close().awaitUninterruptibly(); try { if (bootstrap != null) { shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup); } else { shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, eventExecutorGroup); } } catch (Throwable t2) { } state = State.FAILED; throw t; } }
Source:
private FileObject processFile(FileObject file) throws AxisFault { boolean isFailedRecord = VFSUtils.isFailRecord(fsManager, file); if(isFailedRecord) { return file; } else { try { FileContent content = file.getContent(); String fileName = file.getName().getBaseName(); String filePath = file.getName().getPath(); String fileURI = file.getName().getURI(); if (injectHandler != null) { Map<String, Object> transportHeaders = new HashMap<String, Object>(); transportHeaders.put(VFSConstants.FILE_PATH, filePath); transportHeaders.put(VFSConstants.FILE_NAME, fileName); transportHeaders.put(VFSConstants.FILE_URI, fileURI); try { transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize()); transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime()); } catch (FileSystemException e) { log.warn("Unable to set file length or last modified date header.", e); } injectHandler.setTransportHeaders(transportHeaders); if (!injectHandler.invoke(file)) { return null; } } } catch (FileSystemException e) { log.error("Error reading file content or attributes : " + file, e); } return file; } }

Target:
private FileObject processFile(FileObject file) throws AxisFault { try { FileContent content = file.getContent(); String fileName = file.getName().getBaseName(); String filePath = file.getName().getPath(); String fileURI = file.getName().getURI(); if (injectHandler != null) { Map<String, Object> transportHeaders = new HashMap<String, Object>(); transportHeaders.put(VFSConstants.FILE_PATH, filePath); transportHeaders.put(VFSConstants.FILE_NAME, fileName); transportHeaders.put(VFSConstants.FILE_URI, fileURI); try { transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize()); transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime()); } catch (FileSystemException e) { log.warn("Unable to set file length or last modified date header.", e); } injectHandler.setTransportHeaders(transportHeaders); if (!injectHandler.invoke(file)) { return null; } } } catch (FileSystemException e) { log.error("Error reading file content or attributes : " + file, e); } return file; }
Source:
private static Collection<InetAddress> resolveInetAddresses(ClusterNode node) { Set<InetAddress> res = new HashSet<>(node.addresses().size()); Iterator<String> hostNamesIt = node.hostNames().iterator(); for (String addr : node.addresses()) { String hostName = hostNamesIt.hasNext() ? hostNamesIt.next() : null; InetAddress inetAddr = null; if (!F.isEmpty(hostName)) { try { if (IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_TEST_ENV)) { if (hostName.endsWith(".hostname")) { String ipStr = hostName.substring(0, hostName.length() - ".hostname".length()); inetAddr = InetAddress.getByAddress(hostName, InetAddress.getByName(ipStr).getAddress()); } else throw new UnknownHostException(hostName); } else inetAddr = InetAddress.getByName(hostName); } catch (UnknownHostException ignored) { } } if (inetAddr == null || inetAddr.isLoopbackAddress()) { try { if (IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_TEST_ENV)) inetAddr = InetAddress.getByAddress(addr + ".hostname", InetAddress.getByName(addr).getAddress()); else inetAddr = InetAddress.getByName(addr); } catch (UnknownHostException ignored) { } } if (inetAddr != null) res.add(inetAddr); } return res; }

Target:
private static Collection<InetAddress> resolveInetAddresses(ClusterNode node) { Set<InetAddress> res = new HashSet<>(node.addresses().size()); Iterator<String> hostNamesIt = node.hostNames().iterator(); for (String addr : node.addresses()) { String hostName = hostNamesIt.hasNext() ? hostNamesIt.next() : null; InetAddress inetAddr = null; if (!F.isEmpty(hostName)) { try { if (IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_TEST_ENV)) { if (hostName.endsWith(".hostname")) { String ipStr = hostName.substring(0, hostName.length() - ".hostname".length()); inetAddr = InetAddress.getByAddress(hostName, InetAddress.getByName(ipStr).getAddress()); } } else inetAddr = InetAddress.getByName(hostName); } catch (UnknownHostException ignored) { } } if (inetAddr == null || inetAddr.isLoopbackAddress()) { try { if (IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_TEST_ENV)) inetAddr = InetAddress.getByAddress(addr + ".hostname", InetAddress.getByName(addr).getAddress()); else inetAddr = InetAddress.getByName(addr); } catch (UnknownHostException ignored) { } } if (inetAddr != null) res.add(inetAddr); } return res; }
Source:
public String toString() { return dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()) + " " + localTime.toString(); }

Target:
public String toString() { return dayOfWeek + "@" + localTime; }
Source:
public MessageListenerTestContainer createListenerContainer(RabbitListenerEndpoint endpoint) { MessageListenerTestContainer container = new MessageListenerTestContainer(endpoint); this.listenerContainers.put(endpoint.getId(), container); if (endpoint.getId() == null && endpoint instanceof AbstractRabbitListenerEndpoint) { ((AbstractRabbitListenerEndpoint) endpoint).setId("endpoint#" + counter.getAndIncrement()); } return container; }

Target:
public MessageListenerTestContainer createListenerContainer(RabbitListenerEndpoint endpoint) { MessageListenerTestContainer container = new MessageListenerTestContainer(endpoint); if (endpoint.getId() == null && endpoint instanceof AbstractRabbitListenerEndpoint) { ((AbstractRabbitListenerEndpoint) endpoint).setId("endpoint#" + counter.getAndIncrement()); } String id = endpoint.getId(); assertNotNull(this.getClass().getSimpleName() + " does not support " + endpoint.getClass().getSimpleName() + " without an id", id); this.listenerContainers.put(id, container); return container; }
Source:
public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.CONSTRUCTOR); }

Target:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList(Tree.Kind.CONSTRUCTOR); }
Source:
void shouldNotFailOnDeleteByEntityWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> { tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume(); return null; }); } StepVerifier.create(repository.findById(1L).map(thing -> repository.deleteById(1L))) .expectNextCount(1L) .verifyComplete(); }

Target:
void shouldNotFailOnDeleteByEntityWithNullVersion(@Autowired VersionedThingWithAssignedIdRepository repository) { try (Session session = driver.session()) { session.writeTransaction(tx -> tx.run("CREATE (v:VersionedThingWithAssignedId {id:1})").consume()); } StepVerifier.create(repository.findById(1L).map(thing -> repository.deleteById(1L))) .expectNextCount(1L) .verifyComplete(); }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { logger.debug("validateItemType called with bindingConfig={}", bindingConfig); Matcher matcher = CONFIG_PATTERN.matcher(bindingConfig); if (!matcher.matches() || matcher.groupCount() != 2) throw new BindingConfigParseException("Config for item '" + item.getName() + "' could not be parsed."); String property = matcher.group(2); logger.debug("validateItemType called with property={}", property); }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { logger.trace("validateItemType called with bindingConfig={}", bindingConfig); Matcher matcher = CONFIG_PATTERN.matcher(bindingConfig); if (!matcher.matches() || matcher.groupCount() != 2) throw new BindingConfigParseException("Config for item '" + item.getName() + "' could not be parsed."); String property = matcher.group(2); logger.trace("validateItemType called with property={}", property); }
Source:
private SearchQueryBuilder(FhirContext theFhirContext, ModelConfig theModelConfig, PartitionSettings thePartitionSettings, RequestPartitionId theRequestPartitionId, String theResourceType, SqlObjectFactory theSqlBuilderFactory, String theBindVariableSubstitutionBase, Dialect theDialect, boolean theCountQuery, ArrayList<Object> theBindVariableValues) { myFhirContext = theFhirContext; myModelConfig = theModelConfig; myPartitionSettings = thePartitionSettings; myRequestPartitionId = theRequestPartitionId; myResourceType = theResourceType; mySqlBuilderFactory = theSqlBuilderFactory; myCountQuery = theCountQuery; myDialect = theDialect; if (myDialect instanceof org.hibernate.dialect.MySQL57Dialect){ dialectIsMySql = true; } if (myDialect instanceof org.hibernate.dialect.MariaDB53Dialect){ dialectIsMariaDb = true; } if (myDialect instanceof org.hibernate.dialect.SQLServer2012Dialect){ dialectIsMsSql = true; } mySpec = new DbSpec(); mySchema = mySpec.addDefaultSchema(); mySelect = new SelectQuery(); myBindVariableSubstitutionBase = theBindVariableSubstitutionBase; myBindVariableValues = theBindVariableValues; }

Target:
private SearchQueryBuilder(FhirContext theFhirContext, ModelConfig theModelConfig, PartitionSettings thePartitionSettings, RequestPartitionId theRequestPartitionId, String theResourceType, SqlObjectFactory theSqlBuilderFactory, String theBindVariableSubstitutionBase, Dialect theDialect, boolean theCountQuery, ArrayList<Object> theBindVariableValues) { myFhirContext = theFhirContext; myModelConfig = theModelConfig; myPartitionSettings = thePartitionSettings; myRequestPartitionId = theRequestPartitionId; myResourceType = theResourceType; mySqlBuilderFactory = theSqlBuilderFactory; myCountQuery = theCountQuery; myDialect = theDialect; if (myDialect instanceof org.hibernate.dialect.MySQLDialect){ dialectIsMySql = true; } if (myDialect instanceof org.hibernate.dialect.SQLServerDialect){ dialectIsMsSql = true; } mySpec = new DbSpec(); mySchema = mySpec.addDefaultSchema(); mySelect = new SelectQuery(); myBindVariableSubstitutionBase = theBindVariableSubstitutionBase; myBindVariableValues = theBindVariableValues; }
Source:
private static Analyzer createAnalyzer() { try { return (Analyzer) Class.forName(LUCENE_ANALYZER) .getConstructor(Version.class) .newInstance(Version.LUCENE_30); } catch (Exception e) { throw new IllegalArgumentException("Unable to initizalize Lucene analyzer", e); } }

Target:
private static Analyzer createAnalyzer() { String analyzerClassName = Utils.getProperty(LUCENE_ANALYZER, null); if (analyzerClassName == null) { return new StandardAnalyzer(); } try { return (Analyzer) Class.forName(analyzerClassName).getConstructor().newInstance(); } catch (Exception e) { throw DbException.get(ErrorCode.LUCENE_ANALYZER_DOES_NOT_EXIST_1, e, analyzerClassName); } }
Source:
static void uploadClusterConfigs(String hardwareLayoutPath, String partitionLayoutPath, String zkLayoutPath, String clusterNamePrefix, int maxPartitionsInOneResource, HelixAdminFactory helixAdminFactory) throws Exception { HelixBootstrapUpgradeUtil clusterMapToHelixMapper = new HelixBootstrapUpgradeUtil(hardwareLayoutPath, partitionLayoutPath, zkLayoutPath, clusterNamePrefix, maxPartitionsInOneResource, false, false, helixAdminFactory); Map<String, Map<String, String>> partitionOverrideInfos = clusterMapToHelixMapper.generatePartitionOverrideFromAllDCs(); info("Uploading partition override to HelixPropertyStore based on static clustermap."); clusterMapToHelixMapper.uploadPartitionOverride(partitionOverrideInfos); info("Upload cluster configs completed."); }

Target:
static void uploadClusterConfigs(String hardwareLayoutPath, String partitionLayoutPath, String zkLayoutPath, String clusterNamePrefix, int maxPartitionsInOneResource, HelixAdminFactory helixAdminFactory) throws Exception { HelixBootstrapUpgradeUtil clusterMapToHelixMapper = new HelixBootstrapUpgradeUtil(hardwareLayoutPath, partitionLayoutPath, zkLayoutPath, clusterNamePrefix, maxPartitionsInOneResource, false, false, helixAdminFactory); Map<String, Map<String, String>> partitionOverrideInfos = clusterMapToHelixMapper.generatePartitionOverrideFromAllDCs(); info("Uploading partition override to HelixPropertyStore based on override json file."); clusterMapToHelixMapper.uploadPartitionOverride(partitionOverrideInfos); info("Upload cluster configs completed."); }
Source:
public void onPlayerJoin(final PlayerJoinEvent event) { for (NPC npc : getAllNPCs()) { if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) { ((CraftPlayer)event.getPlayer()).getHandle().playerConnection.sendPacket( new PacketPlayOutPlayerInfo(EnumPlayerInfoAction.ADD_PLAYER, ((CraftPlayer) npc .getEntity()).getHandle())); } } Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() { @Override public void run() { for (NPC npc : getAllNPCs()) { if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) { ((CraftPlayer)event.getPlayer()).getHandle().playerConnection.sendPacket( new PacketPlayOutPlayerInfo(EnumPlayerInfoAction.REMOVE_PLAYER, ((CraftPlayer) npc .getEntity()).getHandle())); } } } }, 60); }

Target:
public void onPlayerJoin(final PlayerJoinEvent event) { for (NPC npc : getAllNPCs()) { if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) { NMS.sendPlayerlistPacket(true, event.getPlayer(), npc); } } Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() { @Override public void run() { for (NPC npc : getAllNPCs()) { if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) { NMS.sendPlayerlistPacket(false, event.getPlayer(), npc); } } } }, 60); }
Source:
public void updateShuttleRoutesStopView(final MITShuttle mitShuttle, final boolean isFirstStop) { HashMap<String, String> stopParams = new HashMap<String, String>(); stopParams.put("route", mitShuttle.getRouteID()); if (isFirstStop) { stopParams.put("stop", mitShuttle.getFirstStopID()); } else { stopParams.put("stop", mitShuttle.getSecondStopID()); } apiClient.get(Constants.SHUTTLES, Constants.Shuttles.STOP_INFO_PATH, stopParams, null, new Callback<MITShuttleStopWrapper>() { @Override public void success(MITShuttleStopWrapper mitShuttleStopWrapper, Response response) { if (mitShuttleStopWrapper.getPredictions() != null) { if (mitShuttleStopWrapper.getPredictions().size() != 0) { if (isFirstStop) { mitShuttle.setFirstMinute(mitShuttleStopWrapper.getPredictions().get(0). getSeconds() / 60 + "m"); } else { mitShuttle.setSecondMinute(mitShuttleStopWrapper.getPredictions().get(0). getSeconds() / 60 + "m"); } } } mitShuttleAdapter.notifyDataSetChanged(); } @Override public void failure(RetrofitError error) { } }); }

Target:
public void updateShuttleRoutesStopView(final MITShuttle mitShuttle, final boolean isFirstStop) { HashMap<String, String> stopParams = new HashMap<String, String>(); stopParams.put("route", mitShuttle.getRouteID()); if (isFirstStop) { stopParams.put("stop", mitShuttle.getFirstStopID()); } else { stopParams.put("stop", mitShuttle.getSecondStopID()); } apiClient.get(Constants.SHUTTLES, Constants.Shuttles.STOP_INFO_PATH, stopParams, null, new Callback<MITShuttleStopWrapper>() { @Override public void success(MITShuttleStopWrapper mitShuttleStopWrapper, Response response) { if (mitShuttleStopWrapper.getPredictions() != null && mitShuttleStopWrapper.getPredictions().size() > 0) { if (isFirstStop) { mitShuttle.setFirstMinute(mitShuttleStopWrapper.getPredictions().get(0). getSeconds() / 60 + "m"); } else { mitShuttle.setSecondMinute(mitShuttleStopWrapper.getPredictions().get(0). getSeconds() / 60 + "m"); } } mitShuttleAdapter.notifyDataSetChanged(); } @Override public void failure(RetrofitError error) { } }); }
Source:
public List<JobVertexID> getVertices() { return vertices; }

Target:
public List<JobVertexID> getVertices() { return Collections.unmodifiableList(vertices); }
Source:
public InputFilterMinMax(String min, String max) { this.min = Double.parseDouble(min); this.max = Double.parseDouble(max); }

Target:
public InputFilterMinMax(String min, String max) { this.min = ReadingTools.safeParseDouble(min); this.max = ReadingTools.safeParseDouble(max); }
Source:
public void eval(FunctionContext ctx, Tuple params) { CurrentValueContext currentValueCtx = (CurrentValueContext)ctx; if (params.get(0).isNotNull()) { currentValueCtx.current = params.get(0); } else { currentValueCtx.current = NullDatum.get(); } }

Target:
public void eval(FunctionContext ctx, Tuple params) { CurrentValueContext currentValueCtx = (CurrentValueContext)ctx; if (params.get(0) == null || params.get(0).isNull()) { currentValueCtx.current = NullDatum.get(); } else { currentValueCtx.current = params.get(0); } }
Source:
public void testKeepAliveTTLWith2Req() throws Exception { int numReqs = 2; AtomicInteger current = new AtomicInteger(); AtomicLong connection1CloseTimestamp = new AtomicLong(); AtomicLong connection2StartTimestamp = new AtomicLong(); server.requestHandler(req -> { current.getAndIncrement(); if(current.get() == 2) connection2StartTimestamp.set(System.currentTimeMillis()); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } req.response().end(); }); HttpClientOptions options = createBaseClientOptions() .setMaxPoolSize(1) .setKeepAlive(true) .setKeepAliveTimeout(300) .setHttp2KeepAliveTimeout(300) .setKeepAliveTTL(1); startServer(testAddress); client.close(); client = vertx.createHttpClient(options.setPoolCleanerPeriod(1)); for (int i = 0;i < numReqs; i++) { client.request(HttpMethod.GET, testAddress, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI) .onComplete(onSuccess(resp -> { resp.request().connection().closeHandler(v -> { if(current.get() == 1) connection1CloseTimestamp.set(System.currentTimeMillis()); if (current.get() == numReqs) { assertTrue("Connection2 start timestamp > Connection1 end timestamp", connection2StartTimestamp.get() > connection1CloseTimestamp.get()); testComplete(); } }); })) .end(); } await(); }

Target:
public void testKeepAliveTTLWith2Req() throws Exception { int numReqs = 2; AtomicInteger current = new AtomicInteger(); AtomicLong connection1CloseTimestamp = new AtomicLong(); AtomicLong connection2StartTimestamp = new AtomicLong(); ArrayList<HttpConnection> connections = new ArrayList<>(); server.requestHandler(req -> { current.getAndIncrement(); if(current.get() == 2) connection2StartTimestamp.set(System.currentTimeMillis()); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } req.response().end(); }); HttpClientOptions options = createBaseClientOptions() .setMaxPoolSize(1) .setKeepAlive(true) .setKeepAliveTimeout(300) .setHttp2KeepAliveTimeout(300) .setKeepAliveTTL(1) .setPoolCleanerPeriod(1); startServer(testAddress); client.close(); client = vertx.createHttpClient(options); for (int i = 0; i < numReqs; i++) { client.request(HttpMethod.GET, testAddress, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI) .onComplete(onSuccess(resp -> { connections.add(resp.request().connection().closeHandler(v -> { if(current.get() == 1) { connection1CloseTimestamp.set(System.currentTimeMillis()); } if (current.get() == numReqs) { assertTrue("Connection2 start timestamp > Connection1 end timestamp", connection2StartTimestamp.get() > connection1CloseTimestamp.get()); assertNotSame("Connection1 and connection2 are different physical connections", connections.get(0), connections.get(1)); testComplete(); } })); })) .end(); } await(); }
Source:
private ActiveQueryPickManager() { activeQueryWorkingQueue = new ConcurrentLinkedQueue<>(); activeQueryWaitingQueue = new ConcurrentLinkedQueue<>(); sharedLock = new Object(); }

Target:
private ActiveQueryPickManager() { this.activeQueryQueue = new ConcurrentLinkedQueue<>(); }
Source:
public boolean stop() { if (s_logger.isInfoEnabled()) { s_logger.info("Stopping Alert Manager"); } return true; }

Target:
public boolean stop() { if (s_logger.isInfoEnabled()) { s_logger.info("Stopping Statement Manager"); } return true; }
Source:
public PostResourceMethodInvokers() { this.invokers = new LinkedHashSet<>(); }

Target:
public PostResourceMethodInvokers() { this.invokers = new ArrayList<>(); }
Source:
private boolean shouldModifyIndexes(FlagAffectedCommand command, InvocationContext ctx, Object key, Object value) { if (indexingMode != null) { return indexingMode.shouldModifyIndexes(command, ctx, distributionManager, rpcManager, key); } if (isManualIndexing) return false; CacheMode cacheMode = cacheConfiguration.clustering().cacheMode(); if (!cacheMode.isClustered()) return true; if (value == null) return cacheMode.isReplicated() || ctx.isOriginLocal(); return IndexModificationStrategy.ALL.shouldModifyIndexes(command, ctx, distributionManager, rpcManager, key); }

Target:
private boolean shouldModifyIndexes(FlagAffectedCommand command, InvocationContext ctx, Object key, Object value) { if (isManualIndexing) return false; if (key == null || distributionManager == null) { return true; } DistributionInfo info = distributionManager.getCacheTopology().getDistribution(key); return info.isPrimary() || info.isWriteOwner() && (ctx.isInTxScope() || !ctx.isOriginLocal() || command != null && command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER)); }
Source:
protected Object handleObjectGet() throws Exception { String workspace = getAttribute("workspace"); ServiceInfo service; if (workspace != null) { WorkspaceInfo ws = geoServer.getCatalog().getWorkspaceByName(workspace); service = geoServer.getService(ws, clazz); } else { service = geoServer.getService(clazz); } if (service == null) { throw new RestletException("Service for workspace " + workspace + " does not exist", Status.CLIENT_ERROR_NOT_FOUND); } return service.clone(true); }

Target:
protected Object handleObjectGet() throws Exception { String workspace = getAttribute("workspace"); ServiceInfo service; if (workspace != null) { WorkspaceInfo ws = geoServer.getCatalog().getWorkspaceByName(workspace); service = geoServer.getService(ws, clazz); } else { service = geoServer.getService(clazz); } if (service == null) { throw new RestletException("Service for workspace " + workspace + " does not exist", Status.CLIENT_ERROR_NOT_FOUND); } return service; }
Source:
private boolean formatHDFS(boolean transactional) throws StorageException{ return format(transactional, INodeDataAccess.class, InMemoryInodeDataAccess.class, SmallOnDiskInodeDataAccess.class, MediumOnDiskInodeDataAccess.class, LargeOnDiskInodeDataAccess.class, BlockInfoDataAccess.class, LeaseDataAccess.class, LeasePathDataAccess.class, ReplicaDataAccess.class, ReplicaUnderConstructionDataAccess.class, InvalidateBlockDataAccess.class, ExcessReplicaDataAccess.class, PendingBlockDataAccess.class, CorruptReplicaDataAccess.class, UnderReplicatedBlockDataAccess.class, HdfsLeDescriptorDataAccess.class, DirectoryWithQuotaFeatureDataAccess.class, StorageIdMapDataAccess.class, BlockLookUpDataAccess.class, SafeBlocksDataAccess.class, MisReplicatedRangeQueueDataAccess.class, QuotaUpdateDataAccess.class, EncodingStatusDataAccess.class, BlockChecksumDataAccess.class, OngoingSubTreeOpsDataAccess.class, MetadataLogDataAccess.class, EncodingJobsDataAccess.class, RepairJobsDataAccess.class, UserDataAccess.class, GroupDataAccess.class, UserGroupDataAccess.class,VariableDataAccess.class, HashBucketDataAccess.class, StorageDataAccess.class, AceDataAccess.class, RetryCacheEntryDataAccess.class, CacheDirectiveDataAccess.class, CachePoolDataAccess.class, CachedBlockDataAccess.class, ActiveBlockReportsDataAccess.class, XAttrDataAccess.class, EncryptionZoneDataAccess.class, FileProvenanceDataAccess.class, FileProvXAttrBufferDataAccess.class, AppProvenanceDataAccess.class); }

Target:
private boolean formatHDFS(boolean transactional) throws StorageException{ return format(transactional, INodeDataAccess.class, InMemoryInodeDataAccess.class, SmallOnDiskInodeDataAccess.class, MediumOnDiskInodeDataAccess.class, LargeOnDiskInodeDataAccess.class, BlockInfoDataAccess.class, LeaseDataAccess.class, LeasePathDataAccess.class, ReplicaDataAccess.class, ReplicaUnderConstructionDataAccess.class, InvalidateBlockDataAccess.class, ExcessReplicaDataAccess.class, PendingBlockDataAccess.class, CorruptReplicaDataAccess.class, UnderReplicatedBlockDataAccess.class, HdfsLeDescriptorDataAccess.class, DirectoryWithQuotaFeatureDataAccess.class, StorageIdMapDataAccess.class, BlockLookUpDataAccess.class, SafeBlocksDataAccess.class, MisReplicatedRangeQueueDataAccess.class, QuotaUpdateDataAccess.class, EncodingStatusDataAccess.class, BlockChecksumDataAccess.class, OngoingSubTreeOpsDataAccess.class, MetadataLogDataAccess.class, EncodingJobsDataAccess.class, RepairJobsDataAccess.class, UserDataAccess.class, GroupDataAccess.class, UserGroupDataAccess.class,VariableDataAccess.class, HashBucketDataAccess.class, StorageDataAccess.class, AceDataAccess.class, RetryCacheEntryDataAccess.class, CacheDirectiveDataAccess.class, CachePoolDataAccess.class, CachedBlockDataAccess.class, ActiveBlockReportsDataAccess.class, XAttrDataAccess.class, EncryptionZoneDataAccess.class, FileProvenanceDataAccess.class, FileProvXAttrBufferDataAccess.class); }
Source:
private double[] getVolatilityAdjoint(final EuropeanVanillaOption option, final double forward, final SABRFormulaData data) { if (_sabrFunction instanceof SABRHaganVolatilityFunction) { return ((SABRHaganVolatilityFunction) _sabrFunction).getVolatilityAdjoint(option, forward, data); } throw new NotImplementedException(); }

Target:
private double[] getVolatilityAdjoint(final EuropeanVanillaOption option, final double forward, final SABRFormulaData data) { VolatilityFunctionProvider<SABRFormulaData> sabrFunction = getVolatilityFunction(); if (sabrFunction instanceof SABRHaganVolatilityFunction) { return ((SABRHaganVolatilityFunction) sabrFunction).getVolatilityAdjoint(option, forward, data); } Function1D<SABRFormulaData, double[]> adjointFunction = sabrFunction.getVolatilityAdjointFunction(option, forward); return adjointFunction.evaluate(data); }
Source:
public Series extract(RoviSeasonHistoryLine season) { Series series = new Series(); Optional<Publisher> parentPublisher = Optional.absent(); try { parentPublisher = parentPublisherCache.get(season.getSeasonProgramId()); } catch (ExecutionException e) { } if (parentPublisher.isPresent()) { series.setPublisher(parentPublisher.get()); } else { series.setPublisher(RoviConstants.DEFAULT_PUBLISHER); } series.setCanonicalUri(RoviUtils.canonicalUriForSeason(season.getSeasonProgramId())); String brandCanonicalUri = RoviUtils.canonicalUriForProgram(season.getSeriesId()); series.setParentRef(new ParentRef(brandCanonicalUri)); if (season.getSeasonName().isPresent()) { series.setTitle(season.getSeasonName().get()); } if (season.getSeasonNumber().isPresent()) { series.withSeriesNumber(season.getSeasonNumber().get()); } return series; }

Target:
public Series extract(RoviSeasonHistoryLine season) { Series series = new Series(); Optional<Publisher> parentPublisher = Optional.absent(); String parentCanonicalUri = canonicalUriForProgram(season.getSeriesId()); parentPublisher = parentPublisherCache.getUnchecked(parentCanonicalUri); if (parentPublisher.isPresent()) { series.setPublisher(parentPublisher.get()); } else { series.setPublisher(DEFAULT_PUBLISHER); } series.setCanonicalUri(canonicalUriForSeason(season.getSeasonProgramId())); series.setParentRef(new ParentRef(parentCanonicalUri)); if (season.getSeasonName().isPresent()) { series.setTitle(season.getSeasonName().get()); } if (season.getSeasonNumber().isPresent()) { series.withSeriesNumber(season.getSeasonNumber().get()); } return series; }
Source:
private static IncludedInDetail resolveBranches(RevCommit commit) throws Exception { Repository git = gitMgr.openRepository(change.getProject()); RevWalk rw = new RevWalk(git); return IncludedInResolver.resolve(git, rw, commit); }

Target:
private static IncludedInDetail resolveBranches(RevCommit commit) throws RepositoryNotFoundException, IOException, OrmException { Repository git = gitMgr.openRepository(change.getProject()); try { RevWalk rw = new RevWalk(git); try { return IncludedInResolver.resolve(git, rw, commit); } finally { rw.release(); } } finally { git.close(); } }
Source:
public void setPolicy(ComputationPolicy policy) { this.policy = policy; }

Target:
protected void setPolicy(ComputationPolicy policy) { this.policy = policy; }
Source:
private List<JarDto> getProjectExternalLibraries(ExternalLibrariesParameters params) { params.setProjectUri(LanguageServiceUtils.prefixURI(params.getProjectUri())); CompletableFuture<Object> result = executeCommand(GET_EXTERNAL_LIBRARIES_COMMAND, singletonList(params)); Type targetClassType = new TypeToken<ArrayList<Jar>>() {}.getType(); try { return gson.fromJson(gson.toJson(result.get(10, TimeUnit.SECONDS)), targetClassType); } catch (JsonSyntaxException | InterruptedException | ExecutionException | TimeoutException e) { throw new JsonRpcException(-27000, e.getMessage()); } }

Target:
private List<Jar> getProjectExternalLibraries(ExternalLibrariesParameters params) { params.setProjectUri(prefixURI(params.getProjectUri())); Type type = new TypeToken<ArrayList<Jar>>() {}.getType(); return doGetList(GET_EXTERNAL_LIBRARIES_COMMAND, params, type); }
Source:
public TopologyDescriptor(long topologyConfigId, @NonNull List<ClusterDescriptor> activeClusters, @NonNull List<ClusterDescriptor> standbyClusters, @NonNull List<ClusterDescriptor> invalidClusters) { this.topologyConfigId = topologyConfigId; this.activeClusters = new HashMap<>(); this.standbyClusters = new HashMap<>(); this.invalidClusters = new HashMap<>(); activeClusters.forEach(activeCluster -> this.activeClusters.put(activeCluster.getClusterId(), activeCluster)); standbyClusters.forEach(standbyCluster -> this.standbyClusters.put(standbyCluster.getClusterId(), standbyCluster)); invalidClusters.forEach(invalidCluster -> this.invalidClusters.put(invalidCluster.getClusterId(), invalidCluster)); }

Target:
public TopologyDescriptor(long topologyConfigId, @NonNull List<ClusterDescriptor> activeClusters, @NonNull List<ClusterDescriptor> standbyClusters, @NonNull List<ClusterDescriptor> invalidClusters) { this(topologyConfigId, activeClusters, standbyClusters); invalidClusters.forEach(invalidCluster -> this.invalidClusters.put(invalidCluster.getClusterId(), invalidCluster)); }
Source:
private List<? extends ParameterValue> filter(List<ParameterValue> parameters) { if (this.run == null) { return parameters; } if (this.parameterDefinitionNames == null) { return parameters; } String shouldKeepFlag = SystemProperties.getString(KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME); if ("true".equalsIgnoreCase(shouldKeepFlag)) { return parameters; } List<ParameterValue> filteredParameters = new ArrayList<ParameterValue>(); for (ParameterValue v : this.parameters) { if (this.parameterDefinitionNames.contains(v.getName()) || isSafeParameter(v.getName())) { filteredParameters.add(v); } else if (!"false".equalsIgnoreCase(shouldKeepFlag)) { LOGGER.log(Level.WARNING, "Skipped parameter `{0}` as it is undefined on `{1}`. Set `-D{2}=true` to allow " + "undefined parameters to be injected as environment variables or `-D{3}=[comma-separated list]` to whitelist specific parameter names, " + "even though it represents a security breach or `-D{2}=false` to no longer show this message.", new Object { v.getName(), run.getParent().getFullName(), KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME, SAFE_PARAMETERS_SYSTEM_PROPERTY_NAME }); } } return filteredParameters; }

Target:
private List<? extends ParameterValue> filter(List<ParameterValue> parameters) { if (this.run == null) { return parameters; } if (this.parameterDefinitionNames == null) { return parameters; } Boolean shouldKeepFlag = SystemProperties.optBoolean(KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME); if (shouldKeepFlag != null && shouldKeepFlag.booleanValue()) { return parameters; } List<ParameterValue> filteredParameters = new ArrayList<ParameterValue>(); for (ParameterValue v : this.parameters) { if (this.parameterDefinitionNames.contains(v.getName()) || isSafeParameter(v.getName())) { filteredParameters.add(v); } else if (shouldKeepFlag == null) { LOGGER.log(Level.WARNING, "Skipped parameter `{0}` as it is undefined on `{1}`. Set `-D{2}=true` to allow " + "undefined parameters to be injected as environment variables or `-D{3}=[comma-separated list]` to whitelist specific parameter names, " + "even though it represents a security breach or `-D{2}=false` to no longer show this message.", new Object { v.getName(), run.getParent().getFullName(), KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME, SAFE_PARAMETERS_SYSTEM_PROPERTY_NAME }); } } return filteredParameters; }
Source:
public static String convertToJson(Listing listing) { StringBuilder sb = new StringBuilder("{"); sb.append("\"id\" : ").append(listing.id).append(","); sb.append("\"supplierId\" : ").append(listing.supplierId).append(","); sb.append("\"lot\" : \"").append(listing.lot).append("\","); sb.append("\"title\" : \"").append(listing.title).append("\","); sb.append("\"lastUpdated\" : \"").append(listing.getLastUpdated()).append("\","); sb.append("\"lastUpdatedByEmail\" : \"").append(listing.lastUpdatedEmail).append("\","); sb.append("\"lastCompleted\" : \"").append(listing.getLastCompleted()).append("\","); sb.append("\"lastCompletedByEmail\" : \"").append(listing.lastCompletedByEmail).append("\","); for (Page page : listing.completedPages) { sb.append(getPageJSON(page)); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } sb.append("}"); return sb.toString(); }

Target:
public static String convertToJson(Listing listing) { StringBuilder sb = new StringBuilder("{"); sb.append("\"id\" : ").append(listing.id).append(","); sb.append("\"supplierId\" : ").append(listing.supplierId).append(","); sb.append("\"lot\" : ").append(gson.toJson(listing.lot)).append(","); sb.append("\"title\" : ").append(gson.toJson(listing.title)).append(","); sb.append("\"lastUpdated\" : ").append(gson.toJson(listing.getLastUpdated())).append(","); sb.append("\"lastUpdatedByEmail\" : ").append(gson.toJson(listing.lastUpdatedEmail)).append(","); sb.append("\"lastCompleted\" : ").append(gson.toJson(listing.getLastCompleted())).append(","); sb.append("\"lastCompletedByEmail\" : ").append(gson.toJson(listing.lastCompletedByEmail)).append(","); for (Page page : listing.completedPages) { sb.append(getPageJSON(page)); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } sb.append("}"); return sb.toString(); }
Source:
public static Collection<Object[]> data() throws Exception { String localEpoch = ((new Date(0)).toInstant()) .atZone(ZoneId.systemDefault()) .truncatedTo(ChronoUnit.SECONDS) .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); return Arrays.asList(new Object[][] { { getPollerResponse(), "<?xml version=\"1.0\"?>\n" + "<poller-response>" + "<poll-status code=\"1\" name=\"Up\" time=\"" + localEpoch + "\"/>" + "</poller-response>" } }); }

Target:
public static Collection<Object[]> data() throws Exception { return Arrays.asList(new Object[][] { { getPollerResponse(), "<?xml version=\"1.0\"?>\n" + "<poller-response>" + "<poll-status code=\"1\" name=\"Up\" time=\"" + StringUtils.iso8601OffsetString(new Date(0), ZoneId.systemDefault(), ChronoUnit.SECONDS) + "\"/>" + "</poller-response>" } }); }
Source:
public int hashCode() { int hash = 17; hash = hash * 31 + Objects.hashCode(_numeratorUnits); hash = hash * 31 + Objects.hashCode(_denominatorUnits); return hash; }

Target:
public int hashCode() { return Objects.hash(_numeratorUnits, _denominatorUnits); }
Source:
protected void initServConf() { regConfForProvider = new RegistryConfig(); regConfForService = new RegistryConfig(); provConf = new ProviderConfig(); protoConfForProvider = new ProtocolConfig("mockprotocol"); protoConfForService = new ProtocolConfig("mockprotocol"); methodConfForService = new MethodConfig(); servConf = new ServiceConfig<DemoService>(); servConf.setApplication(application); provConf.setRegistry(regConfForProvider); servConf.setRegistry(regConfForService); provConf.setProtocols(new ArrayList<>(Arrays.asList(new ProtocolConfig[]{protoConfForProvider}))); servConf.setProtocols(new ArrayList<>(Arrays.asList(new ProtocolConfig[]{protoConfForService}))); servConf.setMethods(Arrays.asList(new MethodConfig[]{methodConfForService})); servConf.setProvider(provConf); servConf.setRef(demoService); servConf.setInterfaceClass(DemoService.class); methodConfForService.setName("sayName"); regConfForService.setAddress("127.0.0.1:9090"); regConfForService.setProtocol("mockregistry"); application.setName("ConfigTests"); }

Target:
protected void initServConf() { regConfForProvider = new RegistryConfig(); regConfForService = new RegistryConfig(); provConf = new ProviderConfig(); protoConfForProvider = new ProtocolConfig("mockprotocol"); protoConfForService = new ProtocolConfig("mockprotocol"); methodConfForService = new MethodConfig(); servConf = new ServiceConfig<DemoService>(); servConf.setApplication(application); provConf.setRegistry(regConfForProvider); servConf.setRegistry(regConfForService); provConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForProvider))); servConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForService))); servConf.setMethods(Arrays.asList(new MethodConfig[]{methodConfForService})); servConf.setProvider(provConf); servConf.setRef(demoService); servConf.setInterfaceClass(DemoService.class); methodConfForService.setName("sayName"); regConfForService.setAddress("127.0.0.1:9090"); regConfForService.setProtocol("mockregistry"); application.setName("ConfigTests"); }
Source:
public Response updateStudentAddress( @PathParam("STUDENTID") Long studentId, @PathParam("ID") Long id, fi.otavanopisto.pyramus.rest.model.Address body ) { Student student = studentController.findStudentById(studentId); if (student == null) { return Response.status(Status.NOT_FOUND).build(); } if (student.getArchived()) { return Response.status(Status.NOT_FOUND).build(); } if (!restSecurity.hasPermission( new String[] { StudentPermissions.UPDATE_STUDENTADDRESS }, student) && !restSecurity.hasPermission( new String[] { PersonPermissions.PERSON_OWNER }, student.getPerson() )) { return Response.status(Status.FORBIDDEN).build(); } Address address = commonController.findAddressById(id); if (address == null) { return Response.status(Status.NOT_FOUND).build(); } if (!address.getContactInfo().getId().equals(student.getContactInfo().getId())) { return Response.status(Status.NOT_FOUND).build(); } ContactType contactType = commonController.findContactTypeById(body.getContactTypeId()); address = studentController.updateStudentAddress( address, contactType, body.getDefaultAddress(), body.getName(), body.getStreetAddress(), body.getPostalCode(), body.getCity(), body.getCountry()); return Response.ok(objectFactory.createModel(address)).build(); }

Target:
public Response updateStudentAddress( @PathParam("STUDENTID") Long studentId, @PathParam("ID") Long id, fi.otavanopisto.pyramus.rest.model.Address body ) { Student student = studentController.findStudentById(studentId); if (student == null) { return Response.status(Status.NOT_FOUND).build(); } if (student.getArchived()) { return Response.status(Status.NOT_FOUND).build(); } if (!restSecurity.hasPermission( new String[] { StudentPermissions.UPDATE_STUDENTADDRESS }, student) && !restSecurity.hasPermission( new String[] { StudentPermissions.STUDENT_OWNER }, student.getPerson() )) { return Response.status(Status.FORBIDDEN).build(); } Address address = commonController.findAddressById(id); if (address == null) { return Response.status(Status.NOT_FOUND).build(); } if (!address.getContactInfo().getId().equals(student.getContactInfo().getId())) { return Response.status(Status.NOT_FOUND).build(); } ContactType contactType = commonController.findContactTypeById(body.getContactTypeId()); address = studentController.updateStudentAddress( address, contactType, body.getDefaultAddress(), body.getName(), body.getStreetAddress(), body.getPostalCode(), body.getCity(), body.getCountry()); return Response.ok(objectFactory.createModel(address)).build(); }
Source:
private static void callCallbackForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, int notificationType, int arg1) { if (nri.messenger == null) { return; } Bundle bundle = new Bundle(); putParcelable(bundle, new NetworkRequest(nri.request)); Message msg = Message.obtain(); if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) { putParcelable(bundle, networkAgent.network); } switch (notificationType) { case ConnectivityManager.CALLBACK_LOSING: { msg.arg1 = arg1; break; } case ConnectivityManager.CALLBACK_CAP_CHANGED: { final NetworkCapabilities nc = new NetworkCapabilities(networkAgent.networkCapabilities); nc.setUids(null); putParcelable(bundle, nc); break; } case ConnectivityManager.CALLBACK_IP_CHANGED: { putParcelable(bundle, new LinkProperties(networkAgent.linkProperties)); break; } } msg.what = notificationType; msg.setData(bundle); try { if (VDBG) { String notification = ConnectivityManager.getCallbackName(notificationType); log("sending notification " + notification + " for " + nri.request); } nri.messenger.send(msg); } catch (RemoteException e) { loge("RemoteException caught trying to send a callback msg for " + nri.request); } }

Target:
private void callCallbackForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent, int notificationType, int arg1) { if (nri.messenger == null) { return; } Bundle bundle = new Bundle(); putParcelable(bundle, new NetworkRequest(nri.request)); Message msg = Message.obtain(); if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) { putParcelable(bundle, networkAgent.network); } switch (notificationType) { case ConnectivityManager.CALLBACK_LOSING: { msg.arg1 = arg1; break; } case ConnectivityManager.CALLBACK_CAP_CHANGED: { final NetworkCapabilities nc = getNetworkCapabilitiesInternal(networkAgent); putParcelable(bundle, nc); break; } case ConnectivityManager.CALLBACK_IP_CHANGED: { putParcelable(bundle, new LinkProperties(networkAgent.linkProperties)); break; } } msg.what = notificationType; msg.setData(bundle); try { if (VDBG) { String notification = ConnectivityManager.getCallbackName(notificationType); log("sending notification " + notification + " for " + nri.request); } nri.messenger.send(msg); } catch (RemoteException e) { loge("RemoteException caught trying to send a callback msg for " + nri.request); } }
Source:
public Integer getResourceMaxPartitionsPerInstance() { return _resourceMaxPartitionsPerInstance; }

Target:
public int getResourceMaxPartitionsPerInstance() { return _resourceMaxPartitionsPerInstance; }
Source:
protected void setCurrentUrl(DownloadUrlLink link) { widget.setVisible(true); String sshPort = "29418"; String sshAddr = Gerrit.getConfig().getSshdAddress(); int p = sshAddr.lastIndexOf(':'); if (p != -1 && !sshAddr.endsWith(":")) { sshPort = sshAddr.substring(p + 1); } StringBuilder cmd = new StringBuilder(); cmd.append("git clone "); cmd.append(link.getUrlData()); cmd.append(" && scp -p -P "); cmd.append(sshPort); cmd.append(" "); cmd.append(Gerrit.getUserAccount().getUserName()); cmd.append("@"); if (sshAddr.startsWith("*:") || p == -1) { cmd.append(Window.Location.getHostName()); } else { sshAddr = sshAddr.substring(0, p); } cmd.append(":hooks/commit-msg "); p = project.get().lastIndexOf('/'); if (p != -1) { cmd.append(project.get().substring(p + 1)); } else { cmd.append(project.get()); } cmd.append("/.git/hooks/"); copyLabel.setText(cmd.toString()); }

Target:
protected void setCurrentUrl(DownloadUrlLink link) { widget.setVisible(true); String sshPort = "29418"; String sshAddr = Gerrit.getConfig().getSshdAddress(); int p = sshAddr.lastIndexOf(':'); if (p != -1 && !sshAddr.endsWith(":")) { sshPort = sshAddr.substring(p + 1); } StringBuilder cmd = new StringBuilder(); cmd.append("git clone "); cmd.append(link.getUrlData()); cmd.append(" && scp -p -P "); cmd.append(sshPort); cmd.append(" "); cmd.append(Gerrit.getUserAccount().getUserName()); cmd.append("@"); if (sshAddr.startsWith("*:") || p == -1) { cmd.append(Window.Location.getHostName()); } else { cmd.append(sshAddr.substring(0, p)); } cmd.append(":hooks/commit-msg "); p = project.get().lastIndexOf('/'); if (p != -1) { cmd.append(project.get().substring(p + 1)); } else { cmd.append(project.get()); } cmd.append("/.git/hooks/"); copyLabel.setText(cmd.toString()); }