auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public RetryPolicyOptions(RetryStrategy retryStrategy, String retryAfterHeader, ChronoUnit retryAfterTimeUnit) { <START> this.retryStrategy = Objects.requireNonNull(retryStrategy, "'retryStrategy' cannot be null."); <END> this.retryAfterHeader = retryAfterHeader; this.retryAfterTimeUnit = retryAfterTimeUnit; if (!isNullOrEmpty(retryAfterHeader)) { Objects.requireNonNull(retryAfterTimeUnit, "'retryAfterTimeUnit' cannot be null."); } }</code><technical_language>this requireNonNull ExponentialBackoff if is null</technical_language>

Target:
public RetryPolicyOptions(RetryStrategy retryStrategy, String retryAfterHeader, ChronoUnit retryAfterTimeUnit) { if (Objects.isNull(retryStrategy)) { this.retryStrategy = new ExponentialBackoff(); } else { this.retryStrategy = retryStrategy; } this.retryAfterHeader = retryAfterHeader; this.retryAfterTimeUnit = retryAfterTimeUnit; if (!isNullOrEmpty(retryAfterHeader)) { Objects.requireNonNull(retryAfterTimeUnit, "'retryAfterTimeUnit' cannot be null."); } }
Source:
<code>public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { <START> LOGGER.error("Failed to call killAllJobs on listener={} error={}", t, killAllListener); <END> } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); }</code><technical_language>arguments in wrong order</technical_language>

Target:
public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { LOGGER.error("Failed to call killAllJobs on listener={} error={}", killAllListener, t); } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); }
Source:
<code><START> public static void main(String[] args) throws InterruptedException { <END> Microservices seed = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .startAwait(); Microservices.builder() .discovery(serviceEndpoint -> serviceDiscovery(serviceEndpoint, seed)) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); ServiceCall service = seed.call(); ServiceMessage request = ServiceMessage.builder().qualifier(SERVICE_QUALIFIER).data("joe").build(); Publisher<ServiceMessage> publisher = service.requestOne(request, Greeting.class); Mono.from(publisher) .subscribe( consumer -> { Greeting greeting = consumer.data(); System.out.println(greeting.message()); }); Thread.currentThread().join(); }</code><technical_language>Remove throws InterruptedException</technical_language>

Target:
public static void main(String[] args) { Microservices seed = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .startAwait(); Microservices ms = Microservices.builder() .discovery(serviceEndpoint -> serviceDiscovery(serviceEndpoint, seed)) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); ServiceCall service = seed.call(); ServiceMessage request = ServiceMessage.builder().qualifier(SERVICE_QUALIFIER).data("joe").build(); Publisher<ServiceMessage> publisher = service.requestOne(request, Greeting.class); Mono.from(publisher) .subscribe( consumer -> { Greeting greeting = consumer.data(); System.out.println(greeting.message()); }); seed.onShutdown().block(); ms.onShutdown().block(); }
Source:
<code>public static Optional<List<Parameter>> getParametersList(io.swagger.oas.annotations.Parameter[] parameters) { if (parameters == null) { return Optional.empty(); } List<Parameter> parametersObject = new ArrayList<>(); for (io.swagger.oas.annotations.Parameter parameter : parameters) { <START> Parameter parameterObject = new Parameter(); <END> parameterObject.setDescription(parameter.description()); parameterObject.setDeprecated(parameter.deprecated()); parameterObject.setName(parameter.name()); parameterObject.setRequired(parameter.required()); parameterObject.setStyle(StringUtils.isNoneBlank(parameter.style()) ? Parameter.StyleEnum.valueOf(parameter.style()) : null); parameterObject.setAllowEmptyValue(parameter.allowEmptyValue()); parameterObject.setAllowReserved(parameter.allowReserved()); parameterObject.setExplode(parameter.explode()); parameterObject.setIn(parameter.in()); parameterObject.setContent(getContents(parameter.content()).get()); parametersObject.add(parameterObject); } return Optional.of(parametersObject); }</code><technical_language>I this logic right. Parameters _explicit_ decorated @Schema annotations, @QueryParam, etc. ParameterProcessor logic previous version for more details this</technical_language>

Target:
public static Optional<List<Parameter>> getParametersList(io.swagger.oas.annotations.Parameter[] parameters) { if (parameters == null) { return Optional.empty(); } List<Parameter> parametersObject = new ArrayList<>(); for (io.swagger.oas.annotations.Parameter parameter : parameters) { getParameter(parameter).ifPresent(parametersObject::add); } return Optional.of(parametersObject); }
Source:
<code><START> public Optional<List<String>> getProjectDependencies(){ <END> return Optional.ofNullable(projectDependencies); }</code><technical_language>good Optional for collections, return empty collection</technical_language>

Target:
public List<String> getProjectDependencies(){ return projectDependencies != null ? projectDependencies : Collections.emptyList(); }
Source:
<code><START> private void validateFolderName(String folderName) throws IOException { <END> File tempFile = new File(folderName); if (tempFile != null && tempFile.getParent() != null) { String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } }</code><technical_language>indentation is a bit</technical_language>

Target:
private void validateFolderName(String folderName) throws IOException { File tempFile = new File(folderName); if (tempFile.getParent() != null) { String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } }
Source:
<code>public void onProjectileLaunch(ProjectileLaunchEvent event) { ConfigurationManager cfg = plugin.getGlobalStateManager(); WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld()); <START> if (event.getEntityType() == EntityType.ARROW && wcfg.disableArrowShooting) { <END> event.setCancelled(true); } }</code><technical_language>@sk89q do if this null? I feel avoided due NPEs before, sure... java event.getEntityType() == EntityType.ARROW</technical_language>

Target:
public void onProjectileLaunch(ProjectileLaunchEvent event) { ConfigurationManager cfg = plugin.getGlobalStateManager(); WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld()); if (wcfg.disableArrowShooting && event.getEntityType() == EntityType.ARROW) { event.setCancelled(true); } }
Source:
<code>public ValueMatcher makeValueMatcher(String[] dimensions, final Predicate<Object[]> predicate) { final int[] dimIndices = new int[dimensions.length]; for (int i = 0; i < dimensions.length; i++) { Integer dimIndexObject = index.getDimensionIndex(dimensions[i]); if (dimIndexObject == null) { return BooleanValueMatcher.FALSE; } dimIndices[i] = dimIndexObject; } final Object[] current = new String[dimIndices.length]; return new ValueMatcher() { @Override public boolean matches() { String[][] selected = new String[dimIndices.length][]; int[] currentIdx = new int[dimIndices.length]; String[][] dims = holder.getKey().getDims(); for (int idx = 0; idx < dimIndices.length; idx++) { if (dimIndices[idx] >= dims.length) { return predicate.apply(null); } selected[idx] = dims[dimIndices[idx]]; if (selected[idx] == null) { current[idx] = null; selected[idx] = new String[0]; } else { current[idx] = selected[idx][0]; } currentIdx[idx] = 0; } if (predicate.apply(current)) { return true; } int currentIteratorIdx = 0; while (true) { currentIdx[currentIteratorIdx]++; if (currentIdx[currentIteratorIdx] < selected[currentIteratorIdx].length) { current[currentIteratorIdx] = selected[currentIteratorIdx][currentIdx[currentIteratorIdx]]; if (currentIteratorIdx > 0) { for (int idx = 0; idx < currentIteratorIdx; idx++) { currentIdx[idx] = 0; current[idx] = selected[idx][0]; } currentIteratorIdx = 0; } if (predicate.apply(current)) { return true; } } else { currentIteratorIdx++; <START> if (currentIteratorIdx == dimIndices.length) { <END> break; } } } return false; } }; }</code><technical_language>this conditional for while loop</technical_language>

Target:
public ValueMatcher makeValueMatcher(String[] dimensions, final Predicate<Object[]> predicate) { final int[] dimIndices = new int[dimensions.length]; final IncrementalIndex.DimDim[] dimValues = new IncrementalIndex.DimDim[dimensions.length]; Arrays.fill(dimIndices, -1); for (int i = 0; i < dimensions.length; i++) { IncrementalIndex.DimensionDesc dimensionDesc = index.getDimension(dimensions[i]); if (dimensionDesc != null) { dimIndices[i] = dimensionDesc.getIndex(); dimValues[i] = dimensionDesc.getValues(); } } return new ValueMatcher() { private final List<Object>[] dimValuesList = new List[dimIndices.length]; @Override public boolean matches() { int[][] dims = holder.getKey().getDims(); for (int i = 0; i < dimIndices.length; i++) { if (dimIndices[i] < 0 || dimIndices[i] >= dims.length) { dimValuesList[i] = EMPTY_PARAM; continue; } int[] dimIdx = dims[dimIndices[i]]; if (dimIdx == null || dimIdx.length == 0) { dimValuesList[i] = EMPTY_PARAM; } else { dimValuesList[i] = Lists.newArrayListWithCapacity(dimIdx.length); for (int j = 0; j < dimIdx.length; j++) { dimValuesList[i].add(dimValues[i].getValue(dimIdx[j])); } } } for (Object[] param : IterableUtils.cartesian(Object.class, dimValuesList)) { if (predicate.apply(param)) { return true; } } return false; } }; }
Source:
<code><START> public boolean setBlueprintProvisioningState(BlueprintProvisioningState blueprintProvisioningState) { <END> boolean updated = false; for (Service s : getServices().values()) { for (ServiceComponent sc : s.getServiceComponents().values()) { if (!sc.isClientComponent()) { for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) { HostComponentDesiredStateEntity desiredStateEntity = sch.getDesiredStateEntity(); if (desiredStateEntity.getBlueprintProvisioningState() != blueprintProvisioningState) { desiredStateEntity.setBlueprintProvisioningState(blueprintProvisioningState); hostComponentDesiredStateDAO.merge(desiredStateEntity); updated = true; } } } } } return updated; }</code><technical_language>do need a global setter</technical_language>

Target:
private boolean setBlueprintProvisioningState(BlueprintProvisioningState blueprintProvisioningState) { boolean updated = false; for (Service s : getServices().values()) { for (ServiceComponent sc : s.getServiceComponents().values()) { if (!sc.isClientComponent()) { for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) { HostComponentDesiredStateEntity desiredStateEntity = sch.getDesiredStateEntity(); if (desiredStateEntity.getBlueprintProvisioningState() != blueprintProvisioningState) { desiredStateEntity.setBlueprintProvisioningState(blueprintProvisioningState); hostComponentDesiredStateDAO.merge(desiredStateEntity); updated = true; } } } } } return updated; }
Source:
<code>public void setUp () { <START> senseiServiceProxy = new SenseiServiceProxy("localhost", 9000); <END> }</code><technical_language>revert this</technical_language>

Target:
public void setUp () { senseiServiceProxy = new SenseiServiceProxy("localhost", 8080); }
Source:
<code>private void addDevicesToEntity(UserDto userDto, User userEntity) { <START> userDto.getOwnPrivateData().getDevices().stream().map(d -> (UserDeviceDto) d).map(d -> createUserDeviceEntity(d, 0)) <END> .forEach(d -> userEntity.addDevice(d)); }</code><technical_language>device ID 0</technical_language>

Target:
private void addDevicesToEntity(UserDto userDto, User userEntity) { userDto.getOwnPrivateData().getDevices().orElse(Collections.emptySet()).stream().map(d -> (UserDeviceDto) d) .map(d -> createUserDeviceEntity(d, 0)).forEach(d -> userEntity.addDevice(d)); }
Source:
<code>public static Block slice( @TypeParameter("E") Type type, @SqlType("array(E)") Block array, @SqlType(StandardTypes.BIGINT) long fromIndex, @SqlType(StandardTypes.BIGINT) long length) { checkCondition(length >= 0, INVALID_FUNCTION_ARGUMENT, "length must be greater than or equal to 0"); checkCondition(fromIndex != 0, INVALID_FUNCTION_ARGUMENT, "SQL array indices start at 1"); int size = array.getPositionCount(); if (size == 0) { return array; } if (fromIndex < 0) { fromIndex = size + fromIndex + 1; } long toIndex = Math.min(fromIndex + length, size + 1); <START> if (fromIndex >= toIndex || fromIndex < 1 || toIndex < 0) { <END> return type.createBlockBuilder(new BlockBuilderStatus(), 0).build(); } return array.getRegion((int) (fromIndex - 1), (int) (toIndex - fromIndex)); }</code><technical_language>Do need toIndex < 0? if fromIndex < toIndex fromIndex >=1, toIndex > 1 for sure? ..</technical_language>

Target:
public static Block slice( @TypeParameter("E") Type type, @SqlType("array(E)") Block array, @SqlType(StandardTypes.BIGINT) long fromIndex, @SqlType(StandardTypes.BIGINT) long length) { checkCondition(length >= 0, INVALID_FUNCTION_ARGUMENT, "length must be greater than or equal to 0"); checkCondition(fromIndex != 0, INVALID_FUNCTION_ARGUMENT, "SQL array indices start at 1"); int size = array.getPositionCount(); if (size == 0) { return array; } if (fromIndex < 0) { fromIndex = size + fromIndex + 1; } long toIndex = Math.min(fromIndex + length, size + 1); if (fromIndex >= toIndex || fromIndex < 1) { return type.createBlockBuilder(new BlockBuilderStatus(), 0).build(); } return array.getRegion((int) (fromIndex - 1), (int) (toIndex - fromIndex)); }
Source:
<code>public List<Runnable> shutdownNow() { shutdown = true; List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); <START> controllerThread.interrupt(); <END> return runnableList; }</code><technical_language>interrupt controller first</technical_language>

Target:
public List<Runnable> shutdownNow() { shutdown = true; controllerThread.interrupt(); List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); return runnableList; }
Source:
<code>private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); return <START> tokens[4].substring(0, tokens[4].length() - 4); <END> }</code><technical_language>location is a user input, do contains tokens separated SEPARATOR</technical_language>

Target:
private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); return (location.endsWith(GIT_EXTENSION)) ? tokens[4].substring(0, tokens[4].length() - 4) : tokens[4].substring(0); }
Source:
<code>NamedTableNode(String alias, TableName name) { super(alias, name); <START> this.dyn_columns = new ArrayList<ColumnDef>(); <END> }</code><technical_language>Initialize this Collections.&lt;ColumnDef&gt;emptyList()</technical_language>

Target:
NamedTableNode(String alias, TableName name) { super(alias, name); dyncolumns = Collections.<ColumnDef>emptyList(); }
Source:
<code>public AuditContext(final ConnectionProvider connectionProvider, final DialectName dialect, final String schema) { <START> final JaversSqlRepository repository = SqlRepositoryBuilder.sqlRepository() <END> .withConnectionProvider(connectionProvider) .withDialect(dialect) .withSchema(schema) .build(); this.javers = JaversBuilder.javers() .registerJaversRepository(repository) .build(); PersistenceListenerManager.getInstance().addListener(new PersistenceListener() { @Override public void onEntityPersisted(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } @Override public void onEntityRemoved(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commitShallowDelete(getAuthor(), entity); } } @Override public void onEntityUpdated(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } }); }</code><technical_language>add some not-null checks here</technical_language>

Target:
public AuditContext(final ConnectionProvider connectionProvider, final DialectName dialect, final String schema) { Assert.requireNonNull(connectionProvider , "connectionProvider"); Assert.requireNonNull(dialect , "dialect"); Assert.requireNonNull(schema , "schema"); final JaversSqlRepository repository = SqlRepositoryBuilder.sqlRepository() .withConnectionProvider(connectionProvider) .withDialect(dialect) .withSchema(schema) .build(); this.javers = JaversBuilder.javers() .registerJaversRepository(repository) .build(); PersistenceListenerManager.getInstance().addListener(new PersistenceListener() { @Override public void onEntityPersisted(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } @Override public void onEntityRemoved(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commitShallowDelete(getAuthor(), entity); } } @Override public void onEntityUpdated(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } }); }
Source:
<code>public void run() { ObjectInputStream br = null; try { br = new ObjectInputStream(client.getInputStream()); while (br != null) { Object streamObject = br.readObject(); if(streamObject instanceof Contact) { Contact ct = (Contact) streamObject; System.out.println("Got contact first=" + ct.getFirstName() + " last=" + ct.getLastName() + " number=" + ct.getPhoneNumber()); } else if(streamObject instanceof TextMessage) { TextMessage txtMessage = (TextMessage) streamObject; <START> txtMessage.setReceiver(new Contact("Jonathan", "Mielke", "6185204620", "")); <END> System.out.println("Client: " + txtMessage.getContent()); System.out.println("TEXT ADDED TO ARRAY"); TaskBar.myTextArray.add(txtMessage); synchronized(TaskBar.textManager){ TaskBar.textManager.notify(); } } else{ System.out.println("Unknown object sent through stream"); } } } catch (Exception e) { System.out.println(e.getMessage() + " inside run()"); } }</code><technical_language>bulid this contact object program stars instead of time receive a message? Also, hardcoded in name, this brings a valid issue currently of knowing users name. In order programatically get this, need asking for name registers storing database</technical_language>

Target:
public void run() { Contact user = new Contact("Jonathan", "Mielke", "6185204620", ""); ObjectInputStream br = null; try { br = new ObjectInputStream(client.getInputStream()); while (br != null) { Object streamObject = br.readObject(); if(streamObject instanceof Contact) { Contact ct = (Contact) streamObject; System.out.println("Got contact first=" + ct.getFirstName() + " last=" + ct.getLastName() + " number=" + ct.getPhoneNumber()); } else if(streamObject instanceof TextMessage) { TextMessage txtMessage = (TextMessage) streamObject; txtMessage.setReceiver(user); System.out.println("Client: " + txtMessage.getContent()); System.out.println("TEXT ADDED TO ARRAY"); TaskBar.myTextArray.add(txtMessage); synchronized(TaskBar.textManager){ TaskBar.textManager.notify(); } } else{ System.out.println("Unknown object sent through stream"); } } } catch (Exception e) { System.out.println(e.getMessage() + " inside run()"); } }
Source:
<code>public void sendStringTest() throws Exception { String garbageString = "This string is garbage that needs to be cleared."; String searchString = "sugarcrm"; iface.go(elementsPage); WebDriverElement textField = iface.getWebDriverElement(Strategy.ID, "textfield"); textField.sendString(garbageString); <START> textField.sendString(searchString + Keys.TAB); <END> Assert.assertEquals(searchString, textField.getText()); String searchString1 = "sugar"; String searchString2 = "con"; textField.sendString(searchString1); textField.sendString(searchString2, true); Assert.assertEquals(searchString1 + searchString2, textField.getText()); }</code><technical_language>Do need send tab key here? I focus dropdown. testing for besides strings matching</technical_language>

Target:
public void sendStringTest() throws Exception { String garbageString = "This string is garbage that needs to be cleared."; String searchString = "sugarcrm"; iface.go(elementsPage); WebDriverElement textField = iface.getWebDriverElement(Strategy.ID, "textfield"); textField.sendString(garbageString); textField.sendString(searchString); Assert.assertEquals(searchString, textField.getText()); String searchString1 = "sugar"; String searchString2 = "con"; textField.sendString(searchString1); textField.sendString(searchString2, true); Assert.assertEquals(searchString1 + searchString2, textField.getText()); }
Source:
<code>private void doProvisionSshKeys( List<SshPairImpl> sshPairs, KubernetesEnvironment k8sEnv, String wsId) { Map<String, String> data = sshPairs .stream() .filter( sshPair -> <START> !isNullOrEmpty(sshPair.getName()) && !isNullOrEmpty(sshPair.getPrivateKey())) <END> .collect( toMap( SshPairImpl::getName, sshPair -> Base64.getEncoder().encodeToString(sshPair.getPrivateKey().getBytes()))); Secret secret = new SecretBuilder() .addToData(data) .withType(SSH_SECRET_TYPE) .withNewMetadata() .withName(wsId + SSH_SECRET_NAME_SUFFIX) .endMetadata() .build(); k8sEnv.getSecrets().put(secret.getMetadata().getName(), secret); k8sEnv .getPodsData() .values() .forEach(p -> mountSshKeySecret(secret.getMetadata().getName(), p.getSpec())); }</code><technical_language>I name null empty <LINK_0> PrivateKey null, check is needed</technical_language>

Target:
private void doProvisionSshKeys( List<SshPairImpl> sshPairs, KubernetesEnvironment k8sEnv, String wsId) { Map<String, String> data = sshPairs .stream() .filter(sshPair -> !isNullOrEmpty(sshPair.getPrivateKey())) .collect( toMap( SshPairImpl::getName, sshPair -> Base64.getEncoder().encodeToString(sshPair.getPrivateKey().getBytes()))); Secret secret = new SecretBuilder() .addToData(data) .withType(SSH_SECRET_TYPE) .withNewMetadata() .withName(wsId + SSH_SECRET_NAME_SUFFIX) .endMetadata() .build(); k8sEnv.getSecrets().put(secret.getMetadata().getName(), secret); k8sEnv .getPodsData() .values() .forEach(p -> mountSshKeySecret(secret.getMetadata().getName(), p.getSpec())); }
Source:
<code>private static void checkDBConnectivity() { boolean dbUp = false; long expectedTimeout = System.currentTimeMillis() + DbFacade.getInstance().getOnStartConnectionTimeout(); long waitBetweenInterval = DbFacade.getInstance().getConnectionCheckInterval(); while (!dbUp && System.currentTimeMillis() < expectedTimeout) { try { dbUp = DbFacade.getInstance().checkDBConnection(); } catch (RuntimeException ex) { log.error("Error in getting DB connection. The database is inaccessible. " + <START> "Original exception is: {}", ExceptionUtils.getMessage(ex)); <END> try { Thread.sleep(waitBetweenInterval); } catch (InterruptedException e) { log.warn("Failed to wait between connection polling attempts. " + "Original exception is: {}", ExceptionUtils.getMessage(e)); } } } if (!dbUp) { throw new IllegalStateException("Could not obtain connection to the database." + " Please make sure that DB is up and accepting connections, and " + "restart the application."); } }</code><technical_language>decide if ExceptionUtils not... removed most, if need add, need another large patch, trivial</technical_language>

Target:
private static void checkDBConnectivity() { boolean dbUp = false; long expectedTimeout = System.currentTimeMillis() + DbFacade.getInstance().getOnStartConnectionTimeout(); long waitBetweenInterval = DbFacade.getInstance().getConnectionCheckInterval(); while (!dbUp && System.currentTimeMillis() < expectedTimeout) { try { dbUp = DbFacade.getInstance().checkDBConnection(); } catch (RuntimeException ex) { log.error("Error in getting DB connection, database is inaccessible: {}", ex.getMessage()); log.debug("Exception", ex); try { Thread.sleep(waitBetweenInterval); } catch (InterruptedException e) { log.warn("Failed to wait between connection polling attempts. " + "Original exception is: {}", ExceptionUtils.getMessage(e)); } } } if (!dbUp) { throw new IllegalStateException("Could not obtain connection to the database." + " Please make sure that DB is up and accepting connections, and " + "restart the application."); } }
Source:
<code>public void start() { LOG.info("Starting Leshan client ..."); endpointsManager.start(); engine.start(); for (LwM2mObjectEnabler objectEnabler : objectTree.getObjectEnablers().values()) { if (objectEnabler instanceof Startable) { ((Startable) objectEnabler).start(); } <START> } <END> if (LOG.isInfoEnabled()) { LOG.info("Leshan client[endpoint:{}] started.", engine.getEndpoint()); } }</code><technical_language>idea is add a start/stop/destroy method ~LwM2mObjectEnabler~ LwM2mObjectTree move loop in this class ? (This is in term of separation of concern)</technical_language>

Target:
public void start() { LOG.info("Starting Leshan client ..."); endpointsManager.start(); engine.start(); objectTree.start(); if (LOG.isInfoEnabled()) { LOG.info("Leshan client[endpoint:{}] started.", engine.getEndpoint()); } }
Source:
<code>public static <T> void put(String key, T value) { <START> throwExceptionIf(key == null, "Key cannot be null"); <END> throwExceptionIf(value == null, "Value cannot be null"); String fullText = getMarshalledValue(value, null); storage.put(key, fullText); }</code><technical_language>this method nice I suitable for case method exception throw in some cases throw exceptions. I current usage is for validations</technical_language>

Target:
public static <T> boolean put(String key, T value) { if (key == null) { throw new NullPointerException("Key cannot be null"); } if (value == null) { throw new NullPointerException("Value cannot be null"); } String cipherText = encoder.encode(value); if (cipherText == null) { return false; } String fullText = DataUtil.addType(cipherText, value.getClass(), false); return storage.put(key, fullText); }
Source:
<code><START> public <T <END> extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { initBaseDAO((BaseDAODbFacade) dao); return (T) dao; } } log.error("Can't find dao for " + daoType); return null; }</code><technical_language>1. method public? out of class. 2. Is guaranteed time of this method called context daos in it. If find some CDI equivalent for Spring @DependsOn in order CDI this bean is dependent DAOs</technical_language>

Target:
protected <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { initBaseDAO((BaseDAODbFacade) dao); return (T) dao; } } log.error("Can't find dao for " + daoType); return null; }
Source:
<code>protected void addOrUpdateLoggerLevel(FeaturesRunner runner, FrameworkMethod method) { for (Loggable loggable : getLoggables(runner, method)) { if (loggable.level() != null) { String loggerName = getLoggerName(loggable); LoggerContext context = LoggerContext.getContext(false); if (!context.hasLogger(loggerName)) { org.apache.logging.log4j.Logger logger = LogManager.getLogger(loggerName); <START> Configurator.setLevel(logger.getName(), Level.OFF); <END> } originalLevelByLogger.put(buildKey(loggable, method), context.getLogger(loggerName).getLevel()); Configurator.setLevel(loggerName, Level.toLevel(loggable.level())); } } }</code><technical_language>giving logger name</technical_language>

Target:
protected void addOrUpdateLoggerLevel(FeaturesRunner runner, FrameworkMethod method) { for (LoggerLevel logger : getLoggers(runner, method)) { if (logger.level() != null) { String loggerName = getLoggerName(logger); LoggerContext context = LoggerContext.getContext(false); if (!context.hasLogger(loggerName)) { Configurator.setLevel(loggerName, Level.OFF); } originalLevelByLogger.put(buildKey(logger, method), context.getLogger(loggerName).getLevel()); Configurator.setLevel(loggerName, Level.toLevel(logger.level())); } } }
Source:
<code>public void refreshBuilds(final RefreshRequest request, final GetBuildsRequest buildRequest, final IOperationMonitor monitor) throws CoreException { final List<IBuild> result = BuildRunner.run(new BuildRunnableWithResult<List<IBuild>>() { @Override public List<IBuild> run() throws CoreException { return server.getBehaviour().getBuilds(buildRequest, monitor); } }); if (result == null) { return; } final BuildServer original = server.getOriginal(); original.getLoader().getRealm().syncExec(new Runnable() { public void run() { Date refreshDate = new Date(); for (IBuildPlan modelPlan : request.getModel().getPlans()) { if (modelPlan.getServer() == original && modelPlan.getId().equals(buildRequest.getPlan().getId())) { updateLastBuild(request, modelPlan, result.get(0), refreshDate); } for (IBuildPlan modelChildPlan : modelPlan.getChildren()) { if (modelChildPlan.getServer() == original && modelChildPlan.getId().equals(buildRequest.getPlan().getId())) { <START> updateLastBuild(request, modelChildPlan, result.get(0), refreshDate); <END> } } } } }); }</code><technical_language>this add child builds build model, is desired</technical_language>

Target:
public void refreshBuilds(final RefreshRequest request, final GetBuildsRequest buildRequest, final IOperationMonitor monitor) throws CoreException { final List<IBuild> result = BuildRunner.run(new BuildRunnableWithResult<List<IBuild>>() { @Override public List<IBuild> run() throws CoreException { return server.getBehaviour().getBuilds(buildRequest, monitor); } }); if (result == null) { return; } final BuildServer original = server.getOriginal(); original.getLoader().getRealm().syncExec(new Runnable() { public void run() { Date refreshDate = new Date(); for (IBuildPlan modelPlan : request.getModel().getPlans()) { if (modelPlan.getServer() == original && modelPlan.getId().equals(buildRequest.getPlan().getId())) { updateLastBuild(request, modelPlan, result.get(0), refreshDate); } } } }); }
Source:
<code>public Result mediaList(Long folderId) { Folder folder = folderManager.findById(folderId); if (!Secured.viewFolder(folder)) { return forbidden("Dazu hast du keine Berechtigung"); } Folder rootFolder = FolderManager.findRoot(folder); List<Media> mediaSet = folder.files; List<Folder> folderList = folder.folders; <START> return created(list.render(mediaSet, folderList, rootFolder.group.id)); <END> }</code><technical_language>copy upload() is this status type correct</technical_language>

Target:
public Result mediaList(Long folderId) { Folder folder = folderManager.findById(folderId); if (!Secured.viewFolder(folder)) { return forbidden("Dazu hast du keine Berechtigung"); } Folder rootFolder = FolderManager.findRoot(folder); List<Media> mediaSet = folder.files; List<Folder> folderList = folder.folders; for (Media media : mediaSet) { media.sizeInByte = mediaManager.bytesToString(media.size, false); } return ok(list.render(mediaSet, folderList, rootFolder.group.id)); }
Source:
<code>public static boolean assertSameHtml(String expected, String actual, boolean isPart, boolean isDifferenceToBeShown) { String processedExpected = convertToStandardHtml(expected, isPart); <START> String processedActual = convertToStandardHtml(actual, isPart); <END> if (!AssertHelper.isContainsRegex(processedExpected, processedActual)) { if (isDifferenceToBeShown) { processedActual = AppPage.processPageSourceForFailureCase(processedActual); processedExpected = AppPage.processPageSourceForFailureCase(processedExpected); assertEquals("<expected>\n" + processedExpected + "</expected>", "<actual>\n" + processedActual + "</actual>"); } return false; } return true; }</code><technical_language>Consider making this private separate public method descriptive names boolean flags, if number of methods high. get rid of flag. However, public methods call private method correct boolean parameter. flags internal optimization clients of class need bother with</technical_language>

Target:
private static boolean assertSameHtml(String expected, String actual, boolean isPart, boolean isDifferenceToBeShown) { String processedExpected = convertToStandardHtml(expected, isPart); String processedActual = convertToStandardHtml(actual, isPart); if (!AssertHelper.isContainsRegex(processedExpected, processedActual)) { if (isDifferenceToBeShown) { processedActual = AppPage.processPageSourceForFailureCase(processedActual); processedExpected = AppPage.processPageSourceForFailureCase(processedExpected); assertEquals("<expected>\n" + processedExpected + "</expected>", "<actual>\n" + processedActual + "</actual>"); } return false; } return true; }
Source:
<code>private void createNodeIdToDAGNode() { <START> nodeIdToDAGNode = new TreeMap<String, DAGNode<Job>>(); <END> for (Task<? extends Serializable> task : allTasks) { if (task.getWork() instanceof MapredWork) { DAGNode<Job> dagNode = asDAGNode(task); nodeIdToDAGNode.put(dagNode.getName(), dagNode); } } Map<String, List<String>> nodeIdToDependencies = getNodeIdToDependencies(); for (Map.Entry<String, List<String>> entry : nodeIdToDependencies.entrySet()) { String nodeId = entry.getKey(); List<String> successorIds = entry.getValue(); DAGNode<Job> dagNode = nodeIdToDAGNode.get(nodeId); List<DAGNode<? extends Job>> dagSuccessors = new ArrayList<DAGNode<? extends Job>>( successorIds.size()); for (String sId : successorIds) { DAGNode<Job> successor = nodeIdToDAGNode.get(sId); dagSuccessors.add(successor); } dagNode.setSuccessors(dagSuccessors); } }</code><technical_language>Do a dep guava? If so, replace this Maps.newTreeMap() <LINK_0></technical_language>

Target:
private void createNodeIdToDAGNode() { nodeIdToDAGNode = Maps.newTreeMap(); for (Task<? extends Serializable> task : allTasks) { if (task.getWork() instanceof MapredWork) { DAGNode<Job> dagNode = asDAGNode(task); nodeIdToDAGNode.put(dagNode.getName(), dagNode); } } Map<String, List<String>> nodeIdToDependencies = getNodeIdToDependencies(); for (Map.Entry<String, List<String>> entry : nodeIdToDependencies.entrySet()) { String nodeId = entry.getKey(); List<String> successorIds = entry.getValue(); DAGNode<Job> dagNode = nodeIdToDAGNode.get(nodeId); List<DAGNode<? extends Job>> dagSuccessors = Lists.newArrayListWithCapacity(successorIds.size()); for (String sId : successorIds) { DAGNode<Job> successor = nodeIdToDAGNode.get(sId); dagSuccessors.add(successor); } dagNode.setSuccessors(dagSuccessors); } }
Source:
<code>public static int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) { if (state.init) { state.init = false; state.gcCount = 0; state.nCount = 0; for (int i = startIndex; i < endIndex; ++i) { final byte base = bases[i]; if (base == 'G' || base == 'C') ++state.gcCount; else if (base == 'N') ++state.nCount; } } else { final byte newBase = bases[endIndex - 1]; if (newBase == 'G' || newBase == 'C') ++state.gcCount; else if (newBase == 'N') ++state.nCount; if (state.priorBase == 'G' || state.priorBase == 'C') --state.gcCount; <START> else if (state.priorBase == 'N') --state.nCount; <END> } state.priorBase = bases[startIndex]; if (state.nCount > 4) return -1; else return (state.gcCount * 100) / (endIndex - startIndex); }</code><technical_language>This is sort of tangential, this method modified SequenceUtil.basesEqual instead of direct == ? cleaner, call StringUtil.toUpperCase(refBases) (which speed up, enough noticeable)</technical_language>

Target:
public static int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) { if (state.init) { state.init = false; state.gcCount = 0; state.nCount = 0; for (int i = startIndex; i < endIndex; ++i) { final byte base = bases[i]; if (SequenceUtil.basesEqual(base, (byte)'G') || SequenceUtil.basesEqual(base, (byte)'C')) ++state.gcCount; else if (SequenceUtil.basesEqual(base, (byte)'N')) ++state.nCount; } } else { final byte newBase = bases[endIndex - 1]; if (SequenceUtil.basesEqual(newBase, (byte)'G') || SequenceUtil.basesEqual(newBase, (byte)'C')) ++state.gcCount; else if (newBase == 'N') ++state.nCount; if (SequenceUtil.basesEqual(state.priorBase, (byte)'G') || SequenceUtil.basesEqual(state.priorBase, (byte)'C')) --state.gcCount; else if (SequenceUtil.basesEqual(state.priorBase, (byte)'N')) --state.nCount; } state.priorBase = bases[startIndex]; if (state.nCount > 4) return -1; else return (state.gcCount * 100) / (endIndex - startIndex); }
Source:
<code>private static void createLink(IFolder parentFolder, IPath location, String targetName) { File source = new File(location.toString()); IWorkspace workspace = ResourcesPlugin.getWorkspace(); try { if (source.isDirectory()) { IFolder folder = parentFolder.getFolder(targetName); IStatus result = workspace.validateLinkLocation(folder, location); if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) { folder.createLink(location, IResource.REPLACE, null); } else { Activator.getDefault().logError("Invalid Trace Location"); } } else { IFile file = parentFolder.getFile(targetName); IStatus result = workspace.validateLinkLocation(file, location); if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) { file.createLink(location, IResource.REPLACE, null); } else { Activator.getDefault().logError("Invalid Trace Location"); } } } catch (CoreException e) { final Exception e1 = e; TraceUtils.displayErrorMsg("Error", e1.getMessage(), e1); <START> Activator.getDefault().logError(e.getMessage(), e); <END> } }</code><technical_language>logged in TraceUtils</technical_language>

Target:
private static void createLink(IFolder parentFolder, IPath location, String targetName) { File source = new File(location.toString()); IWorkspace workspace = ResourcesPlugin.getWorkspace(); try { if (source.isDirectory()) { IFolder folder = parentFolder.getFolder(targetName); IStatus result = workspace.validateLinkLocation(folder, location); if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) { folder.createLink(location, IResource.REPLACE, null); } else { Activator.getDefault().logError("Invalid Trace Location"); } } else { IFile file = parentFolder.getFile(targetName); IStatus result = workspace.validateLinkLocation(file, location); if (result.isOK() || result.matches(IStatus.INFO | IStatus.WARNING)) { file.createLink(location, IResource.REPLACE, null); } else { Activator.getDefault().logError("Invalid Trace Location"); } } } catch (CoreException e) { TraceUtils.displayErrorMsg(e.getClass().getSimpleName(), e.getMessage(), e); } }
Source:
<code>private String parseTimer(String value) { if (value.equals("OFF/OFF")) return "Off/Off"; if (value.equals("ON/OFF")) return "On/Off"; if (value.equals("OFF/ON")) return "Off/On"; <START> if (value.equals("ON/ON")) return "On/Off"; <END> return "None"; }</code><technical_language>please refactor Enumerations instead</technical_language>

Target:
private DaikinTimer parseTimer(String value) { if (value.equals("OFF/OFF")) return DaikinTimer.OffOff; if (value.equals("ON/OFF")) return DaikinTimer.OnOff; if (value.equals("OFF/ON")) return DaikinTimer.OffOn; if (value.equals("ON/ON")) return DaikinTimer.OnOn; return DaikinTimer.None; }
Source:
<code>private void verifyClientShallow() throws IOException, PackProtocolException { AsyncRevObjectQueue q = walk.parseAny(clientShallowCommits, true); try { for (;;) { try { <START> RevObject o = q.next(); <END> if (!(o instanceof RevCommit)) { throw new PackProtocolException( MessageFormat.format( JGitText.get().invalidShallowObject, o.name())); } } catch (MissingObjectException notCommit) { clientShallowCommits.remove(notCommit.getObjectId()); continue; } } } finally { q.release(); } }</code><technical_language>happen o == null</technical_language>

Target:
private void verifyClientShallow() throws IOException, PackProtocolException { AsyncRevObjectQueue q = walk.parseAny(clientShallowCommits, true); try { for (;;) { try { RevObject o = q.next(); if (o == null) { break; } if (!(o instanceof RevCommit)) { throw new PackProtocolException( MessageFormat.format( JGitText.get().invalidShallowObject, o.name())); } } catch (MissingObjectException notCommit) { clientShallowCommits.remove(notCommit.getObjectId()); continue; } } } finally { q.release(); } }
Source:
<code>private IAccessRule loadAccessRule() throws IOException { int problemId = loadInt(); IPath pattern = loadPath(); return <START> JavaCore.newAccessRule(pattern, <END> problemId); }</code><technical_language>AFAICS in instance scope of JavaModelManager, indirection JavaCore unnecessary</technical_language>

Target:
private IAccessRule loadAccessRule() throws IOException { int problemId = loadInt(); IPath pattern = loadPath(); return getAccessRule(pattern, problemId); }
Source:
<code><START> public void calculateSerializedSize() { <END> ByteBuf buf = Unpooled.buffer(); serialize(buf); serializedSize = buf.writerIndex(); log.warn("It is an expensive operation"); }</code><technical_language>this is opaque entry, for fact arguments array is array of byte[]. need allocate a buffer do copy calculate size. java int size = 0; for (byte[] buf : arguments) size += buf.length; size += (SMRMethod.length() * Character.BYTES); size += Integer.BYTES; return size;</technical_language>

Target:
private int calculateSerializedSize() { if (!opaque) { log.error("This operation only supported for an opaque SMR entry"); return 0; } int size = 0; for (Object smrArg : SMRArguments) { size += ((byte[])smrArg).length; } size += (SMRMethod.length() * Character.BYTES); size += Integer.BYTES; return size; }
Source:
<code>private void attemptRecovery(final IOException originalIOException) throws IOException { try { super.continueWith(this.continuator.buildContinuation(originalIOException, this.getBytesRead())); <START> } catch (final IOException ioe) { <END> LOG.debug("Failed to automatically recover: {}", ioe.getMessage()); if (originalIOException != ioe) { originalIOException.addSuppressed(ioe); } throw originalIOException; } }</code><technical_language>This paranoid, want catch UncheckedIOException well</technical_language>

Target:
private void attemptRecovery(final IOException originalIOException) throws IOException { try { super.continueWith(this.continuator.buildContinuation(originalIOException, this.getBytesRead())); } catch (final UncheckedIOException | IOException ioe) { LOG.debug("Failed to automatically recover: {}", ioe.getMessage()); if (originalIOException != ioe) { originalIOException.addSuppressed(ioe); } throw originalIOException; } }
Source:
<code>public void run() { try { state.runtime.stop(options); runtimes.remove(workspaceId); LOG.info( "Workspace '{}/{}' with id '{}' stopped by user '{}'", workspace.getNamespace(), workspace.getConfig().getName(), <START> workspace.getId(), <END> stoppedBy); publishWorkspaceStatusEvent(workspaceId, STOPPED, STOPPING, null); } catch (InfrastructureException e) { runtimes.remove(workspaceId); LOG.info( "Error occurs on workspace '{}/{}' with id '{}' stopped by user '{}'. Error: {}", workspace.getNamespace(), workspace.getConfig().getName(), workspace.getId(), stoppedBy, e); publishWorkspaceStatusEvent( workspaceId, STOPPED, STOPPING, "Error occurs on workspace runtime stop. Error: " + e.getMessage()); if (e instanceof InternalInfrastructureException) { LOG.error(e.getLocalizedMessage(), e); } throw new RuntimeException(e); } }</code><technical_language>workspaceId</technical_language>

Target:
public void run() { String workspaceId = workspace.getId(); try { state.runtime.stop(options); runtimes.remove(workspaceId); LOG.info( "Workspace '{}/{}' with id '{}' stopped by user '{}'", workspace.getNamespace(), workspace.getConfig().getName(), workspaceId, stoppedBy); publishWorkspaceStatusEvent(workspaceId, STOPPED, STOPPING, null); } catch (InfrastructureException e) { runtimes.remove(workspaceId); LOG.info( "Error occurs on workspace '{}/{}' with id '{}' stopped by user '{}'. Error: {}", workspace.getNamespace(), workspace.getConfig().getName(), workspaceId, stoppedBy, e); publishWorkspaceStatusEvent( workspaceId, STOPPED, STOPPING, "Error occurs on workspace runtime stop. Error: " + e.getMessage()); if (e instanceof InternalInfrastructureException) { LOG.error(e.getLocalizedMessage(), e); } throw new RuntimeException(e); } }
Source:
<code>public List<Attribute> getRequiredAttributes(PerunSession sess, Member member, boolean workWithUserAttributes) throws PrivilegeException, InternalErrorException, MemberNotExistsException { Utils.checkPerunSession(sess); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); List<Attribute> attributes = getAttributesManagerBl().getRequiredAttributes(sess, member, workWithUserAttributes); Iterator<Attribute> attrIter = attributes.iterator(); <START> User u = null; <END> while(attrIter.hasNext()) { Attribute attrNext = attrIter.next(); if (getAttributesManagerBl().isFromNamespace(sess, attrNext, NS_MEMBER_ATTR)){ if(!AuthzResolver.isAuthorizedForAttribute(sess, ActionType.READ, attrNext, member, null)) attrIter.remove(); else attrNext.setWritable(AuthzResolver.isAuthorizedForAttribute(sess, ActionType.WRITE, attrNext, member, null)); } else if (getAttributesManagerBl().isFromNamespace(sess, attrNext, NS_USER_ATTR)) { if (u == null) u = getPerunBl().getUsersManagerBl().getUserByMember(sess, member); if(!AuthzResolver.isAuthorizedForAttribute(sess, ActionType.READ, attrNext, u, null)) attrIter.remove(); else attrNext.setWritable(AuthzResolver.isAuthorizedForAttribute(sess, ActionType.WRITE, attrNext, u, null)); } else { throw new ConsistencyErrorException("There is some attribute which is not type of any possible choice."); } } return attributes; }</code><technical_language>Please full name of variable "user" instead of "u" working this object. please call this place always. is calling of method getUserByMember more human readable</technical_language>

Target:
public List<Attribute> getRequiredAttributes(PerunSession sess, Member member, boolean workWithUserAttributes) throws PrivilegeException, InternalErrorException, MemberNotExistsException { Utils.checkPerunSession(sess); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); List<Attribute> attributes = getAttributesManagerBl().getRequiredAttributes(sess, member, workWithUserAttributes); Iterator<Attribute> attrIter = attributes.iterator(); User user = null; while(attrIter.hasNext()) { Attribute attrNext = attrIter.next(); if (getAttributesManagerBl().isFromNamespace(sess, attrNext, NS_MEMBER_ATTR)){ if(!AuthzResolver.isAuthorizedForAttribute(sess, ActionType.READ, attrNext, member, null)) attrIter.remove(); else attrNext.setWritable(AuthzResolver.isAuthorizedForAttribute(sess, ActionType.WRITE, attrNext, member, null)); } else if (getAttributesManagerBl().isFromNamespace(sess, attrNext, NS_USER_ATTR)) { if (user == null) user = getPerunBl().getUsersManagerBl().getUserByMember(sess, member); if(!AuthzResolver.isAuthorizedForAttribute(sess, ActionType.READ, attrNext, user, null)) attrIter.remove(); else attrNext.setWritable(AuthzResolver.isAuthorizedForAttribute(sess, ActionType.WRITE, attrNext, user, null)); } else { throw new ConsistencyErrorException("There is some attribute which is not type of any possible choice."); } } return attributes; }