auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public synchronized HttpClientRequest setStreamPriority(StreamPriority streamPriority) { synchronized (this) { if(!streamPriority.equals(getStreamPriority())) { this.streamPriority = streamPriority; if(stream != null) { stream.setStreamPriority(streamPriority); stream.writePriorityFrame(); } } } return this; }

Target:
public synchronized HttpClientRequest setStreamPriority(StreamPriority streamPriority) { synchronized (this) { if(!streamPriority.equals(getStreamPriority())) { this.streamPriority = streamPriority; if(stream != null) { stream.updatePriority(streamPriority); } } } return this; }
Source:
public DateTime getTo() { return to; }

Target:
public DateTime getTo() { return this.to; }
Source:
public void addReferenceToFilter() throws IOException { page.switchToReferenceToFilterSubTab(); page.addReferenceToFilter(GZIP_PAGE_FILTER_NAME); Assert.assertTrue("Filter reference " + GZIP_PAGE_FILTER_NAME + " is not present in table!", page.getConfigFragment().getResourceManager().isResourcePresent(GZIP_PAGE_FILTER_NAME)); }

Target:
public void addReferenceToFilter() throws Exception { page.switchToFilterReferencesSubTab(); page.addReferenceToFilter(GZIP_PAGE_FILTER_ADDRESS.getLastPairValue()); Assert.assertTrue("Filter reference " + GZIP_PAGE_FILTER_ADDRESS.getLastPairValue() + " is not present in table!", page.getConfigFragment().getResourceManager().isResourcePresent(GZIP_PAGE_FILTER_ADDRESS.getLastPairValue())); new ResourceVerifier(GZIP_FILTER_REFERENCE_ADDRESS, client).verifyExists(); }
Source:
public int getSkippedSince() { if (skippedSince==0 && getSkipCount()==1) { CaseResult prev = getPreviousResult(); if(prev!=null && !prev.isPassed()) this.skippedSince = prev.getSkippedSince(); else if (getRun() != null) { this.skippedSince = getRun().getNumber(); } else { LOGGER.warning("trouble calculating getSkippedSince. We've got prev, but no owner."); } } return skippedSince; }

Target:
public int getSkippedSince() { recomputeSkippedSinceIfNeeded(); return skippedSince; }
Source:
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performBoottime(context, operation, model); context.addStep(new AbstractDeploymentChainStep() { public void execute(DeploymentProcessorTarget processorTarget) { final int DEPENDENCIES_MICROPROFILE_REACTIVE_STREAMS_OPERATORS = 6288; processorTarget.addDeploymentProcessor(MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_NAME, DEPENDENCIES, DEPENDENCIES_MICROPROFILE_REACTIVE_STREAMS_OPERATORS, new ReactiveStreamsOperatorsDependencyProcessor()); } }, RUNTIME); MicroProfileReactiveStreamsOperatorsLogger.LOGGER.activatingSubsystem(); }

Target:
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performBoottime(context, operation, model); context.addStep(new AbstractDeploymentChainStep() { public void execute(DeploymentProcessorTarget processorTarget) { final int DEPENDENCIES_MICROPROFILE_REACTIVE_STREAMS_OPERATORS = 6320; processorTarget.addDeploymentProcessor(MicroProfileReactiveStreamsOperatorsExtension.SUBSYSTEM_NAME, DEPENDENCIES, DEPENDENCIES_MICROPROFILE_REACTIVE_STREAMS_OPERATORS, new ReactiveStreamsOperatorsDependencyProcessor()); } }, RUNTIME); MicroProfileReactiveStreamsOperatorsLogger.LOGGER.activatingSubsystem(); }
Source:
private void onBlock(Block block) { if (onTransactions(block.getTransactionsList())) { ++idx; if (idx == getBlocksRecount()) { Long newGasPrice = getGasPrice(); if (newGasPrice != null) { this.recommendedGasPrice = newGasPrice; } idx = 0; } } }

Target:
private void onBlock(Block block) { if (onTransactions(block.getTransactionsList())) { ++idx; if (idx >= getBlocksRecount()) { Long newGasPrice = getGasPrice(); if (newGasPrice != null) { this.recommendedGasPrice = newGasPrice; } idx = 0; } } }
Source:
public static <T> void put(String key, List<T> list) { throwExceptionIf(key == null, "Key cannot be null"); throwExceptionIf(list == null, "List<T> may not be null"); throwExceptionIf(list.size() == 0, "List<T> may not be null"); String fullText = getMarshalledValue(list.get(0), list); storage.put(key, fullText); }

Target:
public static <T> boolean put(String key, List<T> list) { if (list == null) { throw new NullPointerException("List<T> may not be null"); } if (list.size() == 0) { throw new NullPointerException("List<T> cannot be empty"); } String cipherText = encoder.encode(list); if (cipherText == null) { return false; } Class clazz = list.get(0).getClass(); String fullText = DataUtil.addType(cipherText, clazz, true); return storage.put(key, fullText); }
Source:
ArrayList<Domino> formPartialChain(ArrayList<Domino> current, List<Domino> remaining) { if (remaining.size() == 0) { if (isValidChain(current)) { return current; } else { throw new ChainNotFoundException("No chain found."); } } for (int i = 0; i < remaining.size(); i++) { ArrayList<Domino> newRemaining = new ArrayList<Domino>(remaining); newRemaining.remove(i); ArrayList<Domino> newChainA = new ArrayList<Domino>(current); newChainA.add(remaining.get(i)); ArrayList<Domino> newChainB = new ArrayList<Domino>(current); newChainB.add(new Domino(remaining.get(i).getRight(), remaining.get(i).getLeft())); if (isValidPartialChain(newChainA)) { try { return formPartialChain(newChainA, newRemaining); } catch (ChainNotFoundException e) { } } if (isValidPartialChain(newChainB)) { try { return formPartialChain(newChainB, newRemaining); } catch (ChainNotFoundException e) { } } } throw new ChainNotFoundException("No domino chain found."); }

Target:
ArrayList<Domino> formPartialChain(ArrayList<Domino> current, List<Domino> remaining) throws ChainNotFoundException { if (remaining.size() == 0) { if (isValidChain(current)) { return current; } else { throw new ChainNotFoundException("No domino chain found."); } } for (int i = 0; i < remaining.size(); i++) { ArrayList<Domino> newRemaining = new ArrayList<Domino>(remaining); newRemaining.remove(i); ArrayList<Domino> newChainA = new ArrayList<Domino>(current); newChainA.add(remaining.get(i)); ArrayList<Domino> newChainB = new ArrayList<Domino>(current); newChainB.add(new Domino(remaining.get(i).getRight(), remaining.get(i).getLeft())); if (isValidPartialChain(newChainA)) { try { return formPartialChain(newChainA, newRemaining); } catch (ChainNotFoundException e) { } } if (isValidPartialChain(newChainB)) { try { return formPartialChain(newChainB, newRemaining); } catch (ChainNotFoundException e) { } } } throw new ChainNotFoundException("No domino chain found."); }
Source:
public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); writeInteger(genericIntField1, dest); writeLong(genericLongField1, dest); writeString(genericStringField1, dest); writeString(genericStringField2, dest); ParcelCompat.writeBoolean(dest, genericBooleanField1); writeDouble(genericDoubleField1, dest); }

Target:
public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); writeInteger(genericIntField1, dest); writeLong(genericLongField1, dest); writeString(genericStringField1, dest); writeString(genericStringField2, dest); writeBoolean(genericBooleanField1, dest); writeDouble(genericDoubleField1, dest); }
Source:
public static boolean isStrictType(String type) { int idx; if((idx = type.indexOf(';')) < 0) { return false; } Map<String, String> parameters = Arrays.asList(type.substring(idx + 1).split(",")).stream().map(e -> e.split("=")).collect(Collectors.toMap(e -> ((String[]) e)[0], e -> ((String[]) e)[1])); if (parameters.containsKey("strict")) { return Boolean.parseBoolean(parameters.get("strict")); } return false; }

Target:
public static boolean isStrictType(String type) { int idx; if ((idx = type.indexOf(';')) < 0 || (idx + 1) == type.length()) { return false; } Map<String, String> parameters = Arrays.asList(type.substring(idx + 1).split(",")) .stream() .filter(e -> e.split("=").length > 1) .map(e -> e.split("=")) .collect(Collectors.toMap(e -> ((String[]) e)[0].trim(), e -> ((String[]) e)[1])); return Boolean.parseBoolean(parameters.get(Marshaller.MARSHALLER_PARAMETER_STRICT)); }
Source:
public static void handleNotificationOpen(Context inContext, JSONArray data, boolean fromAlert, String notificationId) { if (shouldLogUserPrivacyConsentErrorMessageForMethodName(null)) return; notificationOpenedRESTCall(inContext, data); if (trackFirebaseAnalytics != null && getFirebaseAnalyticsEnabled()) trackFirebaseAnalytics.trackOpenedEvent(generateOsNotificationOpenResult(data, true, fromAlert)); boolean urlOpened = false; boolean defaultOpenActionDisabled = "DISABLE".equals(OSUtils.getManifestMeta(inContext, "com.onesignal.NotificationOpened.DEFAULT")); if (!defaultOpenActionDisabled) urlOpened = openURLFromNotification(inContext, data); runNotificationOpenedCallback(data, true, fromAlert); if (sessionManager != null && shouldInitDirectSessionFromNotificationOpen(inContext, fromAlert, urlOpened, defaultOpenActionDisabled)) { appEntryState = AppEntryAction.NOTIFICATION_CLICK; sessionManager.onDirectSessionFromNotificationOpen(notificationId); } }

Target:
public static void handleNotificationOpen(Context inContext, JSONArray data, boolean fromAlert, String notificationId) { if (shouldLogUserPrivacyConsentErrorMessageForMethodName(null)) return; notificationOpenedRESTCall(inContext, data); if (trackFirebaseAnalytics != null && getFirebaseAnalyticsEnabled()) trackFirebaseAnalytics.trackOpenedEvent(generateOsNotificationOpenResult(data, true, fromAlert)); boolean urlOpened = false; boolean defaultOpenActionDisabled = "DISABLE".equals(OSUtils.getManifestMeta(inContext, "com.onesignal.NotificationOpened.DEFAULT")); if (!defaultOpenActionDisabled) urlOpened = openURLFromNotification(inContext, data); runNotificationOpenedCallback(data, true, fromAlert); if (shouldInitDirectSessionFromNotificationOpen(inContext, fromAlert, urlOpened, defaultOpenActionDisabled)) { appEntryState = AppEntryAction.NOTIFICATION_CLICK; sessionManager.onDirectSessionFromNotificationOpen(notificationId); } }
Source:
public Applications list() { VM vm = getEntity(entityType, VdcQueryType.GetVmByVmId, new IdQueryParameters(vmId), vmId.toString(), true); Applications applications = new Applications(); int index = 1; if (vm.getAppList() != null) { for (String appName : vm.getAppList().split(",")) { Application app = new Application(); app.setName(appName); app.setId(buildId(index)); applications.getApplications().add(addLinks(app)); index++; } } return applications; }

Target:
public Applications list() { VM vm = getEntity(entityType, VdcQueryType.GetVmByVmId, new IdQueryParameters(vmId), vmId.toString(), true); Applications applications = new Applications(); int index = 1; if (vm.getAppList() != null) { for (String appName : vm.getAppList().split(",")) { applications.getApplications().add(addLinks(map(appName))); } } return applications; }
Source:
public void sleep(IInteger seconds) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(seconds.longValue())); } catch (InterruptedException e) { } }

Target:
public void sleep(IInteger seconds) { try { TimeUnit.SECONDS.sleep(seconds.longValue()); } catch (InterruptedException e) { } }
Source:
public void TestTimeStampBefore1970() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); TimestampUtils tsu = ((BaseConnection) con).getTimestampUtils(); Date date = tsu.convertToDate(Timestamp.valueOf("1969-01-10 12:00:00").getTime(), TimeZone.getDefault()); assertEquals(new GregorianCalendar(1969, Calendar.JANUARY, 10).getTime(), date ); }

Target:
public void TestTimeStampBefore1970() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); TimestampUtils tsu = ((BaseConnection) con).getTimestampUtils(); Date date = tsu.convertToDate(Timestamp.valueOf("1969-01-10 12:00:00").getTime(), TimeZone.getDefault()); assertEquals(new GregorianCalendar(1969, Calendar.JANUARY, 10).getTime().getTime(), date.getTime() ); }
Source:
public String getUpsertQuery(final String table, Collection<String> keyCols, Collection<String> cols) { StringBuilder builder = new StringBuilder("UPSERT "); builder.append(escaped(table)); builder.append("("); joinToBuilder(builder, ",", keyCols, cols, escaper()); builder.append(") VALUES("); nCopiesToBuilder(builder, ",", "?", keyCols.size() + cols.size()); builder.append(")"); builder.append(" WITH PRIMARY KEY"); log.trace("Upsert Query: " + builder.toString()); return builder.toString(); }

Target:
public String getUpsertQuery(final String table, Collection<String> keyCols, Collection<String> cols) { StringBuilder builder = new StringBuilder("UPSERT "); builder.append(escaped(table)); builder.append("("); joinToBuilder(builder, ",", keyCols, cols, escaper()); builder.append(") VALUES("); nCopiesToBuilder(builder, ",", "?", keyCols.size() + cols.size()); builder.append(")"); builder.append(" WITH PRIMARY KEY"); return builder.toString(); }
Source:
Mono<DigitalTwinsResponse<Void>> updateDigitalTwinWithResponse(String digitalTwinId, List<Object> digitalTwinUpdateOperations, UpdateDigitalTwinRequestOptions options, Context context) { return protocolLayer .getDigitalTwins() .updateWithResponseAsync(digitalTwinId, digitalTwinUpdateOperations, options.getIfMatch(), context) .map(response -> { DigitalTwinsResponseHeaders twinHeaders = mapper.convertValue(response.getDeserializedHeaders(), DigitalTwinsResponseHeaders.class); return new DigitalTwinsResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), response.getValue(), twinHeaders); }); }

Target:
Mono<DigitalTwinsResponse<Void>> updateDigitalTwinWithResponse(String digitalTwinId, List<Object> digitalTwinUpdateOperations, UpdateDigitalTwinRequestOptions options, Context context) { String ifMatch = options != null ? options.getIfMatch() : null; return protocolLayer .getDigitalTwins() .updateWithResponseAsync(digitalTwinId, digitalTwinUpdateOperations, ifMatch, context) .map(response -> { DigitalTwinsResponseHeaders twinHeaders = mapper.convertValue(response.getDeserializedHeaders(), DigitalTwinsResponseHeaders.class); return new DigitalTwinsResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), response.getValue(), twinHeaders); }); }
Source:
public void testQueryTaskByVariablesWithByProcessVar() { Map<String, Object> variables = emptyMap(); Map<String, Object> attributes = emptyMap(); Map<String, Object> processVariables = Collections.singletonMap("var_a", "a1"); List<String> potOwners = Collections.emptyList(); List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(attributes, variables, processVariables, potOwners, new QueryContext(0, 2)); Assert.assertEquals(2, data.size()); }

Target:
public void testQueryTaskByVariablesWithByProcessVar() { List<QueryParam> processVariables = list(equalsTo("var_a", "a1")); List<String> potOwners = Collections.emptyList(); List<UserTaskInstanceWithPotOwnerDesc> data = advanceVariableDataService.queryUserTasksByVariables(emptyList(), emptyList(), processVariables, potOwners, queryContext); if (queryContext.getCount() > 0) { Assert.assertThat(data.size(), is(queryContext.getCount())); } else { Assert.assertThat(data.size(), is(3)); } }
Source:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { setUpMapImagePins(); FeatureCollection featureCollection = FeatureCollection.fromJson(loadGeoJsonFromAsset("weather_data_per_state_before2006.geojson")); for (Feature feature : featureCollection.features()) { String stateName = feature.getStringProperty("state"); String lat = feature.getStringProperty("latitude"); String lon = feature.getStringProperty("longitude"); LatLng latLng = new LatLng( Double.parseDouble(lat), Double.parseDouble(lon)); State state = null; for (State curState : states) { if (curState.name.equals(stateName)) { state = curState; break; } } if (state == null) { state = new State(stateName, latLng); states.add(state); } else { state.add(latLng); } } GeoJsonSource geoJsonSource = new GeoJsonSource(GEOJSON_SRC_ID, featureCollection); mapboxMap.getStyle().addSource(geoJsonSource); initTemperatureLayers(); populateMenu(); int indexOfState = indexOfState("Connecticut"); selectState(states.get(indexOfState).name, indexOfState); unitsFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mapboxMap != null) { changeTemperatureUnits(!isImperial); } } }); } }); }

Target:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull final Style style) { setUpMapImagePins(style); new LoadGeoJson(ExpressionIntegrationActivity.this).execute(); } }); }
Source:
public static void main(String[] args) throws IOException { extractKSTS(); String servicesJson = System.getenv("VCAP_SERVICES"); if (servicesJson == null || servicesJson.isEmpty()) { System.err.println("No service found!!!"); return; } BasicJsonParser parser = new BasicJsonParser(); Map<String, Object> json = parser.parseMap(servicesJson); List hazelcast = (List) json.get("hazelcast"); Map map = (Map) hazelcast.get(0); Map credentials = (Map) map.get("credentials"); List<String> members = (List<String>) credentials.get("members"); clientConfig = new ClientConfig(); ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig(); for (String member : members) { networkConfig.addAddress(member.replace('"', ' ').trim()); } SpringApplication.run(Application.class, args); }

Target:
public static void main(String[] args) throws IOException { extractKSTS(); String servicesJson = System.getenv("VCAP_SERVICES"); if (servicesJson == null || servicesJson.isEmpty()) { System.err.println("No service found!!!"); return; } BasicJsonParser parser = new BasicJsonParser(); Map<String, Object> json = parser.parseMap(servicesJson); List hazelcast = (List) json.get("hazelcast"); Map map = (Map) hazelcast.get(0); Map credentials = (Map) map.get("credentials"); String clusterName = (String) credentials.get("cluster_name"); List<String> members = (List<String>) credentials.get("members"); clientConfig = new ClientConfig(); clientConfig.setClusterName(clusterName); ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig(); for (String member : members) { networkConfig.addAddress(member.replace('"', ' ').trim()); } SpringApplication.run(Application.class, args); }
Source:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { ConceptProposal conceptProposal = new ConceptProposal(); conceptProposal.setOriginalText("OriginalText"); List<ConceptProposal> existingConceptProposals = conceptService.getConceptProposals("OriginalText"); assertTrue(existingConceptProposals == null || existingConceptProposals.isEmpty()); ConceptProposal savedConceptProposal = conceptService.saveConceptProposal(conceptProposal); assertEquals(conceptProposal, savedConceptProposal); }

Target:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { final String ORIGINAL_TEXT = "OriginalText"; ConceptProposal conceptProposal = new ConceptProposal(); conceptProposal.setOriginalText(ORIGINAL_TEXT); List<ConceptProposal> existingConceptProposals = conceptService.getConceptProposals(ORIGINAL_TEXT); assertTrue(existingConceptProposals.isEmpty()); ConceptProposal savedConceptProposal = conceptService.saveConceptProposal(conceptProposal); assertEquals(ORIGINAL_TEXT, savedConceptProposal.getOriginalText()); assertEquals(conceptProposal, savedConceptProposal); }
Source:
private boolean ensureEitherCssOrGss(List<URL> resources, TreeLogger logger) throws UnableToCompleteException { boolean css = resources.get(0).toString().endsWith(".css"); for (URL stylesheet : resources) { if (css) { if (!stylesheet.toString().endsWith(".css")) { logger.log(Type.ERROR, "Only either css files or gss files are supported on one interface"); throw new UnableToCompleteException(); } } else { if (!stylesheet.toString().endsWith(".gss")) { logger.log(Type.ERROR, "Only either css files or gss files are supported on one interface"); throw new UnableToCompleteException(); } } } return css; }

Target:
private boolean ensureEitherCssOrGss(List<URL> resources, TreeLogger logger) throws UnableToCompleteException { boolean css = resources.get(0).toString().endsWith(".css"); for (URL stylesheet : resources) { if (css && !stylesheet.toString().endsWith(".css")) { logger.log(Type.ERROR, "Only either css files or gss files are supported on one interface"); throw new UnableToCompleteException(); } else if (!css && !stylesheet.toString().endsWith(".gss")) { logger.log(Type.ERROR, "Only either css files or gss files are supported on one interface"); throw new UnableToCompleteException(); } } return css; }
Source:
public void selectAll() throws CandybeanException { String tag = we.getTagName(); if (tag.equals("input")) { executeJavascript("arguments[0].select()"); } else throw new CandybeanException("Cannot select text of a non-" + "text element. Actual element was of tag: "+ tag); }

Target:
public void selectAll() throws CandybeanException { String tag = we.getTagName(); if (!"input".equals(tag)) { throw new CandybeanException("Cannot select text of a non-" + "INPUT element. Actual element was of tag: " + tag); } executeJavascript("arguments[0].select()"); }
Source:
public Collection<Pair<BlockState, TRSRTransformation>> getBlocks(ItemStack stack, float growth) { Set<Pair<BlockState, TRSRTransformation>> ret = new HashSet(); Matrix4f stemMatrix = new Matrix4f(); stemMatrix.setIdentity(); stemMatrix.rotY(-1.571f); stemMatrix.setTranslation(new Vector3f(.75f, .0625f, 0)); if(growth < .375) { int age = Math.min(7, Math.round(7*growth/.375f)); return ImmutableList.of(Pair.of(this.stemBlock.getDefaultState().with(StemBlock.AGE, age), new TRSRTransformation(stemMatrix))); } else { float scale = ((growth-.375f)/.625f)*.3125f; Matrix4f cropMatrix = new Matrix4f(); cropMatrix.setIdentity(); cropMatrix.setTranslation(new Vector3f(0.75f-scale/2, .5625f-scale, 0.5f-scale/2)); cropMatrix.setScale(scale); return ImmutableList.of(Pair.of(this.attachedStemBlock.getDefaultState(), new TRSRTransformation(stemMatrix)), Pair.of(this.cropBlock.getDefaultState(), new TRSRTransformation(cropMatrix))); } }

Target:
public Collection<Pair<BlockState, TRSRTransformation>> getBlocks(ItemStack stack, float growth) { Set<Pair<BlockState, TRSRTransformation>> ret = new HashSet(); Matrix4f stemMatrix = new Matrix4f(); stemMatrix.setIdentity(); stemMatrix.rotY(-(float)Math.PI/2); stemMatrix.setTranslation(new Vector3f(.75f, .0625f, 0)); if(growth < .375) { int age = Math.round(7*growth/.375f); return ImmutableList.of(Pair.of(this.stemBlock.getDefaultState().with(StemBlock.AGE, age), new TRSRTransformation(stemMatrix))); } else { float scale = ((growth-.375f)/.625f)*.3125f; Matrix4f cropMatrix = new Matrix4f(); cropMatrix.setIdentity(); cropMatrix.setTranslation(new Vector3f(0.75f-scale/2, .5625f-scale, 0.5f-scale/2)); cropMatrix.setScale(scale); return ImmutableList.of(Pair.of(this.attachedStemBlock.getDefaultState(), new TRSRTransformation(stemMatrix)), Pair.of(this.cropBlock.getDefaultState(), new TRSRTransformation(cropMatrix))); } }
Source:
private BoundedContext buildDefault(SystemBoundedContext system) { BiFunction<BoundedContextBuilder, SystemGateway, DomainBoundedContext> instanceFactory = (builder, systemGateway) -> DomainBoundedContext.newInstance(builder, system, systemGateway); SystemGateway systemGateway = new DefaultSystemGateway(system); BoundedContext result = buildPartial(instanceFactory, systemGateway); return result; }

Target:
private BoundedContext buildDefault(SystemBoundedContext system) { BiFunction<BoundedContextBuilder, SystemGateway, DomainBoundedContext> instanceFactory = DomainBoundedContext::newInstance; SystemGateway systemGateway = new DefaultSystemGateway(system); BoundedContext result = buildPartial(instanceFactory, systemGateway); return result; }
Source:
private final void createTraceTypeGroup(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.makeColumnsEqualWidth = false; composite.setLayout(layout); composite.setFont(parent.getFont()); GridData buttonData = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(buttonData); Label typeLabel = new Label(composite, SWT.NONE); typeLabel.setText(Messages.ImportTraceWizard_TraceType); typeLabel.setFont(parent.getFont()); fTraceTypes = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1); fTraceTypes.setLayoutData(data); fTraceTypes.setFont(parent.getFont()); String[] availableTraceTypes = TmfTraceType.getAvailableTraceTypes(); String[] traceTypeList = new String[availableTraceTypes.length + 1]; traceTypeList[0] = TRACE_TYPE_AUTO_DETECT; for (int i = 0; i < availableTraceTypes.length; i++) { traceTypeList[i + 1] = availableTraceTypes[i]; } fTraceTypes.setItems(traceTypeList); fTraceTypes.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateWidgetEnablements(); boolean enabled = fTraceTypes.getText().equals(TRACE_TYPE_AUTO_DETECT); fImportUnrecognizedButton.setEnabled(enabled); } }); fTraceTypes.select(0); fImportUnrecognizedButton = new Button(composite, SWT.CHECK); fImportUnrecognizedButton.setSelection(true); fImportUnrecognizedButton.setText(Messages.ImportTraceWizard_ImportUnrecognized); }

Target:
private final void createTraceTypeGroup(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.makeColumnsEqualWidth = false; composite.setLayout(layout); composite.setFont(parent.getFont()); GridData buttonData = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(buttonData); Label typeLabel = new Label(composite, SWT.NONE); typeLabel.setText(Messages.ImportTraceWizard_TraceType); typeLabel.setFont(parent.getFont()); fTraceTypes = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1); fTraceTypes.setLayoutData(data); fTraceTypes.setFont(parent.getFont()); String[] availableTraceTypes = TmfTraceType.getAvailableTraceTypes(); String[] traceTypeList = new String[availableTraceTypes.length + 1]; traceTypeList[0] = TRACE_TYPE_AUTO_DETECT; System.arraycopy(availableTraceTypes,0,traceTypeList,1,availableTraceTypes.length); fTraceTypes.setItems(traceTypeList); fTraceTypes.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { updateWidgetEnablements(); boolean enabled = fTraceTypes.getText().equals(TRACE_TYPE_AUTO_DETECT); fImportUnrecognizedButton.setEnabled(enabled); } }); fTraceTypes.select(0); fImportUnrecognizedButton = new Button(composite, SWT.CHECK); fImportUnrecognizedButton.setSelection(true); fImportUnrecognizedButton.setText(Messages.ImportTraceWizard_ImportUnrecognized); }
Source:
public void createEndpointWithMinimalArnConfiguration() throws Exception { AmazonSQSClientMock mock = new AmazonSQSClientMock(); ((JndiRegistry) ((PropertyPlaceholderDelegateRegistry) context.getRegistry()).getRegistry()).bind("amazonSQSClient", mock); SqsComponent component = new SqsComponent(context); SqsEndpoint endpoint = (SqsEndpoint) component.createEndpoint("aws-sqs://arn:aws:sqs:region:account:MyQueue?amazonSQSClient=#amazonSQSClient&accessKey=xxx&secretKey=yyy&region=US_EAST_2"); assertEquals("US_EAST_2", endpoint.getConfiguration().getRegion()); assertEquals("account", endpoint.getConfiguration().getQueueOwnerAWSAccountId()); assertEquals("MyQueue", endpoint.getConfiguration().getQueueName()); assertEquals("xxx", endpoint.getConfiguration().getAccessKey()); }

Target:
public void createEndpointWithMinimalArnConfiguration() throws Exception { AmazonSQSClientMock mock = new AmazonSQSClientMock(); ((JndiRegistry) ((PropertyPlaceholderDelegateRegistry) context.getRegistry()).getRegistry()).bind("amazonSQSClient", mock); SqsComponent component = new SqsComponent(context); SqsEndpoint endpoint = (SqsEndpoint) component.createEndpoint("aws-sqs://arn:aws:sqs:us-east-1:account:MyQueue?amazonSQSClient=#amazonSQSClient&accessKey=xxx&secretKey=yyy"); assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion()); assertEquals("account", endpoint.getConfiguration().getQueueOwnerAWSAccountId()); assertEquals("MyQueue", endpoint.getConfiguration().getQueueName()); assertEquals("xxx", endpoint.getConfiguration().getAccessKey()); }
Source:
public void globalVerify() throws Exception { Thread.sleep(expiryDuration * 4); IList<Counter> results = targetInstance.getList(basename); Counter total = new Counter(); for (Counter i : results) { total.add(i); } log.info(basename + ": " + total + " from " + results.size() + " worker Threads"); final ICache<Integer, Long> cache = cacheManager.getCache(basename, Integer.class, Long.class); for(int i=0; i<keyCount; i++){ assertFalse(basename + ": cache should not contain any keys ", cache.containsKey(i) ); } assertFalse(basename + ": iterator should not have elements ", cache.iterator().hasNext()); assertEquals(basename + ": cache size not 0", 0, cache.size()); }

Target:
public void globalVerify() throws Exception { IList<Counter> results = targetInstance.getList(basename); Counter total = new Counter(); for (Counter i : results) { total.add(i); } log.info(basename + ": " + total + " from " + results.size() + " worker Threads"); final ICache<Integer, Long> cache = cacheManager.getCache(basename, Integer.class, Long.class); for(int i=0; i<keyCount; i++){ assertFalse(basename + ": cache should not contain any keys ", cache.containsKey(i) ); } assertFalse(basename + ": iterator should not have elements ", cache.iterator().hasNext()); assertEquals(basename + ": cache size not 0", 0, cache.size()); }
Source:
public void testGetNetwork() throws Exception { Network found = networkApi.getNetwork(network.id()); assertEquals(found, network); checkNetwork(found); assertEquals(found.networkIdentifier(), "192.168.253.0"); assertEquals(found.name(), "NetworkApiLiveTestNetwork"); assertEquals(found.cidr(), 24); assertEquals(found.notes(), "this is a test network from JClouds NetworkApiLiveTest."); }

Target:
public void testGetNetwork() throws Exception { Network found = networkApi.getNetwork(network.id()); assertEquals(found, network); checkNetwork(found); assertEquals(found.networkIdentifier(), "192.168.253.0"); assertEquals(found.name(), "NetworkApiLiveTestNetwork"); assertEquals(found.cidr(), 24); assertEquals(found.notes(), "this is a test network from jclouds NetworkApiLiveTest."); }
Source:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { VersionedPrepareCommand versionedPrepareCommand = (VersionedPrepareCommand) command; if (ctx.isOriginLocal()) { (versionedPrepareCommand).setVersionsSeen(ctx.getCacheTransaction().getVersionsRead()); } wrapEntriesForPrepare(ctx, command); EntryVersionsMap newVersionData= null; if (ctx.isOriginLocal() && !ctx.getCacheTransaction().isFromStateTransfer()) { newVersionData = cdl.createNewVersionsAndCheckForWriteSkews(versionGenerator, ctx, versionedPrepareCommand); } Object retval = invokeNextInterceptor(ctx, command); if (!ctx.isOriginLocal()) newVersionData = cdl.createNewVersionsAndCheckForWriteSkews(versionGenerator, ctx, versionedPrepareCommand); if (command.isOnePhaseCommit()) { ctx.getCacheTransaction().setUpdatedEntryVersions((versionedPrepareCommand).getVersionsSeen()); } if (newVersionData != null) { retval = newVersionData; } if (command.isOnePhaseCommit()) { commitContextEntries(ctx, null, null); } return retval; }

Target:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { if (ctx.isOriginLocal()) { ((VersionedPrepareCommand) command).setVersionsSeen(ctx.getCacheTransaction().getVersionsRead()); } wrapEntriesForPrepare(ctx, command); EntryVersionsMap newVersionData= null; if (ctx.isOriginLocal() && !ctx.getCacheTransaction().isFromStateTransfer()) newVersionData = cdl.createNewVersionsAndCheckForWriteSkews(versionGenerator, ctx, (VersionedPrepareCommand) command); Object retval = invokeNextInterceptor(ctx, command); if (!ctx.isOriginLocal()) newVersionData = cdl.createNewVersionsAndCheckForWriteSkews(versionGenerator, ctx, (VersionedPrepareCommand) command); if (command.isOnePhaseCommit()) ctx.getCacheTransaction().setUpdatedEntryVersions(((VersionedPrepareCommand) command).getVersionsSeen()); if (newVersionData != null) retval = newVersionData; if (command.isOnePhaseCommit()) commitContextEntries(ctx, null, null); return retval; }
Source:
protected PreparedStatement deleteSnapshots(Connection connection, String aggregateIdentifier, long sequenceNumber) throws SQLException { final String sql = schema.deleteSnapshotsSqlStatement(); PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, aggregateIdentifier); preparedStatement.setLong(2, sequenceNumber); return preparedStatement; }

Target:
protected PreparedStatement deleteSnapshots(Connection connection, String aggregateIdentifier, long sequenceNumber) throws SQLException { return deleteSnapshots.build(connection, schema, aggregateIdentifier, sequenceNumber); }
Source:
public ProcessInstance createProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) { if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) { return commandExecutor.execute(new CreateProcessInstanceCmd(processInstanceBuilder)); } else { throw new ActivitiIllegalArgumentException("No processDefinitionId, processDefinitionKey nor messageName provided"); } }

Target:
public ProcessInstance createProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) { if (processInstanceBuilder.hasProcessDefinitionIdOrKey()) { return commandExecutor.execute(new CreateProcessInstanceCmd(processInstanceBuilder)); } else { throw new ActivitiIllegalArgumentException("No processDefinitionId, processDefinitionKey nor messageName provided"); } }
Source:
public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { ImagingService service = Framework.getService(ImagingService.class); List<Blob> sources = blobHolder.getBlobs(); List<Blob> results = new ArrayList<Blob>(sources.size()); for (Blob source : sources) { if (source != null) { Blob result = service.convertToPDF(source); if (result != null) { results.add(result); } } } return new SimpleCachableBlobHolder(results); }

Target:
public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { ImagingService service = Framework.getService(ImagingService.class); List<Blob> sources = blobHolder.getBlobs(); List<Blob> results = new ArrayList<>(sources.size()); sources.stream().filter(source -> source != null).forEach(source -> { Blob result = service.convertToPDF(source); if (result != null) { results.add(result); } }); return new SimpleCachableBlobHolder(results); }
Source:
public ReactiveJwtDecoder createDecoder(ClientRegistration clientRegistration) { return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), key -> { if (!StringUtils.hasText(clientRegistration.getProviderDetails().getJwkSetUri())) { OAuth2Error oauth2Error = new OAuth2Error( MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the JwkSet URI.", null ); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } NimbusReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder( clientRegistration.getProviderDetails().getJwkSetUri()); OAuth2TokenValidator<Jwt> jwtValidator = new DelegatingOAuth2TokenValidator<>(jwtValidatorFactory.apply(clientRegistration)); jwtDecoder.setJwtValidator(jwtValidator); return jwtDecoder; }); }

Target:
public ReactiveJwtDecoder createDecoder(ClientRegistration clientRegistration) { Assert.notNull(clientRegistration, "clientRegistration cannot be null."); return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), key -> { if (!StringUtils.hasText(clientRegistration.getProviderDetails().getJwkSetUri())) { OAuth2Error oauth2Error = new OAuth2Error( MISSING_SIGNATURE_VERIFIER_ERROR_CODE, "Failed to find a Signature Verifier for Client Registration: '" + clientRegistration.getRegistrationId() + "'. Check to ensure you have configured the JwkSet URI.", null ); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } NimbusReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder( clientRegistration.getProviderDetails().getJwkSetUri()); OAuth2TokenValidator<Jwt> jwtValidator = jwtValidatorFactory.apply(clientRegistration); jwtDecoder.setJwtValidator(jwtValidator); return jwtDecoder; }); }
Source:
private Optional<KafkaDatastreamStatesResponse> getDatastreamStatesResponse(String streamName) { List<KafkaDatastreamStatesResponse> responses; synchronized (_runningTasks) { responses = _runningTasks.values() .stream() .filter(connectorTaskEntry -> connectorTaskEntry.getConnectorTask().hasDatastream(streamName)) .map(connectorTaskEntry -> connectorTaskEntry.getConnectorTask().getKafkaDatastreamStatesResponse()) .collect(Collectors.toList()); } if (responses.size() > 0) { Map<TopicPartition, PausedSourcePartitionMetadata> autoPausedPartitions = new HashMap<>(); Map<String, Set<String>> manualPausedPartitions = new HashMap<>(); Set<TopicPartition> assignedTopicPartitions = new HashSet<>(); responses.forEach(t -> { autoPausedPartitions.putAll(t.getAutoPausedPartitions()); manualPausedPartitions.putAll(t.getManualPausedPartitions()); assignedTopicPartitions.addAll(t.getAssignedTopicPartitions()); }); return Optional.of(new KafkaDatastreamStatesResponse(responses.get(0).getDatastream(), autoPausedPartitions, manualPausedPartitions, assignedTopicPartitions)); } return Optional.empty(); }

Target:
private Optional<KafkaDatastreamStatesResponse> getDatastreamStatesResponse(String streamName) { List<KafkaDatastreamStatesResponse> responses; synchronized (_runningTasks) { responses = _runningTasks.values() .stream() .map(ConnectorTaskEntry::getConnectorTask) .filter(task -> task.hasDatastream(streamName)) .map(AbstractKafkaBasedConnectorTask::getKafkaDatastreamStatesResponse) .collect(Collectors.toList()); } if (responses.size() > 0) { Map<TopicPartition, PausedSourcePartitionMetadata> autoPausedPartitions = new HashMap<>(); Map<String, Set<String>> manualPausedPartitions = new HashMap<>(); Set<TopicPartition> assignedTopicPartitions = new HashSet<>(); responses.forEach(t -> { autoPausedPartitions.putAll(t.getAutoPausedPartitions()); manualPausedPartitions.putAll(t.getManualPausedPartitions()); assignedTopicPartitions.addAll(t.getAssignedTopicPartitions()); }); return Optional.of(new KafkaDatastreamStatesResponse(responses.get(0).getDatastream(), autoPausedPartitions, manualPausedPartitions, assignedTopicPartitions)); } return Optional.empty(); }
Source:
private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; for (int i = 0; i < 2; i++) { if (lock.getSemaphoreLocks() != null) { for (Entry<String, Guid> entry : lock.getSemaphoreLocks().entrySet()) { if (!insertSemaphoreLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of semaphore lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of exclusive lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debug("Successed to acquire a lock"); return true; }

Target:
private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; for (int i = 0; i < 2; i++) { if (lock.getSharedLocks() != null) { for (Entry<String, Guid> entry : lock.getSharedLocks().entrySet()) { if (!insertSharedLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of shared lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of exclusive lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debug("Successed to acquire a lock"); return true; }
Source:
private Reader getPemReader() throws IOException { String privateKey = tokenClientConfiguration.getPrivateKey(); if (privateKey.startsWith("-----BEGIN PRIVATE KEY-----") && privateKey.contains("-----END PRIVATE KEY-----")) { return new StringReader(tokenClientConfiguration.getPrivateKey()); } else { Path privateKeyPemFilePath = Paths.get(tokenClientConfiguration.getPrivateKey()); return Files.newBufferedReader(privateKeyPemFilePath, Charset.defaultCharset()); } }

Target:
private Reader getPemReader() throws IOException { String privateKey = tokenClientConfiguration.getPrivateKey(); if (ConfigUtil.hasPrivateKeyContentWrapper(privateKey)) { return new StringReader(privateKey); } else { return Files.newBufferedReader(Paths.get(privateKey), Charset.defaultCharset()); } }
Source:
private void runBuild(BuildSettings buildSettings) { URLService urlService = new URLService(); StreamConsumer buildConsole; if (new SystemEnvironment().isConsoleLogsThroughWebsocketEnabled()) { buildConsole = new ConsoleOutputWebsocketTransmitter(webSocketSessionHandler, buildSettings.getBuildId()); } else { buildConsole = new ConsoleOutputTransmitter( new RemoteConsoleAppender( urlService.prefixPartialUrl(buildSettings.getConsoleUrl()), httpService) ); } ArtifactsRepository artifactsRepository = new UrlBasedArtifactsRepository( httpService, urlService.prefixPartialUrl(buildSettings.getArtifactUploadBaseUrl()), urlService.prefixPartialUrl(buildSettings.getPropertyBaseUrl()), new ZipUtil()); DefaultBuildStateReporter buildStateReporter = new DefaultBuildStateReporter(webSocketSessionHandler, getAgentRuntimeInfo()); TimeProvider clock = new TimeProvider(); BuildVariables buildVariables = new BuildVariables(getAgentRuntimeInfo(), clock); BuildSession build = new BuildSession( buildSettings.getBuildId(), buildStateReporter, buildConsole, buildVariables, artifactsRepository, httpService, clock, new File(".")); this.buildSession.set(build); build.setEnv("GO_SERVER_URL", getSystemEnvironment().getServiceUrl()); getAgentRuntimeInfo().idle(); try { getAgentRuntimeInfo().busy(new AgentBuildingInfo(buildSettings.getBuildLocatorForDisplay(), buildSettings.getBuildLocator())); build.build(buildSettings.getBuildCommand()); } finally { try { buildConsole.stop(); } finally { getAgentRuntimeInfo().idle(); } } this.buildSession.set(null); }

Target:
private void runBuild(BuildSettings buildSettings) { URLService urlService = new URLService(); StreamConsumer buildConsole; if (getSystemEnvironment().isConsoleLogsThroughWebsocketEnabled()) { buildConsole = new ConsoleOutputWebsocketTransmitter(webSocketSessionHandler, buildSettings.getBuildId()); } else { buildConsole = new ConsoleOutputTransmitter( new RemoteConsoleAppender( urlService.prefixPartialUrl(buildSettings.getConsoleUrl()), httpService) ); } ArtifactsRepository artifactsRepository = new UrlBasedArtifactsRepository( httpService, urlService.prefixPartialUrl(buildSettings.getArtifactUploadBaseUrl()), urlService.prefixPartialUrl(buildSettings.getPropertyBaseUrl()), new ZipUtil()); DefaultBuildStateReporter buildStateReporter = new DefaultBuildStateReporter(webSocketSessionHandler, getAgentRuntimeInfo()); TimeProvider clock = new TimeProvider(); BuildVariables buildVariables = new BuildVariables(getAgentRuntimeInfo(), clock); BuildSession build = new BuildSession( buildSettings.getBuildId(), buildStateReporter, buildConsole, buildVariables, artifactsRepository, httpService, clock, new File(".")); this.buildSession.set(build); build.setEnv("GO_SERVER_URL", getSystemEnvironment().getServiceUrl()); getAgentRuntimeInfo().idle(); try { getAgentRuntimeInfo().busy(new AgentBuildingInfo(buildSettings.getBuildLocatorForDisplay(), buildSettings.getBuildLocator())); build.build(buildSettings.getBuildCommand()); } finally { try { buildConsole.stop(); } finally { getAgentRuntimeInfo().idle(); } } this.buildSession.set(null); }
Source:
public void listNetworkPartitions() throws CommandException { try { Type listType = new TypeToken<ArrayList<NetworkPartitionBean>>() { }.getType(); List<NetworkPartitionBean> networkPartitionsList = (List<NetworkPartitionBean>) restClient.listEntity(ENDPOINT_LIST_NETWORK_PARTITIONS, listType, "network-partitions"); if ((networkPartitionsList == null) || (networkPartitionsList.size() == 0)) { System.out.println("No network partitions found"); return; } RowMapper<NetworkPartitionBean> networkPartitionMapper = new RowMapper<NetworkPartitionBean>() { public String[] getData(NetworkPartitionBean partition) { String[] data = new String[3]; data[0] = partition.getId(); data[1] = (partition.getKubernetesClusterId() != null) ? partition.getKubernetesClusterId() : ""; data[2] = String.valueOf(partition.getPartitions().size());; return data; } }; NetworkPartitionBean[] partitions = new NetworkPartitionBean[networkPartitionsList.size()]; partitions = networkPartitionsList.toArray(partitions); System.out.println("Network partitions found:"); CliUtils.printTable(partitions, networkPartitionMapper, "PartitionId", "Kubernetes Cluster Id", "Partitions"); } catch (Exception e) { String message = "Error in listing network partitions" + e; printError(message, e); } }

Target:
public void listNetworkPartitions() throws CommandException { try { Type listType = new TypeToken<ArrayList<NetworkPartitionBean>>() { }.getType(); List<NetworkPartitionBean> networkPartitionsList = (List<NetworkPartitionBean>) restClient.listEntity(ENDPOINT_LIST_NETWORK_PARTITIONS, listType, "network-partitions"); if ((networkPartitionsList == null) || (networkPartitionsList.size() == 0)) { System.out.println("No network partitions found"); return; } RowMapper<NetworkPartitionBean> networkPartitionMapper = new RowMapper<NetworkPartitionBean>() { public String[] getData(NetworkPartitionBean partition) { String[] data = new String[3]; data[0] = partition.getId(); data[1] = (partition.getKubernetesClusterId() != null) ? partition.getKubernetesClusterId() : ""; data[2] = String.valueOf(partition.getPartitions().size());; return data; } }; NetworkPartitionBean[] partitions = new NetworkPartitionBean[networkPartitionsList.size()]; partitions = networkPartitionsList.toArray(partitions); System.out.println("Network partitions found:"); CliUtils.printTable(partitions, networkPartitionMapper, "PartitionId", "Kubernetes Cluster Id", "Partitions"); } catch (Exception e) { String message = "Error in listing network partitions"; printError(message, e); } }