auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void sendTo(UnifiedMessage unifiedMessage) { StringBuilder sb = buildUrl("selected"); final Map<String, Object> selectedPayloadObject = new LinkedHashMap<String, Object>(); if (unifiedMessage.getAliases() != null && !unifiedMessage.getAliases().isEmpty()) { selectedPayloadObject.put("alias", unifiedMessage.getAliases()); } if(unifiedMessage.getCategory() != null) { selectedPayloadObject.put("category", unifiedMessage.getCategory()); } if(unifiedMessage.getDeviceType() != null && !unifiedMessage.getDeviceType().isEmpty()) { selectedPayloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if(unifiedMessage.getVariants() != null && !unifiedMessage.getVariants().isEmpty()) { selectedPayloadObject.put("variants", unifiedMessage.getVariants()); } <START> if(unifiedMessage.getSimplePushMap()!= null && !unifiedMessage.getSimplePushMap().isEmpty()) { <END> selectedPayloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } selectedPayloadObject.put("message", unifiedMessage.getAttributes()); String payload = transformJSON(selectedPayloadObject); submitPayload(sb.toString(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret()); }</code><technical_language>move != null && !empty checks a helper, simply pass collection in</technical_language>

Target:
public void sendTo(UnifiedMessage unifiedMessage) { StringBuilder sb = buildUrl("selected"); final Map<String, Object> selectedPayloadObject = new LinkedHashMap<String, Object>(); if (!isEmpty(unifiedMessage.getAliases())) { selectedPayloadObject.put("alias", unifiedMessage.getAliases()); } if (!isEmpty(unifiedMessage.getCategory())) { selectedPayloadObject.put("category", unifiedMessage.getCategory()); } if (!isEmpty(unifiedMessage.getDeviceType())) { selectedPayloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if (!isEmpty(unifiedMessage.getVariants())) { selectedPayloadObject.put("variants", unifiedMessage.getVariants()); } if (!isEmpty(unifiedMessage.getSimplePushMap())) { selectedPayloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } if (!isEmpty(unifiedMessage.getAttributes())) { selectedPayloadObject.put("message", unifiedMessage.getAttributes()); } String payload = transformJSON(selectedPayloadObject); submitPayload(sb.toString(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret()); }
Source:
<code>public String retrieveStatusOfWorkflow(String uuid) throws InternalWorkflowException { Connection connection = null; PreparedStatement prepStmt = null; ResultSet rs = null; String query = SQLConstants.GET_WORKFLOW_REQUEST_QUERY; try { connection = IdentityDatabaseUtil.getDBConnection(); prepStmt = connection.prepareStatement(query); prepStmt.setString(1, uuid); rs = prepStmt.executeQuery(); if (rs.next()) { String status = rs.getString(SQLConstants.REQUEST_STATUS_COLUMN); return status; } } catch (IdentityException e) { throw new InternalWorkflowException("Error when connecting to the Identity Database.", e); } catch (SQLException e) { throw new InternalWorkflowException("Error when executing the sql query:" + query, e); } finally { <START> IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt); <END> } return ""; }</code><technical_language>close result set</technical_language>

Target:
public String retrieveStatusOfWorkflow(String uuid) throws InternalWorkflowException { Connection connection = null; PreparedStatement prepStmt = null; ResultSet resultSet = null; String query = SQLConstants.GET_WORKFLOW_REQUEST_QUERY; try { connection = IdentityDatabaseUtil.getDBConnection(); prepStmt = connection.prepareStatement(query); prepStmt.setString(1, uuid); resultSet = prepStmt.executeQuery(); if (resultSet.next()) { String status = resultSet.getString(SQLConstants.REQUEST_STATUS_COLUMN); return status; } } catch (IdentityException e) { throw new InternalWorkflowException("Error when connecting to the Identity Database.", e); } catch (SQLException e) { throw new InternalWorkflowException("Error when executing the sql query:" + query, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } return ""; }
Source:
<code>public void oSType_SelectedItemChanged() { if (getModel().getOSType().getSelectedItem() != null) { EmulatedMachine <START> em = <END> AsyncDataProvider.getInstance().emulatedMachineByOs(getModel().getOSType().getSelectedItem()); if (getModel().getEmulatedMachine().getIsAvailable()) { getModel().getEmulatedMachine().setSelectedItem(em); } } }</code><technical_language>this em null - in case I do logic below. - please move content of this method updateEmulatedMachines()</technical_language>

Target:
public void oSType_SelectedItemChanged() { updateEmulatedMachines(); }
Source:
<code><START> private RNASequence readGenbankRNAResource(final String resource) throws Exception { <END> RNASequence sequence = null; InputStream inputStream = null; try { inputStream = getClass().getResourceAsStream(resource); GenbankReader<RNASequence, NucleotideCompound> genbankRNA = new GenbankReader<>( inputStream, new GenericGenbankHeaderParser<>(), new RNASequenceCreator(RNACompoundSet.getRNACompoundSet()) ); LinkedHashMap<String, RNASequence> rnaSequences = genbankRNA.process(); sequence = rnaSequences.values().iterator().next(); } finally { try { inputStream.close(); } catch (Exception e) { } } return sequence; }</code><technical_language>declare exceptions thrown? I suppose IOException only</technical_language>

Target:
private RNASequence readGenbankRNAResource(final String resource) throws IOException, CompoundNotFoundException { InputStream inputStream = getClass().getResourceAsStream(resource); GenbankReader<RNASequence, NucleotideCompound> genbankRNA = new GenbankReader<>( inputStream, new GenericGenbankHeaderParser<>(), new RNASequenceCreator(RNACompoundSet.getRNACompoundSet()) ); LinkedHashMap<String, RNASequence> rnaSequences = genbankRNA.process(); return rnaSequences.values().iterator().next(); }
Source:
<code><START> public void lineBreak() { <END> delegate.lineBreak(); }</code><technical_language>assertOpenBlock(); here, a test fails</technical_language>

Target:
public void lineBreak() { assertOpenBlock(); delegate.lineBreak(); }
Source:
<code>private synchronized void flushWrittenBytesToServiceInternal(final long offset, final boolean retainUncommitedData, final boolean isClose) throws IOException { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "flushWrittenBytesToServiceInternal", "flush")) { AbfsRestOperation op = client.flush(path, offset, retainUncommitedData, isClose, this.authzStatus); perfInfo.registerResult(op.getResult()).registerSuccess(true); } catch (AzureBlobFileSystemException ex) { if (ex instanceof AbfsRestOperationException) { if (((AbfsRestOperationException) ex).getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new FileNotFoundException(ex.getMessage()); } } <START> if ((ex instanceof AbfsAuthorizationException) <END> || (ex instanceof AbfsAuthorizerUnhandledException)) { throw ex; } throw new IOException(ex); } this.lastFlushOffset = offset; }</code><technical_language>this done separate catch clauses line 364, e.g. catch(AbfsAuthException | AbfsAuthUnhandledException ex) { throw ex; }</technical_language>

Target:
private synchronized void flushWrittenBytesToServiceInternal(final long offset, final boolean retainUncommitedData, final boolean isClose) throws IOException { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "flushWrittenBytesToServiceInternal", "flush")) { AbfsRestOperation op = client.flush(path, offset, retainUncommitedData, isClose); perfInfo.registerResult(op.getResult()).registerSuccess(true); } catch (AzureBlobFileSystemException ex) { if (ex instanceof AbfsRestOperationException) { if (((AbfsRestOperationException) ex).getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { throw new FileNotFoundException(ex.getMessage()); } } throw new IOException(ex); } this.lastFlushOffset = offset; }
Source:
<code>private void migrateDiscoveryGroup(ModelNode newAddOp, List<String> warnings) { boolean mandatorySocketBinding = false; for (String property : asList(LOCAL_BIND_ADDRESS.getName(), GROUP_ADDRESS.getName(), GROUP_PORT.getName())) { if (newAddOp.has(property)) { newAddOp.remove(property); warnings.add(ROOT_LOGGER.couldNotMigrateDiscoveryGroupAttribute(property, pathAddress(newAddOp.get(OP_ADDR)))); mandatorySocketBinding = true; } } if (mandatorySocketBinding) <START> newAddOp.get(SOCKET_BINDING.getName()).set("group-x-binding"); <END> removePropertiesWithExpression(newAddOp, warnings, JGROUPS_CHANNEL.getName(), JGROUPS_STACK.getName()); }</code><technical_language>1 migrate operation add reference unexisting socket-binding. correct migrate a resource migrate messaging subsystem, add socket-binding resource update socket-binding attribute of broadcast-groups resource</technical_language>

Target:
private void migrateDiscoveryGroup(ModelNode newAddOp, List<String> warnings) { boolean mandatorySocketBinding = false; for (String property : asList(LOCAL_BIND_ADDRESS.getName(), GROUP_ADDRESS.getName(), GROUP_PORT.getName())) { if (newAddOp.has(property)) { newAddOp.remove(property); warnings.add(ROOT_LOGGER.couldNotMigrateDiscoveryGroupAttribute(property, pathAddress(newAddOp.get(OP_ADDR)))); mandatorySocketBinding = true; } } if (mandatorySocketBinding) { newAddOp.get(SOCKET_BINDING.getName()).set("group-s-binding"); } List<String> removed = removePropertiesWithExpression(newAddOp, warnings, JGROUPS_CHANNEL.getName(), JGROUPS_STACK.getName()); if (!removed.isEmpty() && !mandatorySocketBinding) { newAddOp.get(SOCKET_BINDING.getName()).set("group-s-binding"); } }
Source:
<code>public JobCoordinator getJobCoordinator(String processorId, Config config, MetricsRegistry metricsRegistry) { String jobCoordinatorZkBasePath = getJobCoordinationZkPath(config); ZkUtils zkUtils = getZkUtils(config, metricsRegistry, jobCoordinatorZkBasePath); LOG.debug("Creating ZkJobCoordinator with config: {}.", config); ZkMetadataStore metadataStore = new ZkMetadataStore(zkUtils.getKeyBuilder().getRootPath(), config, metricsRegistry); <START> metadataStore.init(); <END> return new ZkJobCoordinator(processorId, config, metricsRegistry, zkUtils, metadataStore); }</code><technical_language>this need initialized closed in Coordinator? if a single class responsible for lifecycle of this object</technical_language>

Target:
public JobCoordinator getJobCoordinator(String processorId, Config config, MetricsRegistry metricsRegistry) { String jobCoordinatorZkBasePath = getJobCoordinationZkPath(config); ZkUtils zkUtils = getZkUtils(config, metricsRegistry, jobCoordinatorZkBasePath); LOG.debug("Creating ZkJobCoordinator with config: {}.", config); ZkMetadataStore metadataStore = new ZkMetadataStore(zkUtils.getKeyBuilder().getRootPath(), config, metricsRegistry); return new ZkJobCoordinator(processorId, config, metricsRegistry, zkUtils, metadataStore); }
Source:
<code>public final void retrievesForks() throws Exception { final Iterable<Fork> forks = RtForksITCase.repo().forks() .iterate("newest"); MatcherAssert.assertThat(forks, Matchers.notNullValue()); int count = 0; for (final Fork fork : forks) { MatcherAssert.assertThat(fork, Matchers.notNullValue()); <START> count += 1; <END> } MatcherAssert.assertThat( "Test repo should have at leas 1 fork", count, Matchers.greaterThan(0) ); }</code><technical_language>Instead of counting forks iteration, assertion following: java MatcherAssert.assertThat( forks.iterate(), Matchers.not(Matchers.emptyIterable()) );</technical_language>

Target:
public final void retrievesForks() throws Exception { final String organization = System.getProperty( "failsafe.github.organization" ); Assume.assumeThat(organization, Matchers.notNullValue()); final Repo repo = RtForksITCase.repos().create( Json.createObjectBuilder().add( "name", RandomStringUtils.randomNumeric(5) ).build() ); try { final Fork fork = repo.forks().create(organization); MatcherAssert.assertThat(fork, Matchers.notNullValue()); final Iterable<Fork> forks = repo.forks().iterate("newest"); MatcherAssert.assertThat(forks, Matchers.notNullValue()); MatcherAssert.assertThat( forks, Matchers.not(Matchers.emptyIterable()) ); MatcherAssert.assertThat( forks, Matchers.contains(fork) ); } finally { RtForksITCase.repos().remove(repo.coordinates()); } }
Source:
<code>public SSLContext createSSLContext(ZKConfig config) throws SSLContextException { if (config.getProperty(sslClientContextProperty) != null) { LOG.debug("Loading SSLContext from property '" + sslClientContextProperty + "'"); String sslClientContextClass = config.getProperty(sslClientContextProperty); try { Class<?> sslContextClass = Class.forName(sslClientContextClass); <START> ZKClientSSLContext sslContext = (ZKClientSSLContext) sslContextClass.getConstructor().newInstance(); <END> return sslContext.getSSLContext(); } catch (ClassNotFoundException | ClassCastException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { throw new SSLContextException("Could not retrieve the SSLContext from source '" + sslClientContextClass + "' provided in the property '" + sslClientContextProperty + "'", e); } } else { return createSSLContextFromConfig(config); } }</code><technical_language>I java.util.function.Supplier<SSLContext> instead of ZKClientSSLContext type</technical_language>

Target:
public SSLContext createSSLContext(ZKConfig config) throws SSLContextException { return createSSLContextAndOptions(config).getSSLContext(); }
Source:
<code>private Map executeCommand(String lines, InterpreterContext context, Map<String, Integer> userSessionMap) throws LivyException { String json; try { json = executeHTTP(property.get("zeppelin.livy.url") + "/sessions/" + userSessionMap.get(context.getAuthenticationInfo().getUser()) + "/statements", "POST", "{\"code\": \"" + StringEscapeUtils.escapeJson(lines) + "\"}", context.getParagraphId()); } catch (Exception e) { throw new LivyException("Error executing command in Livy", e); } if (json == null || json.matches("^(\")?Session (\'[0-9]\' )?not found(.?\"?)$")) { <START> throw new LivyNoSessionException(); <END> } try { Map jsonMap = gson.fromJson(json, new TypeToken<Map>() { }.getType()); return jsonMap; } catch (Exception e) { LOGGER.error("Error executeCommand", e); throw new LivyException("Error parsing Livy response", e); } }</code><technical_language>add some logging this happens</technical_language>

Target:
private Map executeCommand(String lines, InterpreterContext context, Map<String, Integer> userSessionMap) throws LivyException { String json; try { json = executeHTTP(property.get("zeppelin.livy.url") + "/sessions/" + userSessionMap.get(context.getAuthenticationInfo().getUser()) + "/statements", "POST", "{\"code\": \"" + StringEscapeUtils.escapeJson(lines) + "\"}", context.getParagraphId()); } catch (Exception e) { throw new LivyException("Error executing command in Livy", e); } if (json == null || json.matches("^(\")?Session (\'[0-9]+\' )?not found(.?\"?)$")) { LOGGER.warn("Livy session has been lost!"); throw new LivyNoSessionException(); } try { Map jsonMap = gson.fromJson(json, new TypeToken<Map>() { }.getType()); return jsonMap; } catch (Exception e) { LOGGER.error("Error executeCommand", e); throw new LivyException("Error parsing Livy response", e); } }
Source:
<code><START> public boolean checkThreadAccess() { <END> return mEnforcer.checkThreadAccess(); }</code><technical_language>mark of ThreadBound methods final, long else is overriding them. point of deriving this class is allow base class handle them, derived classes accidentally override :)</technical_language>

Target:
public final boolean checkThreadAccess() { return mEnforcer.checkThreadAccess(); }
Source:
<code>private void stopCommonServices() { if (leaderElection != null && leaderElection.isRunning()) { try { leaderElection.stopElectionThread(); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } if (rpcServer != null) { rpcServer.stop(); } if (namesystem != null) { namesystem.close(); } if (pauseMonitor != null) { pauseMonitor.stop(); } if(mdCleaner != null){ mdCleaner.stopMDCleanerMonitor(); } if (plugins != null) { for (ServicePlugin p : plugins) { try { p.stop(); } catch (Throwable t) { LOG.warn("ServicePlugin " + p + " could not be stopped", t); } } } if (revocationListFetcherService != null) { try { revocationListFetcherService.serviceStop(); } catch (Exception ex) { LOG.warn("Exception while stopping CRL fetcher service, but we are shutting down anyway"); } } stopHttpServer(); }</code><technical_language>logger If want print something</technical_language>

Target:
private void stopCommonServices() { if (leaderElection != null && leaderElection.isRunning()) { try { leaderElection.stopElectionThread(); } catch (InterruptedException e) { LOG.warn("LeaderElection thread stopped",e); } } if (rpcServer != null) { rpcServer.stop(); } if (namesystem != null) { namesystem.close(); } if (pauseMonitor != null) { pauseMonitor.stop(); } if(mdCleaner != null){ mdCleaner.stopMDCleanerMonitor(); } if (plugins != null) { for (ServicePlugin p : plugins) { try { p.stop(); } catch (Throwable t) { LOG.warn("ServicePlugin " + p + " could not be stopped", t); } } } if (revocationListFetcherService != null) { try { revocationListFetcherService.serviceStop(); } catch (Exception ex) { LOG.warn("Exception while stopping CRL fetcher service, but we are shutting down anyway"); } } stopHttpServer(); }
Source:
<code>private void acquireUnmanagedUsbController( VmBase vmBase, List<VmDevice> managedUsbControllers, List<VmDevice> unmanagedControllers) { if (unmanagedControllers.size() > 1) { throw new IllegalStateException(format("At most one unmanaged USB controller expected for VM=%s(%s), found=%s", vmBase.getName(), vmBase.getId(), unmanagedControllers)); } final UsbControllerModel controllerModel = getUsbControllerModel(vmBase); <START> if (unmanagedControllers.size() != 1) { <END> return; } removeVmDevices(managedUsbControllers); VmDevice device = unmanagedControllers.iterator().next(); device.setManaged(true); device.setPlugged(true); device.setReadOnly(false); device.setSpecParams(createUsbControllerSpecParams(controllerModel.libvirtName, 0)); vmDeviceDao.update(device); }</code><technical_language>Gilad Bracha's quote: "live is death", I "positive is negative" :) replacing with: if (unmanagedControllers.isEmpty())</technical_language>

Target:
private void acquireUnmanagedUsbController( VmBase vmBase, List<VmDevice> managedUsbControllers, List<VmDevice> unmanagedControllers) { if (unmanagedControllers.size() > 1) { throw new IllegalStateException(format("At most one unmanaged USB controller expected for VM=%s(%s), found=%s", vmBase.getName(), vmBase.getId(), unmanagedControllers)); } final UsbControllerModel controllerModel = getUsbControllerModel(vmBase); if (unmanagedControllers.isEmpty()) { return; } removeVmDevices(managedUsbControllers); VmDevice device = unmanagedControllers.iterator().next(); device.setManaged(true); device.setPlugged(true); device.setReadOnly(false); device.setSpecParams(createUsbControllerSpecParams(controllerModel.libvirtName, 0)); vmDeviceDao.update(device); }
Source:
<code>public SchemaGen( String dialect, String model, File outputPath, String delimiter) { this.dialect = dialectFor(dialect); if (this.dialect instanceof DB2Dialect) { System.err.println(JpaDdlGenI18n.dialectRequiresModification.text(this.dialect.getClass().getSimpleName())); } <START> <END> this.delimiter = delimiter; this.model = JpaSource.Models.getModel(model); if (this.model == null) { throw new RuntimeException(JpaDdlGenI18n.invalidModel.text()); } this.outputPath = outputPath; if (this.outputPath != null && !this.outputPath.exists()) { this.outputPath.mkdirs(); String logMsg = JpaDdlGenI18n.directoryLocationCreated.text(this.outputPath.getAbsolutePath()); logger.log(Level.INFO, logMsg); } }</code><technical_language>this check DerbyDialect</technical_language>

Target:
public SchemaGen( String dialect, String model, File outputPath, String delimiter) { this.dialect = dialectFor(dialect); if ((this.dialect instanceof DB2Dialect) | (this.dialect instanceof DerbyDialect)) { System.err.println(JpaDdlGenI18n.dialectRequiresModification.text(this.dialect.getClass().getSimpleName())); } this.delimiter = delimiter; this.model = JpaSource.Models.getModel(model); if (this.model == null) { throw new RuntimeException(JpaDdlGenI18n.invalidModel.text()); } this.outputPath = outputPath; if (this.outputPath != null && !this.outputPath.exists()) { this.outputPath.mkdirs(); String logMsg = JpaDdlGenI18n.directoryLocationCreated.text(this.outputPath.getAbsolutePath()); logger.log(Level.INFO, logMsg); } }
Source:
<code>public void close() throws IOException { if (closing) { return; } closing = true; sslEngine.closeOutbound(); try { if (!flush(netWriteBuffer)) { <START> throw new IOException("Remaining data in the network buffer, can't send SSL close message."); <END> } netWriteBuffer.clear(); SSLEngineResult handshake = sslEngine.wrap(emptyBuf, netWriteBuffer); if (handshake.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Invalid close state, will not send network data."); } netWriteBuffer.flip(); flush(netWriteBuffer); socketChannel.socket().close(); socketChannel.close(); } catch (IOException ie) { log.warn("Failed to send SSL Close message ", ie); } key.attach(null); key.cancel(); }</code><technical_language>if this is right do. channel is blocking. If write wrote partially, flush return false this throw</technical_language>

Target:
public void close() throws IOException { if (closing) { return; } closing = true; sslEngine.closeOutbound(); try { if (!flush(netWriteBuffer)) { throw new IOException("Remaining data in the network buffer, can't send SSL close message."); } netWriteBuffer.clear(); SSLEngineResult handshake = sslEngine.wrap(emptyBuf, netWriteBuffer); if (handshake.getStatus() != SSLEngineResult.Status.CLOSED) { throw new IOException("Invalid close state, will not send network data."); } netWriteBuffer.flip(); flush(netWriteBuffer); socketChannel.socket().close(); socketChannel.close(); } catch (IOException ie) { logger.warn("Failed to send SSL close message ", ie); } key.attach(null); key.cancel(); }
Source:
<code>public void setUpRefs() throws IOException { Set<String> existingRefs = new LinkedHashSet<String>( repository.getRefDatabase().getRefs( getPubSubRefFromLocal(remote, Constants.R_REFS)) .keySet()); Map<String, Ref> refs = getRemoteRefs(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { String ref = entry.getKey(); String existingRef = ref.substring(Constants.R_REFS.length()); existingRefs.remove(existingRef); String pubsubRef = getPubSubRefFromLocal(remote, ref); if (repository.getRef(pubsubRef) != null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(entry.getValue().getObjectId()); <START> ru.setRefLogMessage("pubsub setup", true); <END> ru.update(); } for (String r : existingRefs) { String pubsubRef = getPubSubRefFromLocal( remote, Constants.R_REFS + r); if (repository.getRef(pubsubRef) == null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setForceUpdate(true); ru.delete(); } }</code><technical_language>I want false here. true appends of "created", "fast forward", "forced-update" message. Considering this is basically unconditional copy, I this information is useful user. Also, kinda feels this JGitText, inspecting existing usages of setRefLogMessage shows aren't. defer Shawn</technical_language>

Target:
public void setUpRefs() throws IOException, URISyntaxException { remoteConfig = new RemoteConfig(repository.getConfig(), remoteName); Set<String> existingRefs = new LinkedHashSet<String>( repository.getRefDatabase().getRefs( getPubSubRefFromRemote(remoteName, Constants.R_REFS)) .keySet()); Map<String, Ref> refs = getRemoteRefs(); for (Map.Entry<String, Ref> entry : refs.entrySet()) { String ref = entry.getKey(); String existingRef = ref.substring(Constants.R_REFS.length()); existingRefs.remove(existingRef); } for (String r : existingRefs) { String pubsubRef = getPubSubRefFromRemote( remoteName, Constants.R_REFS + r); if (repository.getRef(pubsubRef) == null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setForceUpdate(true); ru.delete(); } for (Map.Entry<String, Ref> entry : refs.entrySet()) { String ref = entry.getKey(); String pubsubRef = getPubSubRefFromRemote(remoteName, ref); if (repository.getRef(pubsubRef) != null) continue; RefUpdate ru = repository.updateRef(pubsubRef); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(entry.getValue().getObjectId()); ru.setRefLogMessage("pubsub setup", false); ru.forceUpdate(); } }
Source:
<code>private String getInstrumentCodeLine(String encodedParam, int lineNo, int colNo){ <START> return "module$exports$instrument$code.instrumentCodeInstance.instrumentCode(\"" + <END> encodedParam + "\", " + lineNo + ", " + colNo + ")"; }</code><technical_language>Strings.lenientFormat here</technical_language>

Target:
private String getInstrumentCodeLine(String encodedParam, int lineNo, int colNo) { return Strings.lenientFormat( "%s(\"%s\", %s, %s)", "module$exports$instrument$code.instrumentCodeInstance.instrumentCode", encodedParam, lineNo, colNo); }
Source:
<code>public void track(File file) throws IOException { <START> DirCache dc = repository.lockDirCache(); <END> try { String repoPath = getRepoRelativePath(new Path(file.getPath()) .toString()); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[100]; try { int size = fis.read(buffer); while (size > 0) { bos.write(buffer, 0, size); size = fis.read(buffer); } } finally { fis.close(); bos.close(); } final byte[] newContent = bos.toByteArray(); DirCacheEditor editor = dc.editor(); editor.add(new PathEdit(repoPath) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.REGULAR_FILE); ent.setAssumeValid(false); ObjectInserter inserter = repository.newObjectInserter(); ent.setLength(newContent.length); ent.setLastModified(System.currentTimeMillis()); InputStream in = new ByteArrayInputStream(newContent); try { ent.setObjectId(inserter.insert(Constants.OBJ_BLOB, newContent.length, in)); inserter.flush(); } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { in.close(); } catch (IOException e) { } } } }); try { editor.commit(); } catch (RuntimeException e) { if (e.getCause() instanceof IOException) throw (IOException) e.getCause(); else throw e; } } finally { dc.unlock(); } }</code><technical_language>I clean in a way: AFAIK do longer a difference "add index" "track", I delete track() replace addToIndex(). In addition jgit AddCommand heavily simplify this class</technical_language>

Target:
public void track(File file) throws IOException { String repoPath = getRepoRelativePath(new Path(file.getPath()) .toString()); try { new Git(repository).add().addFilepattern(repoPath).call(); } catch (NoFilepatternException e) { throw new IOException(e.getMessage()); } }
Source:
<code><START> public static Double get(String key, double def) { <END> String value = configuration.getProperty(key); return value == null ? def : ParseUtil.parseDoubleOrDefault(value, def); }</code><technical_language>returning boxed Double</technical_language>

Target:
public static double get(String key, double def) { String value = configuration.getProperty(key); return value == null ? def : ParseUtil.parseDoubleOrDefault(value, def); }
Source:
<code>public String intercept(ActionInvocation invocation) throws Exception { ActionContext context = invocation.getInvocationContext(); HttpServletRequest request = context.getServletRequest(); invocation.addPreResultListener(this); if (exemptedPaths.contains(request.getContextPath())) { return invocation.invoke(); } if (resourceIsolationPolicy.isRequestAllowed(request)) { return invocation.invoke(); } <START> beforeResult(invocation, SC_FORBIDDEN); <END> return SC_FORBIDDEN; }</code><technical_language>work this line? -- registered a pre-result</technical_language>

Target:
public String intercept(ActionInvocation invocation) throws Exception { ActionContext context = invocation.getInvocationContext(); HttpServletRequest request = context.getServletRequest(); addVaryHeaders(invocation); String contextPath = request.getContextPath(); if (exemptedPaths.contains(contextPath)) { return invocation.invoke(); } if (resourceIsolationPolicy.isRequestAllowed(request)) { return invocation.invoke(); } logger.atDebug().log( "Fetch metadata rejected cross-origin request to %s", contextPath ); return SC_FORBIDDEN; }
Source:
<code>public static void killCaches(boolean clear, Collection<Cache> caches) { for (Cache c : caches) { try { if (c != null && c.getStatus() == ComponentStatus.RUNNING) { TransactionManager tm = c.getAdvancedCache().getTransactionManager(); if (tm != null) { try { tm.rollback(); } catch (Exception e) { } } if (c.getAdvancedCache().getRpcManager() != null) { <START> log.tracef("Local entries on %s before stopping: %d", c.getAdvancedCache().getRpcManager().getAddress(), <END> c.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).size()); } else { log.tracef("Local entries before stopping: %d", c.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).size()); } if (clear) { try { c.clear(); } catch (Exception ignored) } c.stop(); } } catch (Throwable t) { } } }</code><technical_language>Local size sounds "entries"</technical_language>

Target:
public static void killCaches(boolean clear, Collection<Cache> caches) { for (Cache c : caches) { try { if (c != null && c.getStatus() == ComponentStatus.RUNNING) { TransactionManager tm = c.getAdvancedCache().getTransactionManager(); if (tm != null) { try { tm.rollback(); } catch (Exception e) { } } if (c.getAdvancedCache().getRpcManager() != null) { log.tracef("Local size on %s before stopping: %d", c.getAdvancedCache().getRpcManager().getAddress(), c.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).size()); } else { log.tracef("Local size before stopping: %d", c.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).size()); } if (clear) { try { c.clear(); } catch (Exception ignored) } c.stop(); } } catch (Throwable t) { } } }
Source:
<code>long gtk_draw (long widget, long cairo) { if ((state & OBSCURED) != 0) return 0; if (!hooksPaint ()) return 0; GdkRectangle rect = new GdkRectangle (); OS.gdk_cairo_get_clip_rectangle (cairo, rect); Event event = new Event (); event.count = 1; Rectangle eventRect = new Rectangle (rect.x, rect.y, rect.width, rect.height); <START> Rectangle eventBounds = DPIUtil.autoScaleDown (eventRect); <END> if ((style & SWT.MIRRORED) != 0) eventBounds.x = DPIUtil.autoScaleDown (getClientWidth ()) - eventBounds.width - eventBounds.x; event.setBounds (eventBounds); GCData data = new GCData (); if (OS.GTK_VERSION <= OS.VERSION (3, 9, 0)) { data.cairo = cairo; } GC gc = event.gc = GC.gtk_new (this, data); gc.setClipping (eventBounds.x, eventBounds.y, eventBounds.width, eventBounds.height); drawWidget (gc); sendEvent (SWT.Paint, event); gc.dispose (); event.gc = null; return 0; }</code><technical_language>Style: inline this? Multiple rectangle creation debugging a bit more difficult. Instead, do: Rectangle eventBounds = DPIUtil.autoScaleDown (new Rectangle (rect.x, rect.y, rect.width, rect.height));</technical_language>

Target:
long gtk_draw (long widget, long cairo) { if ((state & OBSCURED) != 0) return 0; if (!hooksPaint ()) return 0; GdkRectangle rect = new GdkRectangle (); OS.gdk_cairo_get_clip_rectangle (cairo, rect); Event event = new Event (); event.count = 1; Rectangle eventBounds = DPIUtil.autoScaleDown (new Rectangle (rect.x, rect.y, rect.width, rect.height)); if ((style & SWT.MIRRORED) != 0) eventBounds.x = DPIUtil.autoScaleDown (getClientWidth ()) - eventBounds.width - eventBounds.x; event.setBounds (eventBounds); GCData data = new GCData (); if (OS.GTK_VERSION <= OS.VERSION (3, 9, 0)) { data.cairo = cairo; } GC gc = event.gc = GC.gtk_new (this, data); gc.setClipping (eventBounds.x, eventBounds.y, eventBounds.width, eventBounds.height); drawWidget (gc); sendEvent (SWT.Paint, event); gc.dispose (); event.gc = null; return 0; }
Source:
<code><START> public FormValidation doCheckURIEncoding(StaplerRequest request) { <END> Jenkins.get().checkPermission(Jenkins.ADMINISTER); final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }</code><technical_language>unrelated</technical_language>

Target:
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }
Source:
<code>private static boolean isPreserveAuthorization(Request request) { <START> return request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY) == TRUE; <END> }</code><technical_language>equals clear care identity semantics (readers verify is set), fine java TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY));</technical_language>

Target:
private static boolean isPreserveAuthorization(Request request) { return TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY)); }
Source:
<code>public String showCommandLine(VMRunnerConfiguration configuration, ILaunch launch, IProgressMonitor monitor) throws CoreException { CommandDetails cmd = getCommandLine(configuration, launch, monitor); <START> if (monitor.isCanceled()) { <END> return ""; } String[] cmdLine = cmd.getCommandLine(); cmdLine = quoteWindowsArgs(cmdLine); return getCmdLineAsString(cmdLine); }</code><technical_language>BTW, this is another potential NPE "implicit statement" rework</technical_language>

Target:
public String showCommandLine(VMRunnerConfiguration configuration, ILaunch launch, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor); CommandDetails cmd = getCommandLine(configuration, launch, subMonitor); if (subMonitor.isCanceled()) { return ""; } String[] cmdLine = cmd.getCommandLine(); cmdLine = quoteWindowsArgs(cmdLine); return getCmdLineAsString(cmdLine); }
Source:
<code>public VisualEditorPageObject clickApplyChanges() { <START> for (int i=0; i<buttonsList.size(); i++) { <END> if (buttonsList.get(i).getText().contentEquals("Apply changes")) { buttonsList.get(i).click(); } } return this; }</code><technical_language>is this loop necessary? need click a single element? However, I wrong 100% is checked</technical_language>

Target:
public VisualEditorPageObject clickApplyChanges() { wait.forElementVisible(applyChangesButton); applyChangesButton.click(); return this; }
Source:
<code>public RoleData getRuntimeRole(String name) { Role role = authorizationConfigService.get() .getRoles() .stream() .filter(r -> r.getName().equals(name)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(name)); if (SystemRole.ADMIN.name().equals(name)) { RuntimeRole adminRole = new RuntimeRole(role, (a) -> new AdminAccessModel(a)); <START> return new RuntimeRole(adminRole, (a) -> new AuthorizedAccessModel(a)); <END> } else if (SystemRole.ANONYMOUS.name().equals(name)) { return new RuntimeRole(role, (a) -> new AnonymousAccessModel(a)); } return new RuntimeRole(role, (a) -> new AuthorizedAccessModel(a)); }</code><technical_language>admin everything, I pointless wrap AuthorizedAccessModel</technical_language>

Target:
public Role getRuntimeRole(String name) { RoleData role = authorizationConfigService.get() .getRoles() .stream() .filter(r -> r.getName().equals(name)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(name)); if (SystemRole.ADMIN.name().equals(name)) { RuntimeRole adminRole = new RuntimeRole(role, (a) -> new AdminAccessModel()); return new RuntimeRole(adminRole, (a) -> new AuthenticatedAccessModel(a)); } else if (SystemRole.ANONYMOUS.name().equals(name)) { return new RuntimeRole(role, (a) -> new AnonymousAccessModel(a)); } return new RuntimeRole(role, (a) -> new AuthenticatedAccessModel(a)); }
Source:
<code>private void processSplashElementIcon( IConfigurationElement configurationElement) { String iconImageFilePath = configurationElement.getAttribute(F_ELEMENT_ICON); if ((iconImageFilePath == null) || (iconImageFilePath.length() == 0)) { return; } <START> ImageDescriptor descriptor = <END> ResourceLocator.imageDescriptorFromBundle( configurationElement.getNamespaceIdentifier(), iconImageFilePath).orElse(null); if (descriptor == null) { return; } Image image = descriptor.createImage(); if (image == null) { return; } if ((image.getBounds().width != F_IMAGE_WIDTH) || (image.getBounds().height != F_IMAGE_HEIGHT)) { image.dispose(); return; } fImageList.add(image); }</code><technical_language>this template needs a version check</technical_language>

Target:
private void processSplashElementIcon( IConfigurationElement configurationElement) { String iconImageFilePath = configurationElement.getAttribute(F_ELEMENT_ICON); if ((iconImageFilePath == null) || (iconImageFilePath.length() == 0)) { return; } ImageDescriptor descriptor = AbstractUIPlugin.imageDescriptorFromPlugin( configurationElement.getNamespaceIdentifier(), iconImageFilePath); if (descriptor == null) { return; } Image image = descriptor.createImage(); if (image == null) { return; } if ((image.getBounds().width != F_IMAGE_WIDTH) || (image.getBounds().height != F_IMAGE_HEIGHT)) { image.dispose(); return; } fImageList.add(image); }
Source:
<code>public static String getCredential(@Nullable Pair<String, String> usernameAndPasswordToAuthWith) { String credential; <START> if (usernameAndPasswordToAuthWith == null) { <END> Pair<User, String> userAndDomain = getUserAndDomain(true); credential = ModernHttpRequester.getCredential(userAndDomain.first, userAndDomain.second); } else { credential = ModernHttpRequester.getCredential( buildDomainUser(usernameAndPasswordToAuthWith.first), buildAppPassword(usernameAndPasswordToAuthWith.second)); } return credential; }</code><technical_language>This needs check if individual components of Pair null, HttpRequestGenerator.buildNoAuthGenerator() is generate a request, results in a call CommCareApplication.buildHttpRequester() usernameAndPasswordToAuthWith parameter is of form Pair<>(null, null)</technical_language>

Target:
public static String getCredential(@Nullable Pair<String, String> usernameAndPasswordToAuthWith) { String credential; if (usernameAndPasswordToAuthWith == null) { Pair<User, String> userAndDomain = getUserAndDomain(true); credential = getCredential(userAndDomain.first, userAndDomain.second); } else { credential = getCredential( buildDomainUser(usernameAndPasswordToAuthWith.first), buildAppPassword(usernameAndPasswordToAuthWith.second)); } return credential; }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AuthenticationManager.setAuthenticationChallengeHandler(customAuthenticationChallengeHandler); mOAuthLoginDialog = new Dialog(this); mMapView = (MapView) findViewById(R.id.mapViewLayout); try { OAuthConfiguration config = new OAuthConfiguration(getString(R.string.portal_url), getString(R.string.client_id), getString(R.string.redirect_url)); AuthenticationManager.addOAuthConfiguration(config); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } Portal portal = new Portal(getString(R.string.portal_url)); <START> portal.loadAsync(); <END> PortalItem webMapItem = new PortalItem(portal, getString(R.string.webmap_id)); ArcGISMap map = new ArcGISMap(webMapItem); mMapView.setMap(map); }</code><technical_language>need call load</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AuthenticationManager.setAuthenticationChallengeHandler(mCustomAuthenticationChallengeHandler); mOAuthLoginDialog = new Dialog(this); mMapView = findViewById(R.id.mapView); try { OAuthConfiguration config = new OAuthConfiguration(getString(R.string.portal_url), getString(R.string.client_id), getString(R.string.redirect_url)); AuthenticationManager.addOAuthConfiguration(config); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage(), e.getCause()); } Portal portal = new Portal(getString(R.string.portal_url), true); PortalItem webMapItem = new PortalItem(portal, getString(R.string.webmap_id)); ArcGISMap map = new ArcGISMap(webMapItem); mMapView.setMap(map); }
Source:
<code>public void will_execute_a_void_based_on_strongly_typed_one_parameter_function() throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString())) <START> .will(answerVoid((VoidAnswer1<String>) target::simpleMethod)); <END> iMethods.simpleMethod("string"); verify(target, times(1)).simpleMethod("string"); }</code><technical_language>Please revert changes. While build locally Java 8, target Java 6 I compiling older jdks. Travis build sadly test jdk 6 longer deprecated broken in containers :sob:</technical_language>

Target:
public void will_execute_a_void_based_on_strongly_typed_one_parameter_function() throws Exception { final IMethods target = mock(IMethods.class); given(iMethods.simpleMethod(anyString())) .will(answerVoid(new VoidAnswer1<String>() { public void answer(String s) { target.simpleMethod(s); } })); iMethods.simpleMethod("string"); verify(target, times(1)).simpleMethod("string"); }
Source:
<code>public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); <START> originalClusterVersion = (originalClusterVersion == null) ? Version.v3_6_compat : originalClusterVersion; <END> oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { oldClusterVersionOfSnapshotWithMemory = null; } }</code><technical_language>please change lowest supported version now</technical_language>

Target:
public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? Version.v4_0 : originalClusterVersion; oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { oldClusterVersionOfSnapshotWithMemory = null; } }
Source:
<code>public void testIsDataStall_EvaluationDnsWithDnsTimeoutCount() { WrappedNetworkMonitor wrappedMonitor = makeMeteredWrappedNetworkMonitor(); wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000); makeDnsTimeoutEvent(wrappedMonitor, 3); assertFalse(wrappedMonitor.isDataStall()); makeDnsTimeoutEvent(wrappedMonitor, 2); <START> assertTrue(wrappedMonitor.isDataStall()); <END> setConsecutiveDnsTimeoutThreshold(51); wrappedMonitor = makeMeteredWrappedNetworkMonitor(); wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000); makeDnsTimeoutEvent(wrappedMonitor, 50); assertFalse(wrappedMonitor.isDataStall()); makeDnsTimeoutEvent(wrappedMonitor, 1); assertTrue(wrappedMonitor.isDataStall()); }</code><technical_language>Do need test counter reset case this? e.g. makeDnsSuccess(...) assertFalse(...)</technical_language>

Target:
public void testIsDataStall_EvaluationDnsWithDnsTimeoutCount() { WrappedNetworkMonitor wrappedMonitor = makeMeteredWrappedNetworkMonitor(); wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000); makeDnsTimeoutEvent(wrappedMonitor, 3); assertFalse(wrappedMonitor.isDataStall()); makeDnsSuccessEvent(wrappedMonitor, 1); makeDnsTimeoutEvent(wrappedMonitor, 2); assertFalse(wrappedMonitor.isDataStall()); makeDnsTimeoutEvent(wrappedMonitor, 3); assertTrue(wrappedMonitor.isDataStall()); setConsecutiveDnsTimeoutThreshold(51); wrappedMonitor = makeMeteredWrappedNetworkMonitor(); wrappedMonitor.setLastProbeTime(SystemClock.elapsedRealtime() - 1000); makeDnsTimeoutEvent(wrappedMonitor, 50); assertFalse(wrappedMonitor.isDataStall()); makeDnsTimeoutEvent(wrappedMonitor, 1); assertTrue(wrappedMonitor.isDataStall()); }
Source:
<code>public boolean validate(IDocument document, int offset, DocumentEvent event) { if (!isOffsetValid(offset)) return fIsValidated= false; if (isSupportingRequiredProposals()) { CompletionProposal coreProposal= ((MemberProposalInfo) getProposalInfo()).fProposal; if (coreProposal.isSuffixProposal()) <START> fIsValidated= isValidPrefix(getPrefix(document, offset)); <END> else fIsValidated= CharOperation.camelCaseMatch(getPrefix(document, offset).toCharArray(), TextProcessor.deprocess(getDisplayString()).toCharArray()) || CharOperation.substringMatch(getPrefix(document, offset), TextProcessor.deprocess(getDisplayString())); } else fIsValidated= isValidPrefix(getPrefix(document, offset)); if (fIsValidated && event != null) { int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength; final int newLength= Math.max(getReplacementLength() + delta, 0); setReplacementLength(newLength); } return fIsValidated; }</code><technical_language>avoid duplication of line if simply add this if: && (((MemberProposalInfo) getProposalInfo()).fProposal).isSuffixProposal()</technical_language>

Target:
public boolean validate(IDocument document, int offset, DocumentEvent event) { if (!isOffsetValid(offset)) return fIsValidated= false; if (isSupportingRequiredProposals() && !(((MemberProposalInfo) getProposalInfo()).fProposal).isSuffixProposal()) { fIsValidated= CharOperation.camelCaseMatch(getPrefix(document, offset).toCharArray(), TextProcessor.deprocess(getDisplayString()).toCharArray()) || CharOperation.substringMatch(getPrefix(document, offset), TextProcessor.deprocess(getDisplayString())); } else fIsValidated= isValidPrefix(getPrefix(document, offset)); if (fIsValidated && event != null) { int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength; final int newLength= Math.max(getReplacementLength() + delta, 0); setReplacementLength(newLength); } return fIsValidated; }
Source:
<code>private void waitForOperation(String operationName, int maxSeconds) throws InterruptedException { GetOperationRequest request = GetOperationRequest.newBuilder().setName(operationName).build(); for (int i = 0; i < maxSeconds * 2; i++) { Thread.sleep(500); Operation response = client.getOperation(request); if (response.getDone()) { switch (response.getResultCase()) { case ERROR: <START> throw new RuntimeException("Cluster could not be created: " + response.getError()); <END> case RESPONSE: return; case RESULT_NOT_SET: throw new IllegalStateException( "System returned invalid response for Operation check: " + response); } } } throw new IllegalStateException( String.format("Waited %d seconds and operation was not complete", maxSeconds)); }</code><technical_language>"Cluster resized"</technical_language>

Target:
public void waitForOperation(String operationName, int maxSeconds) throws InterruptedException { long endTimeMillis = TimeUnit.SECONDS.toMillis(maxSeconds) + System.currentTimeMillis(); GetOperationRequest request = GetOperationRequest.newBuilder().setName(operationName).build(); do { Thread.sleep(500); Operation response = client.getOperation(request); if (response.getDone()) { switch (response.getResultCase()) { case RESPONSE: return; case ERROR: throw new RuntimeException("Cluster could not be resized: " + response.getError()); case RESULT_NOT_SET: throw new IllegalStateException( "System returned invalid response for Operation check: " + response); } } } while (System.currentTimeMillis() < endTimeMillis); throw new IllegalStateException( String.format("Waited %d seconds and cluster was not resized yet.", maxSeconds)); }