auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public JsonLoader(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; try { this.inputFormat = (FileInputFormat) Class.forName(inputFormatClassName).newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } catch (IllegalAccessException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } catch (ClassNotFoundException e) { throw new RuntimeException("Failed creating input format " + inputFormatClassName, e); } }

Target:
public JsonLoader(String inputFormatClassName) { this.inputFormatClassName = inputFormatClassName; }
Source:
public void addResult(Resource resource, Collection<String> metrics) { this.m_results.add(new Result(resource, metrics)); }

Target:
public void addResult(Resource resource, Collection<String> metrics) { this.results.add(new Result(resource, metrics)); }
Source:
public static boolean hasPermission(EntityPlayer player, String node) { return hasPermission(player.getGameProfile(), node, new PlayerContext(player)); }

Target:
public static boolean hasPermission(EntityPlayer player, String node) { Preconditions.checkNotNull(player, "Player can't be null!"); return hasPermission(player.getGameProfile(), node, new PlayerContext(player)); }
Source:
public static Response handleIntercept(Chain chain, Tmdb tmdb) throws IOException { Request request = chain.request(); if (!Tmdb.API_HOST.equals(request.url().host())) { return chain.proceed(request); } AuthenticationType type = null; HttpUrl.Builder urlBuilder = request.url().newBuilder(); urlBuilder.setEncodedQueryParameter(Tmdb.PARAM_API_KEY, tmdb.apiKey()); if (request.url().pathSegments().get(1).equals("account") || request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("account_states")) { type = AuthenticationType.ACCOUNT; } else if (request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("rating") || !request.method().toLowerCase().equals("get")) { type = determineAuthenticationType(urlBuilder, tmdb); } addSessionToQuery(urlBuilder, type, tmdb); urlBuilder.removeAllEncodedQueryParameters("authentication"); if (type != null) { urlBuilder.fragment(type.toString()); } Request.Builder builder = request.newBuilder(); builder.url(urlBuilder.build()); Response response = chain.proceed(builder.build()); if (!response.isSuccessful()) { String retryAfter = response.header("Retry-After"); if (retryAfter != null) { try { Integer retry = Integer.parseInt(retryAfter); Thread.sleep((int) ((retry + 0.5) * 1000)); return handleIntercept(chain,tmdb); } catch (Exception exc) { } } } handleErrors(response, tmdb); return response; }

Target:
public static Response handleIntercept(Chain chain, Tmdb tmdb) throws IOException { Request request = chain.request(); if (!Tmdb.API_HOST.equals(request.url().host())) { return chain.proceed(request); } AuthenticationType type = null; HttpUrl.Builder urlBuilder = request.url().newBuilder(); urlBuilder.setEncodedQueryParameter(Tmdb.PARAM_API_KEY, tmdb.apiKey()); if (request.url().pathSegments().get(1).equals("account") || request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("account_states")) { type = AuthenticationType.ACCOUNT; } else if (request.url().pathSegments().get(request.url().pathSegments().size() - 1).equals("rating") || !request.method().toLowerCase().equals("get")) { type = determineAuthenticationType(urlBuilder, tmdb); } addSessionToQuery(urlBuilder, type, tmdb); urlBuilder.removeAllEncodedQueryParameters("authentication"); if (type != null) { urlBuilder.fragment(type.toString()); } Request.Builder builder = request.newBuilder(); builder.url(urlBuilder.build()); Response response = chain.proceed(builder.build()); if (!response.isSuccessful()) { String retryAfter = response.header("Retry-After"); if (retryAfter != null) { try { Integer retry = Integer.parseInt(retryAfter); Thread.sleep((int) ((retry + 0.5) * 1000)); } catch (NumberFormatException | InterruptedException e) { return response; } return handleIntercept(chain,tmdb); } } handleErrors(response, tmdb); return response; }
Source:
public void setTaskDetailsData(final TaskSummary model, Date logDate) { removeCSSClass(humanTaskContainer, "hidden"); taskId.setTextContent(model.getId().toString()); createdOn.setTextContent(DateUtils.getDateTimeStr(model.getCreatedOn())); if (model.getCreatedBy().isEmpty()) { createdByLabel.setHidden(true); createdBy.setHidden(true); } else { createdBy.setTextContent(model.getCreatedBy()); } updatedOn.setTextContent(DateUtils.getDateTimeStr(logDate)); taskId.setTextContent(model.getId().toString()); taskStatus.setTextContent(new TaskStatusConverter().toWidgetValue(model.getTaskStatus())); if (model.getActualOwner().isEmpty()) { actualOwner.setTextContent(constants.NotClaimed()); } else { actualOwner.setTextContent(model.getActualOwner()); } description.setTextContent(model.getDescription()); }

Target:
public void setTaskDetailsData(final TaskSummary model, Date logDate) { removeCSSClass(humanTaskContainer, "hidden"); taskId.setTextContent(model.getId().toString()); createdOn.setTextContent(DateUtils.getDateTimeStr(model.getCreatedOn())); if (model.getCreatedBy() != null && !model.getCreatedBy().isEmpty()) { createdBy.setTextContent(model.getCreatedBy()); } else { createdByLabel.setHidden(true); createdBy.setHidden(true); } updatedOn.setTextContent(DateUtils.getDateTimeStr(logDate)); taskStatus.setTextContent(new TaskStatusConverter().toWidgetValue(model.getTaskStatus())); if (model.getActualOwner() != null && !model.getActualOwner().isEmpty()) { actualOwner.setTextContent(model.getActualOwner()); } else { actualOwner.setTextContent(constants.NotClaimed()); } description.setTextContent(model.getDescription()); }
Source:
protected void internalReceiveCommand(String itemName, Command command) { logger.debug( "internalReceiveCommand() is called! itemName {}, command {}", itemName, command); for (NeoHubBindingProvider provider : providers) { if (!provider.providesBindingFor(itemName)) { continue; } final String device = provider.getNeoStatDevice(itemName); switch (provider.getNeoStatProperty(itemName)) { case Away: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setAway(OnOffType.ON == onOffType, device); } break; case Standby: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setStandby(OnOffType.ON == onOffType, device); } default: break; } } }

Target:
protected void internalReceiveCommand(String itemName, Command command) { for (NeoHubBindingProvider provider : providers) { if (!provider.providesBindingFor(itemName)) { continue; } final String device = provider.getNeoStatDevice(itemName); switch (provider.getNeoStatProperty(itemName)) { case Away: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setAway(OnOffType.ON == onOffType, device); } break; case Standby: if (command instanceof OnOffType) { OnOffType onOffType = (OnOffType) command; createProtocol().setStandby(OnOffType.ON == onOffType, device); } default: break; } } }
Source:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { AddCinderDiskCommand addCinderDiskCommand = (AddCinderDiskCommand) command; Guid diskId = ((AddDiskParameters) addCinderDiskCommand.getParameters()).getDiskInfo().getId(); ImageStatus imageStatus = addCinderDiskCommand.getCinderBroker().getDiskStatus(diskId); DiskImage disk = (CinderDisk) DbFacade.getInstance().getDiskDao().get(diskId); if (imageStatus != null && imageStatus != disk.getImageStatus()) { switch (imageStatus) { case OK: setCommandEndStatus(command, false, status, childCmdIds); break; case ILLEGAL: setCommandEndStatus(command, true, status, childCmdIds); break; } } }

Target:
protected void childCommandsExecutionEnded(CommandBase<?> command, boolean anyFailed, List<Guid> childCmdIds, CommandExecutionStatus status, int completedChildren) { AddCinderDiskCommand<AddDiskParameters> addCinderDiskCommand = (AddCinderDiskCommand<AddDiskParameters>) command; Guid diskId = getDiskId(addCinderDiskCommand); ImageStatus imageStatus = addCinderDiskCommand.getCinderBroker().getDiskStatus(diskId); DiskImage disk = (CinderDisk) command.getDiskDao().get(diskId); if (imageStatus != null && imageStatus != disk.getImageStatus()) { switch (imageStatus) { case OK: setCommandEndStatus(command, false, status, childCmdIds); break; case ILLEGAL: setCommandEndStatus(command, true, status, childCmdIds); break; } } }
Source:
public AlarmNotificationsDto retrieveCurrentAlarmNotifications(final DlmsConnectionHolder conn) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress alarmFilterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); if (conn.hasDlmsMessageListener()) { conn.getDlmsMessageListener() .setDescription("SetAlarmNotifications retrieve current value, retrieve attribute: " + this.describeAttributes(alarmFilterValue)); } LOGGER.info( "Retrieving current alarm filter by issuing get request for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final GetResult getResult = conn.getConnection().get(alarmFilterValue); if (getResult == null) { throw new ProtocolAdapterException("No GetResult received while retrieving current alarm filter."); } return this.alarmNotifications(getResult.getResultData()); }

Target:
public AlarmNotificationsDto retrieveCurrentAlarmNotifications(final DlmsConnectionHolder conn) throws IOException, TimeoutException, ProtocolAdapterException { final AttributeAddress alarmFilterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); conn.getDlmsMessageListener() .setDescription("SetAlarmNotifications retrieve current value, retrieve attribute: " + JdlmsObjectToStringUtil.describeAttributes(alarmFilterValue)); LOGGER.info( "Retrieving current alarm filter by issuing get request for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final GetResult getResult = conn.getConnection().get(alarmFilterValue); if (getResult == null) { throw new ProtocolAdapterException("No GetResult received while retrieving current alarm filter."); } return this.alarmNotifications(getResult.getResultData()); }
Source:
protected void undeleteBlob(final String blobIdStr, final String serviceId, FutureResult<Void> futureResult, final Callback<Void> callback) { if (isMaybeMetadataBlob(blobIdStr)) { Callback<GetBlobResultInternal> internalCallback = (GetBlobResultInternal result, Exception exception) -> { if (exception != null) { completeOperation(futureResult, callback, null, exception, false); } else if (result.getBlobResult != null) { exception = new RouterException( "GET blob call returned the blob instead of just the store keys (before TTL update)", RouterErrorCode.UnexpectedInternalError); completeOperation(futureResult, callback, null, exception, false); } else { List<String> blobIdStrs = new ArrayList<>(); blobIdStrs.add(blobIdStr); if (result.storeKeys != null) { result.storeKeys.forEach(key -> blobIdStrs.add(key.getID())); } currentOperationsCount.addAndGet(blobIdStrs.size()); doUndeleteOperation(blobIdStrs, serviceId, futureResult, callback); } }; GetBlobOptions options = new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.All) .getOption(GetOption.None) .build(); GetBlobOptionsInternal optionsInternal = new GetBlobOptionsInternal(options, true, routerMetrics.ageAtTtlUpdate); try { getBlob(blobIdStr, optionsInternal, internalCallback); } catch (RouterException e) { completeUpdateBlobTtlOperation(e, futureResult, callback); } } else { routerMetrics.skippedGetBlobCount.inc(); doUndeleteOperation(Collections.singletonList(blobIdStr), serviceId, futureResult, callback); } }

Target:
protected void undeleteBlob(final String blobIdStr, final String serviceId, FutureResult<Void> futureResult, final Callback<Void> callback) { doOperationTowardsMaybeCompositeBlob(blobIdStr, futureResult, callback, new CompositeBlobOperationHelper("UNDELETE", GetOption.Include_Deleted_Blobs, routerMetrics.ageAtUndelete, (blobIds) -> { doUndeleteOperation(blobIds, serviceId, futureResult, callback); }, (exception) -> { completeUndeleteBlobOperation(exception, futureResult, callback); })); }
Source:
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientProviderBuilder authorizedClientProviderBuilder = OAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken(); if (this.accessTokenResponseClient != null) { authorizedClientProviderBuilder.clientCredentials(configurer -> configurer.accessTokenResponseClient(this.accessTokenResponseClient)); } OAuth2AuthorizedClientProvider authorizedClientProvider = authorizedClientProviderBuilder.build(); DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); argumentResolvers.add(new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager)); } }

Target:
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { if (this.clientRegistrationRepository != null && this.authorizedClientRepository != null) { OAuth2AuthorizedClientProviderBuilder authorizedClientProviderBuilder = OAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken(); if (this.accessTokenResponseClient != null) { authorizedClientProviderBuilder.clientCredentials(configurer -> configurer.accessTokenResponseClient(this.accessTokenResponseClient)); } else { authorizedClientProviderBuilder.clientCredentials(); } OAuth2AuthorizedClientProvider authorizedClientProvider = authorizedClientProviderBuilder.build(); DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( this.clientRegistrationRepository, this.authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); argumentResolvers.add(new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager)); } }
Source:
public double getMiningFeeInSatoshisPerByte() { return CoinUtil.getFeePerByte(miningFee, txSize); }

Target:
public double getMiningFeeInSatoshisPerByte() { return CoinUtil.getFeePerVbyte(miningFee, txSize); }
Source:
private static DetailAST getWhitespaceFollowedNode(DetailAST ast) { final DetailAST whitespaceFollowedAst; switch (ast.getType()) { case TokenTypes.TYPECAST: whitespaceFollowedAst = ast.findFirstToken(TokenTypes.RPAREN); break; case TokenTypes.ARRAY_DECLARATOR: whitespaceFollowedAst = getArrayDeclaratorPreviousElement(ast); break; case TokenTypes.INDEX_OP: final DetailAST resultAst = getIndexOpPreviousElement(ast); if (resultAst == null) { whitespaceFollowedAst = ast; } else { whitespaceFollowedAst = resultAst; } break; default: whitespaceFollowedAst = ast; } return whitespaceFollowedAst; }

Target:
private static DetailAST getWhitespaceFollowedNode(DetailAST ast) { final DetailAST whitespaceFollowedAst; switch (ast.getType()) { case TokenTypes.TYPECAST: whitespaceFollowedAst = ast.findFirstToken(TokenTypes.RPAREN); break; case TokenTypes.ARRAY_DECLARATOR: whitespaceFollowedAst = getArrayDeclaratorPreviousElement(ast); break; case TokenTypes.INDEX_OP: whitespaceFollowedAst = getIndexOpPreviousElement(ast); break; default: whitespaceFollowedAst = ast; } return whitespaceFollowedAst; }
Source:
private Entry<String, CycleDto> createZapiCycleIfNoneExist(ProjectDto targetProjectDto, VersionDto targetVersionDto) { final Optional<Entry<String, CycleDto>> targetCycleEntry = getListOfCycles(targetProjectDto.id, targetVersionDto.id); targetCycleEntry.ifPresent(cycleDtoEntry -> logger.info(() -> format("Found in Zephyr; cycle: \"{0}\" with cycleId: \"{1}\"", Property.ZAPI_CYCLE_REGEX.getValue(), cycleDtoEntry.getKey()))); return targetCycleEntry.orElseGet(() -> { final String createdCycleId = jiraService.cycle().createNewCycle( CreateNewCycleDto.newBuilder().cycleLightDto( CycleLightDto.newBuilder() .versionId(targetVersionDto.id) .projectId(targetProjectDto.id) .name(Property.ZAPI_CYCLE_REGEX.getValue()) .build()) .build()).id; logger.info(() -> format("Created in Zephyr; cycle: \"{0}\" with cycleId: \"{1}\"", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId)); return getListOfCycles(targetProjectDto.id, targetVersionDto.id) .orElseThrow(() -> new NotFoundException(format("Unable to find in JIRA newly created" + " cycle: \"{0}\" with cycleId: \"{1}\"; cycle creation may have failed", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId))); }); }

Target:
private Entry<String, CycleDto> createZapiCycleIfNoneExist( ProjectDto targetProjectDto, VersionDto targetVersionDto) { final Optional<Entry<String, CycleDto>> targetCycleEntry = getListOfCycles(targetProjectDto.id, targetVersionDto.id); targetCycleEntry.ifPresent(cycleDtoEntry -> logger.info(() -> format("Found in Zephyr; [ cycle: %s ] with [ cycleId: %s ]", Property.ZAPI_CYCLE_REGEX.getValue(), cycleDtoEntry.getKey()))); return targetCycleEntry.orElseGet(() -> { final String createdCycleId = jiraService.cycle().createNewCycle( CreateNewCycleDto.newBuilder().cycleLightDto( CycleLightDto.newBuilder() .versionId(targetVersionDto.id) .projectId(targetProjectDto.id) .name(Property.ZAPI_CYCLE_REGEX.getValue()) .build()) .build()).id; logger.info(() -> format("Created in Zephyr; [ cycle: %s ] with [ cycleId: %s ]", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId)); return getListOfCycles(targetProjectDto.id, targetVersionDto.id) .orElseThrow(() -> new NotFoundException(format("Unable to find in JIRA newly created" + " [ cycle: %s ] with [ cycleId: %s ]. Cycle creation may have failed", Property.ZAPI_CYCLE_REGEX.getValue(), createdCycleId))); }); }
Source:
private static void printHelp() throws IOException { final StringBuilder sb = new StringBuilder(); sb.append("============================\n"); sb.append("Please provide the directory path to a configuration file!"); sb.append("\n"); sb.append("For an example, see: <LINK_0>"); sb.append("src/test/resources/spring/migration-bean.xml"); sb.append("\n\n"); sb.append("For detailed instructions, see: <LINK_0>README.md"); sb.append("\n"); sb.append("============================\n"); System.out.println(sb.toString()); }

Target:
private static void printHelp() throws IOException { final StringBuilder sb = new StringBuilder(); sb.append("============================\n"); sb.append("Please provide the directory path to a configuration file!"); sb.append("\n"); sb.append("See: <LINK_0>"); sb.append("src/main/resources/spring/migration-bean.xml"); sb.append("\n\n"); sb.append("The configuration file should contain the following (with appropriate values):"); sb.append("\n"); sb.append("~~~~~~~~~~~~~~\n"); final ClassPathResource resource = new ClassPathResource("spring/migration-bean.xml"); final InputStream example = resource.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(example)); String line = reader.readLine(); while (null != line) { sb.append(line); sb.append("\n"); line = reader.readLine(); } sb.append("~~~~~~~~~~~~~~\n\n"); sb.append("See top of this output for details.\n"); sb.append("============================\n"); System.out.println(sb.toString()); }
Source:
public Collection<String> getAliases(final KeyStore keyStore) throws ScriptSignatureException { try { if (keyStore != null) return Collections.list(keyStore.aliases()); } catch (KeyStoreException e) { throw new ScriptSignatureException("Keystore not initialized properly. Try again.", e); } throw new ScriptSignatureException("Keystore not initialized properly. Try again.", null); }

Target:
public Collection<String> getAliases(final KeyStore keyStore) { try { if (keyStore != null) return Collections.list(keyStore.aliases()); } catch (KeyStoreException e) { return null; } return null; }
Source:
public Status delete(String table, String key) { try { UpdateResponse res = (cloudMode) ? cloudClient.deleteById(table, key, 1000) : httpClient.deleteById(table, key, 1000); if (res.getStatus() > 0) { throw new Exception(""); } return Status.OK; } catch (Exception e) { e.printStackTrace(); } return Status.ERROR; }

Target:
public Status delete(String table, String key) { try { UpdateResponse response; if (batchMode) { response = client.deleteById(table, key, commitTime); } else { response = client.deleteById(table, key); client.commit(table); } return checkStatus(response.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }
Source:
private Set<String> findQueryParams() { Set<String> result = new HashSet<>(); String query = this.request.getQueryString(); String[] splitQuery = StringUtils.split(query, "&"); if(splitQuery == null && query != null) { splitQuery = new String[]{query}; } if (splitQuery != null) { for (String value : splitQuery) { if (value.contains("=")) { value = value.substring(0, value.indexOf("=")); } result.add(value); } } return result; }

Target:
private Set<String> findQueryParams() { Set<String> result = new HashSet<>(); String query = this.request.getQueryString(); if (query != null) { for (String value : StringUtils.tokenizeToStringArray(query, "&")) { if (value.contains("=")) { value = value.substring(0, value.indexOf("=")); } result.add(value); } } return result; }
Source:
protected void preprocess(Container container) { try { ClassLoader parentCl = container.getParentClassLoader(); File homeDir = resolveHomeDirectory(); File bundles = new File(homeDir, "bundles"); File lib = new File(homeDir, "lib"); File deployerJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-runtime-deploy"); File commonJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-common"); if (deployerJar == null || commonJar == null) { System.out.println("Deployer and/or common JAR (nuxeo-runtime-deploy* | nuxeo-common*) not found in " + bundles); return; } ArrayList<URL> urls = new ArrayList<URL>(); File[] files = lib.listFiles(); if (files != null) { for (File f : files) { if (f.getPath().endsWith(".jar")) { urls.add(f.toURI().toURL()); } } } files = bundles.listFiles(); if (files != null) { for (File f : files) { if (f.getPath().endsWith(".jar")) { urls.add(f.toURI().toURL()); } } } urls.add(homeDir.toURI().toURL()); urls.add(new File(homeDir, "config").toURI().toURL()); try (URLClassLoader cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentCl)) { System.out.println("# Running Nuxeo Preprocessor ..."); Class<?> klass = cl.loadClass("org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor"); Method main = klass.getMethod("main", String[].class); main.invoke(null, new Object[] { new String[] { homeDir.getAbsolutePath() } }); System.out.println("# Preprocessing done."); } } catch (IOException | ReflectiveOperationException e) { throw new RuntimeException("Failed to handle event", e); } }

Target:
protected void preprocess(Container container) { try { ClassLoader parentCl = container.getParentClassLoader(); File homeDir = resolveHomeDirectory(); File bundles = new File(homeDir, "bundles"); File lib = new File(homeDir, "lib"); File deployerJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-runtime-deploy"); File commonJar = FrameworkBootstrap.findFileStartingWidth(bundles, "nuxeo-common"); if (deployerJar == null || commonJar == null) { System.out.println("Deployer and/or common JAR (nuxeo-runtime-deploy* | nuxeo-common*) not found in " + bundles); return; } List<URL> urls = new ArrayList<>(); try (Stream<Path> p1 = Files.list(lib.toPath()); Stream<Path> p2 = Files.list(bundles.toPath())) { Stream.concat(p1, p2).filter(p -> p.endsWith(".jar")).map(this::toURL).forEach(urls::add); } urls.add(homeDir.toURI().toURL()); urls.add(new File(homeDir, "config").toURI().toURL()); try (URLClassLoader cl = new URLClassLoader(urls.toArray(new URL[0]), parentCl)) { System.out.println("# Running Nuxeo Preprocessor ..."); Class<?> klass = cl.loadClass("org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor"); Method main = klass.getMethod("main", String[].class); main.invoke(null, new Object[] { new String[] { homeDir.getAbsolutePath() } }); System.out.println("# Preprocessing done."); } } catch (IOException | ReflectiveOperationException | IllegalStateException e) { throw new RuntimeException("Failed to handle event", e); } }
Source:
private Set<String> validateComponents(Devfile devfile) throws DevfileFormatException { Set<String> definedAliases = new HashSet<>(); Component editorComponent = null; Map<String, Set<String>> idsPerComponentType = new HashMap<>(); for (Component component : devfile.getComponents()) { if (component.getAlias() != null && !definedAliases.add(component.getAlias())) { throw new DevfileFormatException( format("Duplicate component alias found:'%s'", component.getAlias())); } if (!idsPerComponentType .computeIfAbsent(component.getType(), __ -> new HashSet<>()) .add(getIdentifiableComponentName(component))) { throw new DevfileFormatException( format( "There are multiple components '%s' of type '%s' that cannot be uniquely" + " identified. Please add aliases that would distinguish the components.", getIdentifiableComponentName(component), component.getType())); } switch (component.getType()) { case EDITOR_COMPONENT_TYPE: if (editorComponent != null) { throw new DevfileFormatException( format( "Multiple editor components found: '%s', '%s'", getIdentifiableComponentName(editorComponent), getIdentifiableComponentName(component))); } editorComponent = component; break; case PLUGIN_COMPONENT_TYPE: case KUBERNETES_COMPONENT_TYPE: case OPENSHIFT_COMPONENT_TYPE: case DOCKERIMAGE_COMPONENT_TYPE: break; default: throw new DevfileFormatException( format( "Unsupported component '%s' type provided:'%s'", getIdentifiableComponentName(component), component.getType())); } } return definedAliases; }

Target:
private Set<String> validateComponents(Devfile devfile) throws DevfileFormatException { Set<String> definedAliases = new HashSet<>(); Component editorComponent = null; Map<String, Set<String>> idsPerComponentType = new HashMap<>(); for (Component component : devfile.getComponents()) { if (component.getAlias() != null && !definedAliases.add(component.getAlias())) { throw new DevfileFormatException( format("Duplicate component alias found:'%s'", component.getAlias())); } if (!idsPerComponentType .computeIfAbsent(component.getType(), __ -> new HashSet<>()) .add(getIdentifiableComponentName(component))) { throw new DevfileFormatException( format( "There are multiple components '%s' of type '%s' that cannot be uniquely" + " identified. Please add aliases that would distinguish the components.", getIdentifiableComponentName(component), component.getType())); } switch (component.getType()) { case EDITOR_COMPONENT_TYPE: if (editorComponent != null) { throw new DevfileFormatException( format( "Multiple editor components found: '%s', '%s'", getIdentifiableComponentName(editorComponent), getIdentifiableComponentName(component))); } editorComponent = component; break; case PLUGIN_COMPONENT_TYPE: case KUBERNETES_COMPONENT_TYPE: case OPENSHIFT_COMPONENT_TYPE: case DOCKERIMAGE_COMPONENT_TYPE: break; default: throw new DevfileFormatException( format( "One of the components has unsupported component type: '%s'", component.getType())); } } return definedAliases; }
Source:
public void onResponse(Map<String, Object> response) { try { infoReturn = new VDSInfoReturn(response); proceedProxyReturnValue(); vdsBrokerObjectsBuilder.updateVDSStatisticsData(getVds(), infoReturn.info); vdsBrokerObjectsBuilder.checkTimeDrift(getVds(), infoReturn.info); getParameters().getCallback().onResponse(Collections.singletonMap("result", getVDSReturnValue())); } catch (Exception ex) { getParameters().getCallback().onFailure(ex); } }

Target:
public void onResponse(Map<String, Object> response) { try { infoReturn = new VDSInfoReturn(response); proceedProxyReturnValue(); vdsBrokerObjectsBuilder.updateVDSStatisticsData(getVds(), infoReturn.info); vdsBrokerObjectsBuilder.checkTimeDrift(getVds(), infoReturn.info); multipathHealthHandler.handleMultipathHealthReport(getVds(), infoReturn.info); getParameters().getCallback().onResponse(Collections.singletonMap("result", getVDSReturnValue())); } catch (Exception ex) { getParameters().getCallback().onFailure(ex); } }
Source:
public void run() { while (true) { try { Status status = MongoDBRiverHelper.getRiverStatus(this.mongoDBRiver.esClient, this.definition.getRiverName()); if (status != this.context.getStatus()) { if (status == Status.RUNNING) { MongoDBRiver.logger.trace("About to start river: {}", this.definition.getRiverName()); mongoDBRiver.internalStartRiver(); } else if (status == Status.STOPPED) { MongoDBRiver.logger.info("About to stop river: {}", this.definition.getRiverName()); mongoDBRiver.internalStopRiver(); } } Thread.sleep(1000L); } catch (InterruptedException e) { MongoDBRiver.logger.debug("Status thread interrupted", e, (Object) null); Thread.currentThread().interrupt(); break; } } }

Target:
public void run() { while (true) { try { Status status = MongoDBRiverHelper.getRiverStatus(this.mongoDBRiver.esClient, this.definition.getRiverName()); if (status != this.context.getStatus()) { if (status == Status.RUNNING && this.context.getStatus() != Status.STARTING) { logger.trace("About to start river: {}", this.definition.getRiverName()); mongoDBRiver.internalStartRiver(); } else if (status == Status.STOPPED) { logger.info("About to stop river: {}", this.definition.getRiverName()); mongoDBRiver.internalStopRiver(); } } Thread.sleep(1000L); } catch (InterruptedException e) { logger.debug("Status thread interrupted", e, (Object) null); Thread.currentThread().interrupt(); break; } } }
Source:
public String readableString() { StringBuilder poolsToStringBuilder = new StringBuilder(); for (Map.Entry<ResourceType<?>, ResourcePool> poolEntry : pools.entrySet()) { poolsToStringBuilder .append(poolEntry.getKey()) .append(": ") .append(poolEntry.getValue()) .append("\n "); } if(!pools.isEmpty()) { poolsToStringBuilder.delete(poolsToStringBuilder.length() -9, poolsToStringBuilder.length()); } return "pools : " + "\n " + poolsToStringBuilder.toString(); }

Target:
public String readableString() { Map<ResourceType<?>, ResourcePool> sortedPools = new TreeMap<ResourceType<?>, ResourcePool>( new Comparator<ResourceType<?>>() { @Override public int compare(ResourceType<?> o1, ResourceType<?> o2) { return o2.getTierHeight() - o1.getTierHeight(); } } ); sortedPools.putAll(pools); StringBuilder poolsToStringBuilder = new StringBuilder(); for (Map.Entry<ResourceType<?>, ResourcePool> poolEntry : sortedPools.entrySet()) { poolsToStringBuilder .append(poolEntry.getKey()) .append(": ") .append("\n ") .append("size: ") .append(poolEntry.getValue() instanceof HumanReadable ? ((HumanReadable) poolEntry.getValue()).readableString() : poolEntry.getValue()) .append("\n ") .append("tierHeight: ") .append(poolEntry.getKey().getTierHeight()) .append("\n "); } if (poolsToStringBuilder.length() > 4) { poolsToStringBuilder.delete(poolsToStringBuilder.length() - 5, poolsToStringBuilder.length()); } return "pools: " + "\n " + poolsToStringBuilder.toString(); }
Source:
public boolean hasOpenSession() { boolean isOpen = fSessions.size() > 0; if (isOpen) { for (Session session : fSessions) { isOpen &= session.isConnected(); } } if (!isOpen) { close(); } return isOpen; }

Target:
public boolean hasOpenSession() { boolean hasOpenSession = fSessions.size() > 0; if (hasOpenSession) { for (Session session : fSessions) { hasOpenSession &= session.isConnected(); } } if (!hasOpenSession) { close(); } return hasOpenSession; }
Source:
private PlanNodeStatsEstimate getGroupStats(GroupReference groupReference) { int group = groupReference.getGroupId(); Memo memo = this.memo.orElseThrow(IllegalStateException::new); Optional<PlanNodeStatsEstimate> stats = memo.getStats(group); if (stats.isPresent()) { return stats.get(); } PlanNodeStatsEstimate groupStats = statsCalculator.calculateStats(memo.getNode(group), this, lookup, session, types.get()); verify(!memo.getStats(group).isPresent(), "Group stats already set"); memo.storeStats(group, groupStats); return groupStats; }

Target:
private PlanNodeStatsEstimate getGroupStats(GroupReference groupReference) { int group = groupReference.getGroupId(); Memo memo = this.memo.orElseThrow(() -> new IllegalStateException("CachingStatsProvider without memo cannot handle GroupReferences")); Optional<PlanNodeStatsEstimate> stats = memo.getStats(group); if (stats.isPresent()) { return stats.get(); } PlanNodeStatsEstimate groupStats = statsCalculator.calculateStats(memo.getNode(group), this, lookup, session, types.get()); verify(!memo.getStats(group).isPresent(), "Group stats already set"); memo.storeStats(group, groupStats); return groupStats; }
Source:
public static Timestamp createExpiryTime(){ Calendar calender = Calendar.getInstance(); Timestamp currentTime = new java.sql.Timestamp(calender.getTime().getTime()); calender.setTime(currentTime); Integer expiryTimeProperty = Integer.parseInt(PropertyUtil.get("oskari.email.link.expirytime")); calender.add(Calendar.DAY_OF_MONTH, expiryTimeProperty); Timestamp expiryTime = new java.sql.Timestamp(calender.getTime().getTime()); return expiryTime; }

Target:
public static Timestamp createExpiryTime(){ Calendar calender = Calendar.getInstance(); Timestamp currentTime = new java.sql.Timestamp(calender.getTime().getTime()); calender.setTime(currentTime); int expireDays = PropertyUtil.getOptional("oskari.email.link.expirytime", 2); calender.add(Calendar.DAY_OF_MONTH, expireDays); Timestamp expiryTime = new java.sql.Timestamp(calender.getTime().getTime()); return expiryTime; }
Source:
public SharedZkClient(RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig, RealmAwareZkClient.RealmAwareZkClientConfig clientConfig, MetadataStoreRoutingData metadataStoreRoutingData) { if (connectionConfig == null) { throw new IllegalArgumentException("RealmAwareZkConnectionConfig cannot be null!"); } _zkRealmShardingKey = connectionConfig.getZkRealmShardingKey(); String zkRealmAddress = null; zkRealmAddress = metadataStoreRoutingData.getMetadataStoreRealm(_zkRealmShardingKey); HelixZkClient.ZkConnectionConfig zkConnectionConfig = new HelixZkClient.ZkConnectionConfig(zkRealmAddress) .setSessionTimeout(connectionConfig.getSessionTimeout()); HelixZkClient.ZkClientConfig zkClientConfig = new HelixZkClient.ZkClientConfig(); zkClientConfig.setZkSerializer(clientConfig.getZkSerializer()) .setConnectInitTimeout(clientConfig.getConnectInitTimeout()) .setOperationRetryTimeout(clientConfig.getOperationRetryTimeout()) .setMonitorInstanceName(clientConfig.getMonitorInstanceName()) .setMonitorKey(clientConfig.getMonitorKey()) .setMonitorType(clientConfig.getMonitorType()) .setMonitorRootPathOnly(clientConfig.isMonitorRootPathOnly()); _innerSharedZkClient = SharedZkClientFactory.getInstance() .buildZkClient(zkConnectionConfig, zkClientConfig); }

Target:
public SharedZkClient(RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig, RealmAwareZkClient.RealmAwareZkClientConfig clientConfig, MetadataStoreRoutingData metadataStoreRoutingData) { if (connectionConfig == null) { throw new IllegalArgumentException("RealmAwareZkConnectionConfig cannot be null!"); } _zkRealmShardingKey = connectionConfig.getZkRealmShardingKey(); if (metadataStoreRoutingData == null) { throw new IllegalArgumentException("MetadataStoreRoutingData cannot be null!"); } _metadataStoreRoutingData = metadataStoreRoutingData; String zkRealmAddress = _metadataStoreRoutingData.getMetadataStoreRealm(_zkRealmShardingKey); if (zkRealmAddress == null || zkRealmAddress.isEmpty()) { throw new IllegalArgumentException( "ZK realm address for the given ZK realm sharding key is invalid! ZK realm address: " + zkRealmAddress + " ZK realm sharding key: " + _zkRealmShardingKey); } _zkRealmAddress = zkRealmAddress; HelixZkClient.ZkConnectionConfig zkConnectionConfig = new HelixZkClient.ZkConnectionConfig(zkRealmAddress) .setSessionTimeout(connectionConfig.getSessionTimeout()); HelixZkClient.ZkClientConfig zkClientConfig = new HelixZkClient.ZkClientConfig(); zkClientConfig.setZkSerializer(clientConfig.getZkSerializer()) .setConnectInitTimeout(clientConfig.getConnectInitTimeout()) .setOperationRetryTimeout(clientConfig.getOperationRetryTimeout()) .setMonitorInstanceName(clientConfig.getMonitorInstanceName()) .setMonitorKey(clientConfig.getMonitorKey()).setMonitorType(clientConfig.getMonitorType()) .setMonitorRootPathOnly(clientConfig.isMonitorRootPathOnly()); _innerSharedZkClient = SharedZkClientFactory.getInstance().buildZkClient(zkConnectionConfig, zkClientConfig); }
Source:
public static boolean checkIfCrashRecoveryAndFinishActivity(final Activity context) { if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); if (!(context instanceof MainMenuActivity)) { context.finish(); } else { sharedPreferences.edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); return true; } } return false; }

Target:
private void checkIfCrashRecoveryAndFinishActivity(final Activity context) { if (isRecoveredFromCrash()) { CrashReporter.sendUnhandledCaughtException(); if (!(context instanceof MainMenuActivity)) { context.finish(); } else { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(RECOVERED_FROM_CRASH, false).commit(); } } }
Source:
private XmlFile(XmlElement root, Map<String, XmlElement> refs) { this.root = ArgChecker.notNull(root, "root"); this.refs = ImmutableMap.copyOf(ArgChecker.notNull(refs, "refs")); }

Target:
private XmlFile(XmlElement root, Map<String, XmlElement> refs) { this.root = ArgChecker.notNull(root, "root"); this.refs = ImmutableMap.copyOf(refs); }
Source:
public <T extends Collector> T register(CollectorRegistry registry) { if (registered.contains(registry)) { return (T) this; } else { registered.add(registry); return super.register(registry); } }

Target:
public <T extends Collector> T register(CollectorRegistry registry) { synchronized (registered) { if (registered.contains(registry)) { return (T) this; } else { registered.add(registry); return super.register(registry); } } }
Source:
private void tryIntegerTypes(NumberSchema subject) { subject.validate(BigInteger.valueOf(123123123123123L)); subject.validate(BigDecimal.valueOf(123123123123123L)); subject.validate(new AtomicInteger(123)); subject.validate(new AtomicLong(123L)); }

Target:
private void tryIntegerTypes(NumberSchema subject) { subject.validate(BigInteger.valueOf(123123123123123L)); subject.validate(new AtomicInteger(123)); subject.validate(new AtomicLong(123L)); }
Source:
private Task prepareCreateEncounterPostActionParameterTask() { TaskTriggerInformation triggerInformation = new TaskTriggerInformation("CREATE SettingsRecord", "data-services", MDS_CHANNEL_NAME, VERSION, TRIGGER_SUBJECT, TRIGGER_SUBJECT); SortedSet<TaskConfigStep> taskConfigStepSortedSet = new TreeSet<>(); TaskConfig taskConfig = new TaskConfig(); taskConfig.addAll(taskConfigStepSortedSet); ArrayList<TaskActionInformation> taskActions = new ArrayList(); taskActions.add(prepareCreateEncounterActionInformation()); taskActions.add(prepareCreatePatientForEncounterActionInformation("{{pa.0.uuid}}", "Jacob Lee")); Task task = new Task("OpenMRSEncounterPostActionParameterTestTask", triggerInformation, taskActions, taskConfig, true, true); getTaskService().save(task); return task; }

Target:
private Task prepareCreateEncounterPostActionParameterTask() { TaskTriggerInformation triggerInformation = new TaskTriggerInformation("CREATE SettingsRecord", "data-services", MDS_CHANNEL_NAME, VERSION, TRIGGER_SUBJECT, TRIGGER_SUBJECT); ArrayList<TaskActionInformation> taskActions = new ArrayList(); taskActions.add(prepareCreateEncounterActionInformation()); taskActions.add(prepareCreatePatientActionInformation("{{pa.0.uuid}}", "Jacob Lee", false)); Task task = new Task("OpenMRSEncounterPostActionParameterTestTask", triggerInformation, taskActions, new TaskConfig(), true, true); getTaskService().save(task); return task; }
Source:
public SaveAllDirtyPartsAddon() { saveJob = doCreateSaveJob(); runnable = new Runnable() { @Override public void run() { saveJob.schedule(); display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, this); } }; idleListener = new Listener() { @Override public void handleEvent(org.eclipse.swt.widgets.Event event) { if (display != null) { display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, runnable); } } }; }

Target:
public SaveAllDirtyPartsAddon() { saveJob = new WorkbenchJob("Auto save parts") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { if (WorkbenchPlugin.getDefault().getPreferenceStore() .getBoolean(IPreferenceConstants.SAVE_AUTOMATICALLY)) { IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench != null) { IWorkbenchWindow[] windows = workbench.getWorkbenchWindows(); for (IWorkbenchWindow window : windows) { IWorkbenchPage p = window.getActivePage(); Display display = getWorkbenchDisplay(); if (p != null && !hasSubShellActive(display)) { p.saveAllEditors(false); } } } } return Status.OK_STATUS; } }; saveJobScheduler = new Runnable() { @Override public void run() { if (saveJob.getState() != Job.RUNNING) { saveJob.schedule(); } Display display = getWorkbenchDisplay(); if (display != null) { display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, this); } } }; idleListener = new Listener() { @Override public void handleEvent(org.eclipse.swt.widgets.Event event) { Display display = getWorkbenchDisplay(); if (display != null) { display.timerExec(WorkbenchPlugin.getDefault().getPreferenceStore() .getInt(IPreferenceConstants.SAVE_AUTOMATICALLY_INTERVAL) * 1000, saveJobScheduler); } } }; dirtyHandler = new EventHandler() { @Override public void handleEvent(Event event) { if (WorkbenchPlugin.getDefault().getPreferenceStore() .getBoolean(IPreferenceConstants.SAVE_AUTOMATICALLY)) { Object newValue = event.getProperty(UIEvents.EventTags.NEW_VALUE); if (!(newValue instanceof Boolean)) { return; } boolean dirty = (Boolean) newValue; if (!dirty) { return; } Display display = getWorkbenchDisplay(); display.addFilter(SWT.KeyUp, idleListener); display.addFilter(SWT.MouseUp, idleListener); } } }; }
Source:
protected String buildItemKey(ConcurStandardAccountingExtractDetailLine saeLine) { String objectCodeForKey = saeLine.getJournalAccountCode(); if (Boolean.TRUE.equals(saeLine.getJournalAccountCodeOverridden())) { objectCodeForKey = buildFakeObjectCodeToLeaveDetailLineUnmerged(); } return new StringBuilder(INITIAL_BUILDER_SIZE) .append(makeEmptyIfBlank(saeLine.getChartOfAccountsCode())) .append('|').append(makeEmptyIfBlank(saeLine.getAccountNumber())) .append('|').append(StringUtils.defaultIfBlank(saeLine.getSubAccountNumber(), getDashSubAccountNumber())) .append('|').append(makeEmptyIfBlank(objectCodeForKey)) .append('|').append(StringUtils.defaultIfBlank(saeLine.getSubObjectCode(), getDashSubObjectCode())) .append('|').append(StringUtils.defaultIfBlank(saeLine.getProjectCode(), getDashProjectCode())) .append('|').append(makeEmptyIfBlank(saeLine.getOrgRefId())) .toString(); }

Target:
protected String buildItemKey(ConcurStandardAccountingExtractDetailLine saeLine) { String objectCodeForKey = saeLine.getJournalAccountCode(); if (Boolean.TRUE.equals(saeLine.getJournalAccountCodeOverridden())) { objectCodeForKey = buildFakeObjectCodeToLeaveDetailLineUnmerged(); } return new StringBuilder(INITIAL_BUILDER_SIZE) .append(makeEmptyIfBlank(saeLine.getChartOfAccountsCode())) .append(PIPE_CHAR).append(makeEmptyIfBlank(saeLine.getAccountNumber())) .append(PIPE_CHAR).append(StringUtils.defaultIfBlank(saeLine.getSubAccountNumber(), getDashSubAccountNumber())) .append(PIPE_CHAR).append(makeEmptyIfBlank(objectCodeForKey)) .append(PIPE_CHAR).append(StringUtils.defaultIfBlank(saeLine.getSubObjectCode(), getDashSubObjectCode())) .append(PIPE_CHAR).append(StringUtils.defaultIfBlank(saeLine.getProjectCode(), getDashProjectCode())) .append(PIPE_CHAR).append(makeEmptyIfBlank(saeLine.getOrgRefId())) .toString(); }
Source:
private List<Change> submitWholeTopic(RevisionResource rsrc, IdentifiedUser caller, boolean force, String topic) throws ResourceConflictException, OrmException, IOException { Preconditions.checkNotNull(topic); final Timestamp timestamp = TimeUtil.nowTs(); ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<ChangeData> changesByTopic = queryProvider.get().byTopicOpen(topic); String problems = problemsForSubmittingChanges(changesByTopic, caller); if (problems != null) { throw new ResourceConflictException(problems); } Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { for (ChangeData c : changesByTopic) { RevisionResource resource = new RevisionResource(new ChangeResource( c.changeControl()), c.currentPatchSet()); BatchMetaDataUpdate batch = approve(resource, update, caller, timestamp); batch.write(update, new CommitBuilder()); submitToDatabase(db, c.getId(), timestamp); } db.commit(); } finally { db.rollback(); } List<Change.Id> ids = new ArrayList<>(changesByTopic.size()); List<Change> ret = new ArrayList<>(changesByTopic.size()); for (ChangeData c : changesByTopic) { ids.add(c.getId()); ret.add(c.change()); } indexer.indexAsync(ids).checkedGet(); return ret; }

Target:
private List<Change> submitWholeTopic(RevisionResource rsrc, IdentifiedUser caller, boolean force, String topic) throws ResourceConflictException, OrmException, IOException { Preconditions.checkNotNull(topic); final Timestamp timestamp = TimeUtil.nowTs(); ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<ChangeData> changesByTopic = queryProvider.get().byTopicOpen(topic); String problems = problemsForSubmittingChanges(changesByTopic, caller); if (problems != null) { throw new ResourceConflictException(problems); } Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { for (ChangeData c : changesByTopic) { BatchMetaDataUpdate batch = approve(c.currentPatchSet().getId(), c.changeControl(), update, caller, timestamp); batch.write(update, new CommitBuilder()); submitToDatabase(db, c.getId(), timestamp); } db.commit(); } finally { db.rollback(); } List<Change.Id> ids = new ArrayList<>(changesByTopic.size()); List<Change> ret = new ArrayList<>(changesByTopic.size()); for (ChangeData c : changesByTopic) { ids.add(c.getId()); ret.add(c.change()); } indexer.indexAsync(ids).checkedGet(); return ret; }
Source:
public ServicePortAdapter(ServicePortAdapter port) { this.name = port.getName(); this.port = port.getPort(); this.containerPort = "0".equals(port.getTargetPort()) ? String.valueOf(this.port) : port.getTargetPort(); this.protocol = port.getProtocol(); this.routePort = port.isRoutePort(); }

Target:
public ServicePortAdapter(ServicePortAdapter port) { this((IServicePort) port); this.routePort = port.isRoutePort(); }
Source:
public synchronized boolean isOpen() { return sub != null && conn.getState() == Constants.ConnState.CONNECTED; }

Target:
public boolean isOpen() { return sub != null && conn.getState() == Constants.ConnState.CONNECTED; }