auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { while (!testContext.isStopped()) { int key = random.nextInt(keyCount); int increment = random.nextInt(maxIncrement); int delayMs=0; if(maxProcessorDelayMs > 0){ delayMs = random.nextInt(maxProcessorDelayMs) + minProcessorDelayMs; } cache.invoke(key, new IncrementEntryProcessor(increment, delayMs)); increments[key] += increment; } sleepMs(completeTaskDelayMs); targetInstance.getList(basename).add(increments); }

Target:
public void run() { while (!testContext.isStopped()) { int key = random.nextInt(keyCount); int increment = random.nextInt(maxIncrement); int delayMs=0; if(maxProcessorDelayMs > 0){ delayMs = random.nextInt(maxProcessorDelayMs - minProcessorDelayMs) + minProcessorDelayMs; } cache.invoke(key, new IncrementEntryProcessor(increment, delayMs)); increments[key] += increment; } sleepMs(completeTaskDelayMs); targetInstance.getList(basename).add(increments); }
Source:
private static void configureController(HierarchicalConfiguration<ImmutableNode> src, MgcpControllerConfiguration dst) { dst.setAddress(src.getString("address", MgcpControllerConfiguration.ADDRESS)); dst.setPort(src.getInt("port", MgcpControllerConfiguration.PORT)); dst.setMgcpBufferSize(src.getInt("mgcpBuffer[@size]", MgcpControllerConfiguration.MGCP_BUFFER_SIZE)); List<HierarchicalConfiguration<ImmutableNode>> endpoints = src.childConfigurationsAt("endpoints"); for (HierarchicalConfiguration<ImmutableNode> endpoint : endpoints) { MgcpEndpointConfiguration endpointConfig = new MgcpEndpointConfiguration(); endpointConfig.setName(endpoint.getString("[@name]")); endpointConfig.setRelayType(endpoint.getString("[@relay]", "mixer")); dst.addEndpoint(endpointConfig); } }

Target:
private static void configureController(HierarchicalConfiguration<ImmutableNode> src, MgcpControllerConfiguration dst) { dst.setAddress(src.getString("address", MgcpControllerConfiguration.ADDRESS)); dst.setPort(src.getInt("port", MgcpControllerConfiguration.PORT)); dst.setChannelBuffer(src.getInt("channelBuffer", MgcpControllerConfiguration.CHANNEL_BUFFER)); List<HierarchicalConfiguration<ImmutableNode>> endpoints = src.childConfigurationsAt("endpoints"); for (HierarchicalConfiguration<ImmutableNode> endpoint : endpoints) { MgcpEndpointConfiguration endpointConfig = new MgcpEndpointConfiguration(); endpointConfig.setName(endpoint.getString("[@name]")); endpointConfig.setRelayType(endpoint.getString("[@relay]", "mixer")); dst.addEndpoint(endpointConfig); } }
Source:
public TestkitResponse process( TestkitState testkitState ) { return Optional.ofNullable( testkitState.getSessionStates().getOrDefault( data.sessionId, null ) ) .map( sessionState -> { Session session = sessionState.getSession(); session.readTransaction( tx -> { System.out.println( "Start" ); sessionState.setRetryableState( 0 ); String txId = testkitState.newId(); testkitState.getTransactions().put( txId, tx ); testkitState.getResponseWriter().accept( retryableTry( txId ) ); while ( true ) { testkitState.getProcessor().get(); switch ( sessionState.retryableState ) { case 0: break; case 1: return 0; case -1: if ( !"".equals( sessionState.retryableErrorId ) ) { throw testkitState.getErrors().get( sessionState.retryableErrorId ); } else { throw new RuntimeException( "Error from client in retryable tx" ); } } } } ); return retryableDone(); } ).orElseThrow( () -> new RuntimeException( "Could not find session" ) ); }

Target:
public TestkitResponse process( TestkitState testkitState ) { return Optional.ofNullable( testkitState.getSessionStates().getOrDefault( data.sessionId, null ) ) .map( sessionState -> { Session session = sessionState.getSession(); session.readTransaction( handle( testkitState, sessionState ) ); return retryableDone(); } ).orElseThrow( () -> new RuntimeException( "Could not find session" ) ); }
Source:
public Observable<Boolean> copyMediaFile(String originFilePath, String destinationFilePath) { File originalFile = new File(originFilePath); try { boolean copied = fileHelper.copyFile(originalFile, new File(destinationFilePath)) == null; if (copied) { return Observable.error(new Exception("Error copying video file")); } else { originalFile.delete(); } return Observable.just(true); } catch (IOException e) { return Observable.error(e); } }

Target:
public Observable<Boolean> copyMediaFile(String originFilePath, String destinationFilePath) { File originalFile = new File(originFilePath); try { String copiedFilePath = fileHelper .copyFile(originalFile, new File(destinationFilePath)); if (copiedFilePath != null) { originalFile.delete(); } else { return Observable.error(new Exception("Error copying video file")); } return Observable.just(true); } catch (IOException e) { return Observable.error(e); } }
Source:
public AWSCredentials getCredentials() { getCredentialsCalled = true; return credentialsFetcher.getCredentials(); }

Target:
public AWSCredentials getCredentials() { AWSCredentials creds = credentialsFetcher.getCredentials(); getCredentialsCalled = true; return creds; }
Source:
public void flush() throws IOException { if (started.get()) { Future future = exec.schedule(new ConsumerRunnable(), 0, TimeUnit.MILLISECONDS); try { future.get(FLUSH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.error(e, e.getMessage()); } catch (ExecutionException e) { log.error(e, e.getMessage()); } catch (TimeoutException e) { log.error(e, e.getMessage()); } } }

Target:
public void flush() throws IOException { if (started.get()) { Future future = exec.schedule(new ConsumerRunnable(), 0, TimeUnit.MILLISECONDS); try { future.get(FLUSH_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { if (e instanceof InterruptedException) { throw new RuntimeException("interrupted flushing elements from queue", e); } log.error(e, e.getMessage()); } } }
Source:
protected int readNoFilter(int[] positions, int positionCount) throws IOException { int streamPosition = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skip(position - streamPosition); streamPosition = position; } if (presentStream != null && !presentStream.nextBit()) { if ((nonDeterministicFilter && filter.testNull()) || nullsAllowed) { if (outputRequired) { nulls[outputPositionCount] = true; } outputPositionCount++; } } else { int scale = (int) scaleStream.next(); long rescale = Decimals.rescale(dataStream.nextLong(), scale, decimalType.getScale()); if (outputRequired) { values[outputPositionCount] = rescale; } if (nullsAllowed && presentStream != null) { nulls[outputPositionCount] = false; } outputPositionCount++; } outputPositions = positions; streamPosition++; } return streamPosition; }

Target:
protected int readNoFilter(int[] positions, int positionCount) throws IOException { int streamPosition = 0; for (int i = 0; i < positionCount; i++) { int position = positions[i]; if (position > streamPosition) { skip(position - streamPosition); streamPosition = position; } if (presentStream != null && !presentStream.nextBit()) { nulls[i] = true; } else { values[i] = Decimals.rescale(dataStream.nextLong(), (int) scaleStream.next(), this.scale); if (presentStream != null) { nulls[i] = false; } } streamPosition++; } outputPositionCount = positionCount; return streamPosition; }
Source:
public DoubleColumnSelector makeDoubleColumnSelector( IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerDoubleColumnSelector implements DoubleColumnSelector { @Override public double get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return 0L; } float floatVal = (Float) dims[dimIndex]; return (double) floatVal; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerDoubleColumnSelector(); }

Target:
public DoubleColumnSelector makeDoubleColumnSelector( IncrementalIndexStorageAdapter.EntryHolder currEntry, IncrementalIndex.DimensionDesc desc ) { final int dimIndex = desc.getIndex(); class IndexerDoubleColumnSelector implements DoubleColumnSelector { @Override public double get() { final Object[] dims = currEntry.getKey().getDims(); if (dimIndex >= dims.length) { return 0.0; } float floatVal = (Float) dims[dimIndex]; return (double) floatVal; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { } } return new IndexerDoubleColumnSelector(); }
Source:
public void setUp() throws Exception { Admin admin = TEST_UTIL.getAdmin(); if (admin.tableExists(TABLE_NAME)) { TEST_UTIL.deleteTable(TABLE_NAME); } TableDescriptor tableDesc = TableDescriptorBuilder.newBuilder(TABLE_NAME) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam1")).build(); int startKey = 0; int endKey = 80000; admin.createTable(tableDesc, Bytes.toBytes(startKey), Bytes.toBytes(endKey), 9); }

Target:
public void setUp() throws Exception { final TableName tableName = TableName.valueOf(name.getMethodName()); TableDescriptor tableDesc = TableDescriptorBuilder.newBuilder(tableName) .setColumnFamily(ColumnFamilyDescriptorBuilder.of("fam1")).build(); int startKey = 0; int endKey = 80000; TEST_UTIL.getAdmin().createTable(tableDesc, Bytes.toBytes(startKey), Bytes.toBytes(endKey), 9); }
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { String name = o.getExpression().getText().toLowerCase(); if (name.lastIndexOf('.') != -1) { if (name.lastIndexOf('.') == name.length() - 1) { return; } name = name.substring(name.lastIndexOf('.') + 1); } if (!formattingFunctions.containsKey(name)) { return; } Integer position = formattingFunctions.get(name); List<GoExpression> arguments = o.getArgumentList().getExpressionList(); if (arguments.size() <= position) { return; } Integer placeholdersCount = getPlaceholders(arguments.get(position)); Integer parameterCount = arguments.size() - position - 1; if (!placeholdersCount.equals(parameterCount)) { PsiElement element = o.getExpression(); String message = String.format("Got %d placeholder(s) for %d arguments(s)", placeholdersCount, parameterCount); if (placeholdersCount < parameterCount) { element = arguments.get(position); } holder.registerProblem(element, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } } }; }

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitCallExpr(@NotNull GoCallExpr o) { PsiReference psiReference = o.getExpression().getReference(); if (psiReference == null) return; PsiElement resolved = psiReference.resolve(); if (!(resolved instanceof GoFunctionOrMethodDeclaration)) return; if (!isInCorrectPackage((GoFunctionOrMethodDeclaration)resolved)) return; String name = getName((GoFunctionOrMethodDeclaration)resolved); Integer placeholderPosition = FORMATTING_FUNCTIONS.get(name); List<GoExpression> arguments = o.getArgumentList().getExpressionList(); if (arguments.size() <= placeholderPosition) return; GoExpression placeholder = arguments.get(placeholderPosition); if (!isStringPlaceholder(placeholder)) { String message = "Value used for formatting text does not appear to be a string"; holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); return; } int parameterCount = arguments.size() - placeholderPosition - 1; int placeholdersCount = getPlaceholders(placeholder); if (placeholdersCount == -1 || placeholdersCount == parameterCount) return; String message = String.format("Got %d placeholder(s) for %d arguments(s)", placeholdersCount, parameterCount); holder.registerProblem(placeholder, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); } }; }
Source:
public SecretVaultValueReader(File activitiConfigFile) throws BPSFault { try (FileInputStream fileInputStream = new FileInputStream(activitiConfigFile)) { StAXOMBuilder builder = new StAXOMBuilder(fileInputStream); activitiConfigElement = builder.getDocumentElement(); secretResolver = SecretResolverFactory.create(activitiConfigElement, true); } catch (XMLStreamException | IOException e) { log.error("Unable to read activiti.xml file", e); throw new BPSFault("Failed to find activiti.xml", e); } }

Target:
public SecretVaultValueReader(File activitiConfigFile) throws BPSFault { try (FileInputStream fileInputStream = new FileInputStream(activitiConfigFile)) { StAXOMBuilder builder = new StAXOMBuilder(fileInputStream); activitiConfigElement = builder.getDocumentElement(); secretResolver = SecretResolverFactory.create(activitiConfigElement, true); } catch (XMLStreamException | IOException e) { throw new BPSFault("Failed to find activiti.xml", e); } }
Source:
public Client setup() throws Exception { final Settings settings = Settings.builder() .put("node.name", InetAddress.getLocalHost().getHostName()) .put("discovery.zen.ping.multicast.enabled", false) .putArray("discovery.zen.ping.unicast.hosts", seeds) .put("path.home", "/tmp/" + UUID.randomUUID()) .build(); final Node node = NodeBuilder .nodeBuilder() .settings(settings) .client(true) .clusterName(clusterName) .node(); return node.client(); }

Target:
public Client setup() throws Exception { final Settings settings = Settings .builder() .put("node.name", InetAddress.getLocalHost().getHostName()) .put("discovery.zen.ping.multicast.enabled", false) .putArray("discovery.zen.ping.unicast.hosts", seeds) .put("path.home", Files.createTempDirectory("tmp")) .build(); final Node node = NodeBuilder .nodeBuilder() .settings(settings) .client(true) .clusterName(clusterName) .node(); return node.client(); }
Source:
public void intercept(HttpServletRequest req, HttpServletResponse resp) { ContentSecurityPolicy csp = BEANS.get(ContentSecurityPolicy.class).appendScriptSrc("'unsafe-inline'"); BrowserInfo browserInfo = BrowserInfo.createFrom(req); if (browserInfo.isWebkit()) { String resolvedSelfUri = m_browserUri.toString(); csp .appendImgSrc(resolvedSelfUri) .appendStyleSrc(resolvedSelfUri); } String cspToken = csp.toToken(); resp.setHeader(HttpServletControl.HTTP_HEADER_CSP, cspToken); if (browserInfo.isMshtml()) { resp.setHeader(HttpServletControl.HTTP_HEADER_CSP_LEGACY, cspToken); } }

Target:
public void intercept(HttpServletRequest req, HttpServletResponse resp) { ContentSecurityPolicy csp = BEANS.get(ContentSecurityPolicy.class).appendScriptSrc("'unsafe-inline'"); BrowserInfo browserInfo = BrowserInfo.createFrom(req); if (browserInfo.isWebkit()) { String resolvedSelfUri = m_browserUri.toString(); csp .appendImgSrc(resolvedSelfUri) .appendStyleSrc(resolvedSelfUri); } String cspToken = csp.toToken(); if (browserInfo.isMshtml()) { resp.setHeader(HttpServletControl.HTTP_HEADER_CSP_LEGACY, cspToken); } else { resp.setHeader(HttpServletControl.HTTP_HEADER_CSP, cspToken); } }
Source:
private Mono<Boolean> ensureValidKeyAvailable() { boolean keyAvailable = !(this.key == null && keyCollection != null); if (!keyAvailable) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().flatMap(jwk -> { this.key = new AtomicReference<>(jwk); initializeCryptoClients(); return Mono.just(this.key.get().isValid()); }); } else { return getKey().flatMap(kvKey -> { this.key = new AtomicReference<>(kvKey.getKey()); initializeCryptoClients(); return Mono.just(key.get().isValid()); }); } } else { return Mono.defer(() -> Mono.just(true)); } }

Target:
private Mono<Boolean> ensureValidKeyAvailable() { boolean keyNotAvailable = (this.key == null && keyCollection != null); if (keyNotAvailable) { if (keyCollection.equals(SECRETS_COLLECTION)) { return getSecretKey().map(jwk -> { this.key = (jwk); initializeCryptoClients(); return this.key.isValid(); }); } else { return getKey().map(kvKey -> { this.key = (kvKey.getKey()); initializeCryptoClients(); return key.isValid(); }); } } else { return Mono.defer(() -> Mono.just(true)); } }
Source:
public String dateFormatChange(String time) { String k; DateTimeFormatter input_format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); DateTimeFormatter output_format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); LocalDateTime parsed_time = LocalDateTime.parse(time, input_format); ZonedDateTime final_time = ZonedDateTime.of(parsed_time, ZoneId.of("Asia/Kolkata")) .withZoneSameInstant(ZoneId.of("UTC+00:00")); k = String.valueOf(output_format.format(final_time)); return k; }

Target:
public String dateFormatChange(String time) { String k; DateTimeFormatter input_format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); DateTimeFormatter output_format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); LocalDateTime parsed_time = LocalDateTime.parse(time, input_format); ZonedDateTime ldtZoned = parsed_time.atZone(ZoneId.systemDefault()); ZonedDateTime final_time = ldtZoned.withZoneSameInstant(ZoneId.of("UTC")); k = String.valueOf(output_format.format(final_time)); return k; }
Source:
private void deleteEntry(final int index) { final LocalItem infoItem = itemListAdapter.getItemsList() .get(index); if(infoItem instanceof StreamStatisticsEntry) { final StreamStatisticsEntry entry = (StreamStatisticsEntry) infoItem; final Disposable onDelte = recordManager.deleteStreamHistory(entry.streamId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( howManyDelted -> Snackbar.make(getView(), R.string.one_item_deleted, Snackbar.LENGTH_SHORT).show(), throwable -> showSnackBarError(throwable, UserAction.DELETE_FROM_HISTORY, "none", "Deleting item failed", R.string.general_error)); disposables.add(onDelte); } }

Target:
private void deleteEntry(final int index) { final LocalItem infoItem = itemListAdapter.getItemsList() .get(index); if(infoItem instanceof StreamStatisticsEntry) { final StreamStatisticsEntry entry = (StreamStatisticsEntry) infoItem; final Disposable onDelete = recordManager.deleteStreamHistory(entry.streamId) .observeOn(AndroidSchedulers.mainThread()) .subscribe( howManyDelted -> { if(getView() != null) { Snackbar.make(getView(), R.string.one_item_deleted, Snackbar.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), R.string.one_item_deleted, Toast.LENGTH_SHORT).show(); } }, throwable -> showSnackBarError(throwable, UserAction.DELETE_FROM_HISTORY, "none", "Deleting item failed", R.string.general_error)); disposables.add(onDelete); } }
Source:
public void shouldAuthoriseChargeForValidCardDetails() throws Exception { String uniqueChargeId = "983794837598475"; setupCharge(uniqueChargeId); given().port(app.getLocalPort()) .contentType(JSON) .body(validCardDetails) .post(cardUrlForChargeId(uniqueChargeId)) .then() .statusCode(204); assertChargeStatusIs(uniqueChargeId, "AUTHORIZATION SUCCESS"); }

Target:
public void shouldAuthoriseChargeForValidCardDetails() throws Exception { String chargeId = createNewCharge(); givenSetup() .body(validCardDetails) .post(cardUrlFor(chargeId)) .then() .statusCode(204); assertChargeStatusIs(chargeId, "AUTHORIZATION SUCCESS"); }
Source:
public void run(String workflowNameArg, String matchPattern) throws Exception { Properties systemProps = loadSystemProperties(); systemProps.setProperty("environment", DigdagClient.objectMapper().writeValueAsString(env)); try (DigdagEmbed digdag = new DigdagEmbed.Bootstrap() .setEnvironment(env) .setSystemPlugins(loadSystemPlugins(systemProps)) .addModules(binder -> { binder.bind(ResumeStateManager.class).in(Scopes.SINGLETON); binder.bind(YamlMapper.class).in(Scopes.SINGLETON); binder.bind(Run.class).toInstance(this); }) .overrideModulesWith((binder) -> { binder.bind(OperatorManager.class).to(OperatorManagerWithSkip.class).in(Scopes.SINGLETON); }) .initializeWithoutShutdownHook()) { run(systemProps, digdag.getInjector(), workflowNameArg, matchPattern); } }

Target:
public void run(String workflowNameArg, String matchPattern) throws Exception { Properties systemProps = loadSystemProperties(); try (DigdagEmbed digdag = new DigdagEmbed.Bootstrap() .setEnvironment(env) .setSystemConfig(PropertyUtils.toConfigElement(systemProps)) .setSystemPlugins(loadSystemPlugins(systemProps)) .addModules(binder -> { binder.bind(SecretAccessPolicy.class).to(LocalSecretAccessPolicy.class).in(Scopes.SINGLETON); binder.bind(SecretStoreManager.class).to(LocalSecretStoreManager.class).in(Scopes.SINGLETON); binder.bind(ResumeStateManager.class).in(Scopes.SINGLETON); binder.bind(YamlMapper.class).in(Scopes.SINGLETON); binder.bind(Run.class).toInstance(this); }) .overrideModulesWith((binder) -> { binder.bind(OperatorManager.class).to(OperatorManagerWithSkip.class).in(Scopes.SINGLETON); }) .initializeWithoutShutdownHook()) { run(systemProps, digdag.getInjector(), workflowNameArg, matchPattern); } }
Source:
private void setProperty(String envProperty, String initParam, Properties properties) { Environment env = context.getBean(Environment.class); String value = env .getProperty(SharedUtil.camelCaseToDashSeparated(envProperty)); if (value == null) { value = env.getProperty(envProperty); } if (value != null) { properties.put(initParam, value); } }

Target:
private void setProperty(String envProperty, String initParam, Properties properties) { Environment env = context.getBean(Environment.class); String value = env.getProperty(upperCaseToDashSeparated(envProperty)); if (value == null) { value = env.getProperty(envProperty); } if (value != null) { properties.put(initParam, value); } }
Source:
protected Void doInBackground(ServiceRequest... params) { synchronized (this) { while (mServiceRequestController == null) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } mServiceRequestController.handleServiceRequest(params[0]); return null; }

Target:
protected Void doInBackground(ServiceRequest... params) { synchronized (this) { while (mServiceRequestController == null) { try { this.wait(); } catch (InterruptedException e) { Log.d("Y:" + this.getClass().getName(),e.getMessage()); } } } if (params.length > 0 && params[0] != null) { mServiceRequestController.handleServiceRequest(params[0]); } else { throw new IllegalArgumentException(); } return null; }
Source:
public boolean isBinaryEquivalent(IDeclaration obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof StructDeclaration)) { return false; } StructDeclaration other = (StructDeclaration) obj; if (fFields.length != other.fFields.length) { return false; } List<IDeclaration> localDecs = new ArrayList<>(); localDecs.addAll(Arrays.asList(fFields)); List<IDeclaration> otherDecs = new ArrayList<>(); otherDecs.addAll(Arrays.asList(other.fFields)); for (int i = 0; i < fFields.length; i++) { if (!otherDecs.get(i).isBinaryEquivalent(localDecs.get(i))) { return false; } } if (fMaxAlign != other.fMaxAlign) { return false; } return true; }

Target:
public boolean isBinaryEquivalent(IDeclaration obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof StructDeclaration)) { return false; } StructDeclaration other = (StructDeclaration) obj; if (fFields.length != other.fFields.length) { return false; } List<IDeclaration> localDecs = Arrays.asList(fFields); List<IDeclaration> otherDecs = Arrays.asList(other.fFields); for (int i = 0; i < fFields.length; i++) { if (!otherDecs.get(i).isBinaryEquivalent(localDecs.get(i))) { return false; } } if (fMaxAlign != other.fMaxAlign) { return false; } return true; }
Source:
public void onNext(final AllocatedEvaluator allocatedEvaluator) { if (dataLoader.isDataLoaderRequest()) { idMap.put(allocatedEvaluator.getId(), DataLoader.class.getName()); dataLoader.handleDataLoadingEvalAlloc(allocatedEvaluator); } else if (emResourceRequestManager.bindCallback(allocatedEvaluator)) { idMap.put(allocatedEvaluator.getId(), ElasticMemory.class.getName()); allocatedEvaluator.submitContextAndService(getContextConfiguration(), getServiceConfiguration()); } else { LOG.warning("Unknown evaluator allocated. Ignore " + allocatedEvaluator.toString()); } }

Target:
public void onNext(final AllocatedEvaluator allocatedEvaluator) { if (dataLoader.isDataLoaderRequest()) { evalToRequestorMap.put(allocatedEvaluator.getId(), DataLoader.class.getName()); dataLoader.handleDataLoadingEvalAlloc(allocatedEvaluator); } else if (emResourceRequestManager.bindCallback(allocatedEvaluator)) { evalToRequestorMap.put(allocatedEvaluator.getId(), ElasticMemory.class.getName()); allocatedEvaluator.submitContextAndService(getContextConfiguration(), getServiceConfiguration()); } else { LOG.warning("Unknown evaluator allocated. Ignore " + allocatedEvaluator); allocatedEvaluator.close(); } }
Source:
public void execute(JPakeClient jClient) { Logger.debug(LOG_TAG, "Verifying their key."); ExtendedJSONObject verificationObj = jClient.jIncoming; if (!verificationObj.get(Constants.JSON_KEY_TYPE).equals( jClient.theirSignerId + "3")) { Logger.error(LOG_TAG, "Invalid round 3 message: " + verificationObj.toJSONString()); jClient.abort(Constants.JPAKE_ERROR_WRONGMESSAGE); return; } ExtendedJSONObject payload; try { payload = verificationObj .getObject(Constants.JSON_KEY_PAYLOAD); } catch (NonObjectJSONException e) { Logger.error(LOG_TAG, "JSON exception.", e); jClient.abort(Constants.JPAKE_ERROR_INVALID); return; } String theirCiphertext = (String) payload .get(Constants.JSON_KEY_CIPHERTEXT); String iv = (String) payload.get(Constants.JSON_KEY_IV); boolean correctPairing; try { correctPairing = verifyCiphertext(theirCiphertext, iv, jClient.myKeyBundle); } catch (UnsupportedEncodingException e) { Logger.error(LOG_TAG, "Unsupported encoding.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } catch (CryptoException e) { Logger.error(LOG_TAG, "Crypto exception.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } if (correctPairing) { Logger.debug(LOG_TAG, "Keys verified successfully."); jClient.paired = true; jClient.onPaired(); } else { Logger.error(LOG_TAG, "Keys don't match."); jClient.abort(Constants.JPAKE_ERROR_KEYMISMATCH); } }

Target:
public void execute(JPakeClient jClient) { Logger.debug(LOG_TAG, "Verifying their key."); ExtendedJSONObject verificationObj = jClient.jIncoming; String signerId = (String) verificationObj.get(Constants.JSON_KEY_TYPE); if (!signerId.equals(jClient.theirSignerId + "3")) { Logger.error(LOG_TAG, "Invalid round 3 message: " + verificationObj.toJSONString()); jClient.abort(Constants.JPAKE_ERROR_WRONGMESSAGE); return; } ExtendedJSONObject payload; try { payload = verificationObj.getObject(Constants.JSON_KEY_PAYLOAD); } catch (NonObjectJSONException e) { Logger.error(LOG_TAG, "JSON exception.", e); jClient.abort(Constants.JPAKE_ERROR_INVALID); return; } String theirCiphertext = (String) payload.get(Constants.JSON_KEY_CIPHERTEXT); String iv = (String) payload.get(Constants.JSON_KEY_IV); boolean correctPairing; try { correctPairing = verifyCiphertext(theirCiphertext, iv, jClient.myKeyBundle); } catch (UnsupportedEncodingException e) { Logger.error(LOG_TAG, "Unsupported encoding.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } catch (CryptoException e) { Logger.error(LOG_TAG, "Crypto exception.", e); jClient.abort(Constants.JPAKE_ERROR_INTERNAL); return; } if (correctPairing) { Logger.debug(LOG_TAG, "Keys verified successfully."); jClient.paired = true; jClient.onPaired(); } else { Logger.error(LOG_TAG, "Keys don't match."); jClient.abort(Constants.JPAKE_ERROR_KEYMISMATCH); } }
Source:
private String queryServer() throws GAWrapperException, UnirestException, InvalidProtocolBufferException { final String url = makeUrl(urlRoot, path); if (wireTracker != null) { wireTracker.theUrl = url; } try { HttpResponse<JsonNode> response = queryServer(url); if (wireTracker != null) { wireTracker.bodyReceived = response.getBody().toString(); wireTracker.setResponseStatus(fromInt(response.getStatus())); } int httpStatus = response.getStatus(); if (httpStatus == HttpStatus.SC_OK) { return response.getBody().toString(); } else { String json = response.getBody().toString(); Common.GAException.Builder exceptionBuilder = Common.GAException.newBuilder(); try { JsonFormat.parser().merge(json, exceptionBuilder); } catch (InvalidProtocolBufferException e) { log.warn("Failure when processing GAException: BODY <" + json + ">: ", e.toString()); throw e; } log.info("Throwing GAException for " + json + ", status " + httpStatus); throw new GAWrapperException(exceptionBuilder.build(), httpStatus); } } catch (UnirestException e) { log.warn("problem communicating with " + url, e.getMessage()); log.debug(e.toString()); throw e; } }

Target:
private String queryServer() throws GAWrapperException, UnirestException, InvalidProtocolBufferException { final String url = makeUrl(urlRoot, path); if (wireTracker != null) { wireTracker.theUrl = url; } try { HttpResponse<JsonNode> response = queryServer(url); if (wireTracker != null) { wireTracker.bodyReceived = response.getBody().toString(); wireTracker.setResponseStatus(fromInt(response.getStatus())); } int httpStatus = response.getStatus(); if (httpStatus == HttpStatus.SC_OK) { return response.getBody().toString(); } else { String json = response.getBody().toString(); Common.GAException.Builder exceptionBuilder = Common.GAException.newBuilder(); try { JsonFormat.parser().merge(json, exceptionBuilder); } catch (InvalidProtocolBufferException e) { log.warn("Failure when processing GAException: BODY <" + json + ">: ", e.toString()); throw e; } log.warn("Throwing GAException for " + json + ", status " + httpStatus); throw new GAWrapperException(exceptionBuilder.build(), httpStatus); } } catch (UnirestException e) { log.warn("problem communicating with " + url, e.getMessage()); throw e; } }
Source:
public void benchmark() throws ExecutionException, InterruptedException { Semaphore semaphore = new Semaphore(futureCount); ArrayList<SettableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < futureCount; i++) { SettableFuture<?> future = SettableFuture.create(); future.addListener(() -> semaphore.release(1), directExecutor()); futures.add(future); } ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures); futures.get(futureCount / 2).set(null); semaphore.acquireUninterruptibly(futureCount); anyComplete.get(); }

Target:
public void benchmark() throws Exception { Semaphore semaphore = new Semaphore(futureCount); ArrayList<SettableFuture<?>> futures = new ArrayList<>(); for (int i = 0; i < futureCount; i++) { SettableFuture<?> future = SettableFuture.create(); future.addListener(() -> semaphore.release(1), directExecutor()); futures.add(future); } ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures); futures.get(futureCount / 2).set(null); semaphore.acquireUninterruptibly(futureCount); anyComplete.get(); }
Source:
public void addLiteralToForm(EditConfigurationVTwo editConfig, FieldVTwo field, String var, String[] valuesArray) { List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null; if( valueList != null && valueList.size() > 0 ) { List<Literal> literalsArray = new ArrayList<Literal>(); for(String value:valueList) { value = N3EditUtils.stripInvalidXMLChars(value); if (!StringUtils.isEmpty(value)) { String rangeLang = field.getRangeLang(); try { if (_vreq != null ) { if (editConfig.getLiteralsInScope().get("label").get(0).getLanguage() != "") { rangeLang = editConfig.getLiteralsInScope().get("label").get(0).getLanguage(); } else { rangeLang = _vreq.getLocale().getLanguage(); if (!_vreq.getLocale().getCountry().isEmpty()) { rangeLang += "-" + _vreq.getLocale().getCountry(); } } } } catch (Exception e) { } literalsArray.add(createLiteral( value, field.getRangeDatatypeUri(), rangeLang)); } } literalsFromForm.put(var, literalsArray); }else{ log.debug("could not find value for parameter " + var ); } }

Target:
public void addLiteralToForm(EditConfigurationVTwo editConfig, FieldVTwo field, String var, String[] valuesArray) { List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null; if( valueList != null && valueList.size() > 0 ) { List<Literal> literalsArray = new ArrayList<Literal>(); for(String value:valueList) { value = N3EditUtils.stripInvalidXMLChars(value); if (!StringUtils.isEmpty(value)) { String rangeLang = field.getRangeLang(); try { if (_vreq != null ) { Boolean getLabelLanguage = false; if (!StringUtils.isBlank(editConfig.formUrl) && editConfig.formUrl.contains("RDFSLabelGenerator")) { getLabelLanguage = true; } if (!StringUtils.isBlank(editConfig.getLiteralsInScope().get("label").get(0).getLanguage()) && getLabelLanguage) { rangeLang = editConfig.getLiteralsInScope().get("label").get(0).getLanguage(); } else { rangeLang = _vreq.getLocale().getLanguage(); if (!_vreq.getLocale().getCountry().isEmpty()) { rangeLang += "-" + _vreq.getLocale().getCountry(); } } } } catch (Exception e) { } literalsArray.add(createLiteral( value, field.getRangeDatatypeUri(), rangeLang)); } } literalsFromForm.put(var, literalsArray); }else{ log.debug("could not find value for parameter " + var ); } }
Source:
public void shouldRemoveNonExistingElement() { final Seq<Integer> t = of(1, 2, 3); assertThat(t.remove(4)).isEqualTo(t); assertNotSame(t, t.remove(4)); }

Target:
public void shouldRemoveNonExistingElement() { final Seq<Integer> t = of(1, 2, 3); assertThat(t.remove(4)).isEqualTo(t).isNotSameAs(t); }
Source:
public void ValidationStereotypesListClass2Test() { EList<Stereotype> appliedStereotypes = class2.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype2); expectedStereotypes.add(stereotype1); assertEquals(appliedStereotypes, expectedStereotypes); }

Target:
public void ValidationStereotypesListClass2Test() { EList<Stereotype> appliedStereotypes = class2.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype2); expectedStereotypes.add(stereotype1); assertEquals("The stereotypes applied on the class must be the same as the expected stereotypes.", appliedStereotypes, expectedStereotypes); }
Source:
public List<String> getSelection() throws RemoteException { String name = getSelectorName(); Object selection = browser.syncRun(String.format( "return view.getFieldValue('%s')", name)); if (selection != null) { String raw = selection.toString(); String[] items = raw.replaceAll("\\[", "").replaceAll("\\]", "") .replaceAll("\\s", "").split(","); return Arrays.asList(items); } return null; }

Target:
public List<String> getSelection() throws RemoteException { String name = getSelectorName(); Object selection = browser.syncRun(String.format( "return view.getFieldValue('%s')", name)); if (selection != null) { String raw = selection.toString(); String[] items = raw.replaceAll("(\\[|\\]|\\s)", "").split(","); return Arrays.asList(items); } return null; }
Source:
public void writeTaskContainerMapping(String taskName, String containerId) { String existingContainerId = taskNameToContainerId.get(taskName); if (existingContainerId != null && !existingContainerId.equals(containerId)) { LOG.info("Task \"{}\" moved from container to container {}", new Object[]{taskName, existingContainerId, containerId}); } else { LOG.debug("Task \"{}\" assigned to container {}", taskName, containerId); } if (containerId == null) { metadataStore.remove(keySerde.toBytes(taskName)); taskNameToContainerId.remove(taskName); } else { metadataStore.put(keySerde.toBytes(taskName), valueSerde.toBytes(containerId)); taskNameToContainerId.put(taskName, containerId); } }

Target:
public void writeTaskContainerMapping(String taskName, String containerId) { String existingContainerId = taskNameToContainerId.get(taskName); if (existingContainerId != null && !existingContainerId.equals(containerId)) { LOG.info("Task \"{}\" moved from container to container {}", new Object[]{taskName, existingContainerId, containerId}); } else { LOG.debug("Task \"{}\" assigned to container {}", taskName, containerId); } if (containerId == null) { metadataStore.delete(keySerde.toBytes(taskName)); taskNameToContainerId.remove(taskName); } else { metadataStore.put(keySerde.toBytes(taskName), valueSerde.toBytes(containerId)); taskNameToContainerId.put(taskName, containerId); } }
Source:
TayamLuminousEnigmaEffect() { super(Outcome.Benefit); this.filter = new FilterPermanentCard("permanent card in your graveyard with converted mana cost 3 or less"); this.filter.add(new ConvertedManaCostPredicate(ComparisonType.FEWER_THAN, 4)); }

Target:
TayamLuminousEnigmaEffect() { super(Outcome.Benefit); staticText = ", then return a permanent card with converted mana cost 3 or less from your graveyard to the battlefield"; }
Source:
public void setServer(AbstractServer server) { router.reset(); router.setIgnoreMessageValidation(true); router.addServer(server); }

Target:
public void setServer(AbstractServer server) { router.reset(); router.addServer(server); }
Source:
public static QoS map(QosBase entity, QoS template) { QoS model = template != null ? template : new QoS(); model.setId(entity.getId().toString()); model.setName(entity.getName()); model.setType(org.ovirt.engine.api.model.QosType.fromValue(entity.getQosType().toString()).name().toLowerCase()); model.setDataCenter(new DataCenter()); model.getDataCenter().setId(entity.getStoragePoolId().toString()); model.setDescription(entity.getDescription()); switch (entity.getQosType()) { case STORAGE: StorageQos storageQos = null; if (entity instanceof StorageQos) { storageQos = (StorageQos) entity; } if (storageQos == null) { return model; } model.setMaxThroughput(storageQos.getMaxThroughput()); model.setMaxReadThroughput(storageQos.getMaxReadThroughput()); model.setMaxWriteThroughput(storageQos.getMaxWriteThroughput()); model.setMaxIops(storageQos.getMaxIops()); model.setMaxReadIops(storageQos.getMaxReadIops()); model.setMaxWriteIops(storageQos.getMaxWriteIops()); case CPU: CpuQos cpuQos = null; if (entity instanceof CpuQos) { cpuQos = (CpuQos) entity; } if (cpuQos == null) { return model; } model.setCpuLimit(cpuQos.getCpuLimit()); default: break; } return model; }

Target:
public static QoS map(QosBase entity, QoS template) { QoS model = template != null ? template : new QoS(); model.setId(entity.getId().toString()); model.setName(entity.getName()); model.setType(org.ovirt.engine.api.model.QosType.fromValue(entity.getQosType().toString()).name().toLowerCase()); model.setDataCenter(new DataCenter()); model.getDataCenter().setId(entity.getStoragePoolId().toString()); model.setDescription(entity.getDescription()); switch (entity.getQosType()) { case STORAGE: StorageQos storageQos = null; if (entity instanceof StorageQos) { storageQos = (StorageQos) entity; } if (storageQos == null) { return model; } model.setMaxThroughput(storageQos.getMaxThroughput()); model.setMaxReadThroughput(storageQos.getMaxReadThroughput()); model.setMaxWriteThroughput(storageQos.getMaxWriteThroughput()); model.setMaxIops(storageQos.getMaxIops()); model.setMaxReadIops(storageQos.getMaxReadIops()); model.setMaxWriteIops(storageQos.getMaxWriteIops()); break; case CPU: CpuQos cpuQos = null; if (entity instanceof CpuQos) { cpuQos = (CpuQos) entity; } if (cpuQos == null) { return model; } model.setCpuLimit(cpuQos.getCpuLimit()); break; default: break; } return model; }
Source:
public void testVirtCanMoveToMaintenance() { VDS vds = new VDS(); vds.getDynamicData().setstatus(VDSStatus.PreparingForMaintenance); vds.getDynamicData().setvm_count(1); assertFalse(virtStrategy.canMoveToMaintenance(vds)); vds.getDynamicData().setvm_count(0); assertTrue(virtStrategy.canMoveToMaintenance(vds)); }

Target:
public void testVirtCanMoveToMaintenance() { VDS vds = new VDS(); vds.setstatus(VDSStatus.PreparingForMaintenance); vds.setvm_count(1); assertFalse(virtStrategy.canMoveToMaintenance(vds)); vds.setvm_count(0); assertTrue(virtStrategy.canMoveToMaintenance(vds)); }
Source:
public ConfigXml(Context context) throws OpenConfigException { mContext = context; mConfigFile = Constants.getConfigFile(mContext); boolean isFirstStart = !mConfigFile.exists(); if (isFirstStart) { Log.i(TAG, "App started for the first time. Generating keys and config."); generateKeysConfig(context); } readConfig(); if (isFirstStart) { boolean changed = false; changed = changeLocalDeviceName() || changed; changed = changeDefaultFolder() || changed; Element options = (Element) mConfig.getDocumentElement() .getElementsByTagName("options").item(0); changed = setConfigElement(options, "restartOnWakeup", "true") || changed; if (changed) { saveChanges(); } } }

Target:
public ConfigXml(Context context) throws OpenConfigException { mContext = context; mConfigFile = Constants.getConfigFile(mContext); boolean isFirstStart = !mConfigFile.exists(); if (isFirstStart) { Log.i(TAG, "App started for the first time. Generating keys and config."); generateKeysConfig(context); } readConfig(); if (isFirstStart) { boolean changed = false; changeLocalDeviceName(); changed = changeDefaultFolder() || changed; if (changed) { saveChanges(); } } }
Source:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); waitForElementByElement(getInfoLink); getInfoLink.click(); switchOutOfIFrame(); return new ArticlePageObject(driver); }

Target:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); try { waitForElementByElement(getInfoLink); getInfoLink.click(); return new ArticlePageObject(driver); } finally { switchOutOfIFrame(); } }
Source:
public String getDescription() { return "Folder"; }

Target:
public String getDescription() { return Messages.BuildStatusFolderIcon_Description(); }
Source:
public CompletableFuture<Void> invoke(boolean success) { if (trace) { log.tracef("After completion callback, success=%d", success); } nonTxPutFromLoadInterceptor.endInvalidating(key, lockOwner, success); return null; }

Target:
public CompletableFuture<Void> invoke(boolean success) { if (trace) { log.tracef("After completion callback, success=%b", success); } nonTxPutFromLoadInterceptor.endInvalidating(key, lockOwner, success); return null; }
Source:
public static void main(String[] args) { try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (FileNotFoundException | CustomException e) { logException(e); } try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (final FileNotFoundException | CustomException | AnotherCustomException e) { logException(e); } }

Target:
public static void main(String[] args) { try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (FileNotFoundException | CustomException e) { logException(e); } try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (final FileNotFoundException | CustomException | com.puppycrawl.tools.checkstyle.grammar.InputJava7MultiCatch.AnotherCustomException e) { logException(e); } }
Source:
public final Set<SequenceSegment> getSegments(final int start, final int end) { Set<SequenceSegment> set = new TreeSet<SequenceSegment>(); for (Set<SequenceSegment> bucket : buckets.subList(Math.max(0, start), Math.min(numberBuckets, end))) { set.addAll(bucket); } return set; }

Target:
public final Set<SequenceSegment> getSegments(final int start, final int end) { Set<SequenceSegment> set = new TreeSet<SequenceSegment>(); int startBucket = Math.max(0, start); int endBucket = Math.min(numberBuckets, end); for (Set<SequenceSegment> bucket : buckets.subList(startBucket, endBucket)) { set.addAll(bucket); } return set; }
Source:
protected void buildVmFloppy() { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDAO() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceType.getName(VmDeviceType.DISK), VmDeviceType.getName(VmDeviceType.FLOPPY)); for (VmDevice vmDevice : vmDevices) { XmlRpcStruct struct = new XmlRpcStruct(); struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); struct.add(VdsProperties.Index, "0"); addAddress(vmDevice, struct); struct.add(VdsProperties.Iface, "fdc"); struct.add(VdsProperties.PoolId, vm.getstorage_pool_id().toString()); struct.add(VdsProperties.DomainId, DbFacade.getInstance() .getStorageDomainDAO() .getIsoStorageDomainIdForPool(vm.getstorage_pool_id()) .toString()); struct.add(VdsProperties.ImageId, Guid.Empty.toString()); String file = StringUtils.string2Map(vmDevice.getSpecParams()).get("path"); struct.add(VdsProperties.VolumeId, file.substring(file.lastIndexOf('/') + 1)); struct.add(VdsProperties.Path, file); struct.add(VdsProperties.ReadOnly, new Boolean(vmDevice.getIsReadOnly()).toString()); devices.add(struct); break; } }

Target:
protected void buildVmFloppy() { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDAO() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceType.getName(VmDeviceType.DISK), VmDeviceType.getName(VmDeviceType.FLOPPY)); for (VmDevice vmDevice : vmDevices) { XmlRpcStruct struct = new XmlRpcStruct(); struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); struct.add(VdsProperties.Index, "0"); addAddress(vmDevice, struct); struct.add(VdsProperties.Iface, "fdc"); struct.add(VdsProperties.PoolId, vm.getstorage_pool_id().toString()); struct.add(VdsProperties.DomainId, DbFacade.getInstance() .getStorageDomainDAO() .getIsoStorageDomainIdForPool(vm.getstorage_pool_id()) .toString()); struct.add(VdsProperties.ImageId, Guid.Empty.toString()); String file = StringUtils.string2Map(vmDevice.getSpecParams()).get("path"); struct.add(VdsProperties.VolumeId, file.substring(file.lastIndexOf('/') + 1)); struct.add(VdsProperties.Path, file); struct.add(VdsProperties.ReadOnly, String.valueOf(vmDevice.getIsReadOnly())); devices.add(struct); break; } }
Source:
public static void main(String[] args) throws Exception { Options options = new Options(); Option addInstanceOption = Option.builder("addInstance") .desc("addInstance <instance> <password>") .hasArg(true) .numberOfArgs(2) .build(); options.addOption(addInstanceOption); Option removeInstanceOption = Option.builder("removeInstance") .hasArg(true) .build(); options.addOption(removeInstanceOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("addInstance")) { String[] values = cmd.getOptionValues("addInstance"); IdentityService service = getIdentityService(); service.addKieServerInstance(values[0], values[1]); log.infof("Instance <%1$s> added", values[0]); return; } if (cmd.hasOption("removeInstance")) { String value = cmd.getOptionValue("removeInstance"); IdentityService service = getIdentityService(); service.removeKieServerInstance(value); log.infof("Instance <%1$s> removed", value); return; } KieServerRouter router = new KieServerRouter(); router.start(HOST, PORT, PORT_TLS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { router.stop(); } }); }

Target:
public static void main(String[] args) throws Exception { Options options = new Options(); Option addInstanceOption = Option.builder(CMD_ADD_USER) .desc(CMD_ADD_USER + " <user> <password>") .hasArg(true) .numberOfArgs(2) .build(); options.addOption(addInstanceOption); Option removeInstanceOption = Option.builder(CMD_REMOVE_USER) .desc(CMD_REMOVE_USER + " <user>") .hasArg(true) .build(); options.addOption(removeInstanceOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); KieServerRouter router = new KieServerRouter(); if (cmd.hasOption(CMD_ADD_USER)) { String[] values = cmd.getOptionValues(CMD_ADD_USER); router.getIdentityService().addKieServerInstance(values[0], values[1]); log.infof("User <%1$s> added", values[0]); return; } if (cmd.hasOption(CMD_REMOVE_USER)) { String value = cmd.getOptionValue(CMD_REMOVE_USER); router.getIdentityService().removeKieServerInstance(value); log.infof("User <%1$s> removed", value); return; } router.start(HOST, PORT, PORT_TLS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { router.stop(); } }); }