auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void pathComparatorOrderTest() { <START> String separator = FileSystems.getDefault().getSeparator(); <END> List<Path> pathsUnderTests = Arrays.asList( Paths.get(separator, "C","E","A.txt"), Paths.get(separator, "C","B","F","A.txt"), Paths.get(separator, "A","A","A.txt"), Paths.get(separator, "A","A","C.txt"), Paths.get(separator, "A","B","B.txt"), Paths.get(separator, "AB","C","A.txt"), Paths.get(separator, "Z","A.txt"), Paths.get(separator, "Z","B.txt"), Paths.get(separator, "A","A.txt"), Paths.get(separator, "A","B.txt"), Paths.get(separator), Paths.get(separator, "B.txt"), Paths.get(separator, "A.txt") ); Collections.sort(pathsUnderTests, new ExternalModuleSpecService.PathComparator()); List<Path> pathsExpectedOrder = Arrays.asList( Paths.get(separator), Paths.get(separator,"A.txt"), Paths.get(separator,"B.txt"), Paths.get(separator,"A","A.txt"), Paths.get(separator,"A","B.txt"), Paths.get(separator,"A","A","A.txt"), Paths.get(separator,"A","A","C.txt"), Paths.get(separator,"A","B","B.txt"), Paths.get(separator,"AB","C","A.txt"), Paths.get(separator,"C","B","F","A.txt"), Paths.get(separator,"C","E","A.txt"), Paths.get(separator,"Z","A.txt"), Paths.get(separator,"Z","B.txt") ); assertArrayEquals("Unexpected order found", pathsUnderTests.toArray(), pathsExpectedOrder.toArray()); }</code><technical_language>For this work Windows this var is need some valid initial part of a Windows path, separator</technical_language>

Target:
public void pathComparatorOrderTest() { Path root = Paths.get("").toAbsolutePath().getRoot(); List<Path> pathsUnderTests = Arrays.asList( root.resolve(Paths.get("C","E","A.txt")), root.resolve(Paths.get("C","B","F","A.txt")), root.resolve(Paths.get("A","A","A.txt")), root.resolve(Paths.get("A","A","C.txt")), root.resolve(Paths.get("A","B","B.txt")), root.resolve(Paths.get("AB","C","A.txt")), root.resolve(Paths.get("Z","A.txt")), root.resolve(Paths.get("Z","B.txt")), root.resolve(Paths.get("A","A.txt")), root.resolve(Paths.get("A","B.txt")), root, root.resolve(Paths.get("B.txt")), root.resolve(Paths.get("A.txt")) ); Collections.sort(pathsUnderTests, new ExternalModuleSpecService.PathComparator()); List<Path> pathsExpectedOrder = Arrays.asList( root, root.resolve(Paths.get("A.txt")), root.resolve(Paths.get("B.txt")), root.resolve(Paths.get("A","A.txt")), root.resolve(Paths.get("A","B.txt")), root.resolve(Paths.get("A","A","A.txt")), root.resolve(Paths.get("A","A","C.txt")), root.resolve(Paths.get("A","B","B.txt")), root.resolve(Paths.get("AB","C","A.txt")), root.resolve(Paths.get("C","B","F","A.txt")), root.resolve(Paths.get("C","E","A.txt")), root.resolve(Paths.get("Z","A.txt")), root.resolve(Paths.get("Z","B.txt")) ); assertArrayEquals("Unexpected order found", pathsUnderTests.toArray(), pathsExpectedOrder.toArray()); }
Source:
<code>public List<MemberInfo> apply(final GroupResource resource) throws AuthException, BadRequestException, ResourceConflictException, Exception { final List<MemberInfo> members = <START> Lists.newLinkedList(getMembers(resource.getGroupUUID(), recursive, <END> new HashSet<AccountGroup.UUID>()).values()); Collections.sort(members, new Comparator<MemberInfo>() { @Override public int compare(MemberInfo a, MemberInfo b) { int cmp = nullToEmpty(a.fullName).compareTo(nullToEmpty(b.fullName)); if (cmp != 0) { return cmp; } cmp = nullToEmpty(a.preferredEmail).compareTo( nullToEmpty(b.preferredEmail)); if (cmp != 0) { return cmp; } return nullToEmpty(a.id).compareTo(nullToEmpty(b.id)); } }); return members; }</code><technical_language>Sorting a linked list is bad. JRE suck allocating a temporary array equal in size linked list, copying list array, sorting array, copying linked list nodes. thought "saved" avoiding array allocation for ArrayList lost sorting list. ArrayList</technical_language>

Target:
public List<MemberInfo> apply(final GroupResource resource) throws AuthException, BadRequestException, ResourceConflictException, Exception { final Map<Account.Id, MemberInfo> members = getMembers(resource.getGroupUUID(), new HashSet<AccountGroup.UUID>()); final List<MemberInfo> memberInfos = Lists.newArrayList(members.values()); Collections.sort(memberInfos, new Comparator<MemberInfo>() { @Override public int compare(MemberInfo a, MemberInfo b) { return ComparisonChain .start() .compare(a.fullName, b.fullName, Ordering.natural().nullsFirst()) .compare(a.preferredEmail, b.preferredEmail, Ordering.natural().nullsFirst()) .compare(a.id, b.id, Ordering.natural().nullsFirst()).result(); } }); return memberInfos; }
Source:
<code>public void setCheckedElements(Object[] elements) { Object[] oldCheckedElements = getCheckedElements(); super.setCheckedElements(elements); Control tree = getControl(); try { tree.setRedraw(false); if (oldCheckedElements.length > 0) { HashSet<Object> changedElements = new HashSet<>(Arrays.asList(elements)); <START> changedElements.removeAll(Arrays.asList(oldCheckedElements)); <END> doCheckStateChanged(changedElements.toArray()); } else { doCheckStateChanged(elements); } } finally { tree.setRedraw(true); } }</code><technical_language>This operate List#contains, depending collection is larger (-> AbstractSet#contains). safe, removeAll replaced oldCheckedElements.forEach(changedElements::remove)</technical_language>

Target:
public void setCheckedElements(Object[] elements) { Object[] oldCheckedElements = getCheckedElements(); super.setCheckedElements(elements); Control tree = getControl(); try { tree.setRedraw(false); if (oldCheckedElements.length > 0) { HashSet<Object> changedElements = new HashSet<>(Arrays.asList(elements)); for (Object element : oldCheckedElements) { changedElements.remove(element); } doCheckStateChanged(changedElements.toArray()); } else { doCheckStateChanged(elements); } } finally { tree.setRedraw(true); } }
Source:
<code>static String getTopStrandNormalizedUmi(final SAMRecord record, final String umiTag, final boolean duplexUmi) { <START> if (umiTag == null) return null; <END> final String umi = record.getStringAttribute(umiTag); if (umi == null) return null; if (duplexUmi) { final String[] split = umi.split(DUPLEX_UMI_DELIMITER); if (split.length != 2) { throw new PicardException("Duplex UMIs must be of the form X-Y where X and Y are equal length UMIs, for example AT-GA. Found UMI, " + umi); } if (isTopStrand(record)) { return split[0] + DUPLEX_UMI_DELIMITER + split[1]; } else { return split[1] + DUPLEX_UMI_DELIMITER + split[0]; } } else { return umi; } }</code><technical_language>I clearer wrap if body lines { } e.g. suggestion if (umiTag == null) { return null; }</technical_language>

Target:
static String getTopStrandNormalizedUmi(final SAMRecord record, final String umiTag, final boolean duplexUmi) { if (umiTag == null) { return null; } final String umi = record.getStringAttribute(umiTag); if (umi == null) { return null; } if (!ALLOWED_UMI.matcher(umi).matches()) { throw new PicardException("UMI found with illegal characters. UMIs must match the regular expression ^[ATCGNatcgn-]*$."); } if (!duplexUmi) { return umi; } final String[] split = umi.split(DUPLEX_UMI_DELIMITER); if (split.length != 2) { throw new PicardException("Duplex UMIs must be of the form X-Y where X and Y are equal length UMIs, for example AT-GA. Found UMI, " + umi); } if (isTopStrand(record)) { return split[0] + DUPLEX_UMI_DELIMITER + split[1]; } else { return split[1] + DUPLEX_UMI_DELIMITER + split[0]; } }
Source:
<code>public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = new ClusterParticipant() { @Override public void initialize(String hostname, int port, List<AmbryHealthReport> ambryHealthReports) { } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { <START> return true; <END> } }; } return clusterParticipant; }</code><technical_language>state set in MockReplicaId here? helix version, this needs check if ReplicaId is instance of MockReplicaId, cast set I</technical_language>

Target:
public ClusterParticipant getClusterParticipant() throws IOException { if (clusterParticipant == null) { clusterParticipant = new ClusterParticipant() { @Override public void initialize(String hostname, int port, List<AmbryHealthReport> ambryHealthReports) { } @Override public void close() { } @Override public boolean setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof MockReplicaId)) { throw new IllegalArgumentException("Not MockReplicaId"); } MockReplicaId mockReplicaId = (MockReplicaId) replicaId; mockReplicaId.setSealedState(isSealed); return true; } }; } return clusterParticipant; }
Source:
<code><START> public ListenableFuture<Void> writeMutationsAsyncFuture(Collection<Mutation> ml) { <END> if (ml.size() == 0) { return Futures.immediateFuture(null); } ListenableFutureTask<Void> lf = ListenableFutureTask.create(DO_NOTHING, null); try { MutationBatch mb = new MutationBatch(ml, lf); mutQueue.put(mb); return lf; } catch (Exception e) { throw new RuntimeException(e); } }</code><technical_language>methods in this class do need public package local</technical_language>

Target:
ListenableFuture<Void> writeMutationsAsyncFuture(Collection<Mutation> ml) { if (ml.size() == 0) { return Futures.immediateFuture(null); } ListenableFutureTask<Void> lf = ListenableFutureTask.create(DO_NOTHING, null); try { MutationBatch mb = new MutationBatch(ml, lf); mutQueue.put(mb); return lf; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>public void testSilence() { final byte[] bytes = new byte[] { 0x00, 0x00, 0x00, 0x00 }; <START> assertTrue(testee.detect(bytes, 0, bytes.length)); <END> }</code><technical_language>testing for silence, detect method returns true? return false</technical_language>

Target:
public void testSilence() { final URL inputFileUrl = this.getClass().getResource("/test_sound_mono_48_silence.pcm"); final int packetSize = 480; final SpeechDetector detector = new NoiseThresholdDetector(10); boolean detected = false; try (FileInputStream inputStream = new FileInputStream(inputFileUrl.getFile())) { byte[] input = new byte[2 * packetSize]; while (inputStream.read(input) == 2 * packetSize) { detected = detected || detector.detect(input, 0, input.length); } } catch (IOException e) { log.error("Could not read file", e); fail("Speech Detector test file access error"); } assertFalse(detected); }
Source:
<code>default <U extends Comparable<? super U>> Option<T> minBy(Function<? super T, ? extends U> f) { Objects.requireNonNull(f, "f is null"); if (isEmpty()) { return None.instance(); } else { T tm = null; U um = null; for (T t : Iterator.ofAll(this)) { U u = f.apply(t); if (um == null || u.compareTo(um) <= 0) { um = u; tm = t; } } <START> return new Some<>(tm); <END> } }</code><technical_language>here... java final Iterator<T> iter = iterator(); T tm = iter.next(); U um = f.apply(tm); while (iter.hasNext()) { final T t = iter.next(); final U u = f.apply(t); if (u.compareTo(um) < 0) { um = u; tm = t; } } return new Some<>(tm);</technical_language>

Target:
default <U extends Comparable<? super U>> Option<T> minBy(Function<? super T, ? extends U> f) { Objects.requireNonNull(f, "f is null"); if (isEmpty()) { return None.instance(); } else { final Iterator<T> iter = iterator(); T tm = iter.next(); U um = f.apply(tm); while (iter.hasNext()) { final T t = iter.next(); final U u = f.apply(t); if (u.compareTo(um) < 0) { um = u; tm = t; } } return new Some<>(tm); } }
Source:
<code>public void fetchesRepoConfigAndUpdatesMemo() throws Exception { final Github ghub = new MkGithub("thindeck"); final Repo repo = ghub.repos().create( Json.createObjectBuilder() .add("name", "test") .build() ); final String config = Joiner.on('\n').join( "domains: [\"example.com\", \"test.example.com\"]", "ports: [80, 443]" ); repo.contents().create( Json.createObjectBuilder() .add("path", ".thindeck.yml") .add("message", "Thindeck config") .add( "content", new String( Base64.encodeBase64( config.getBytes() ) ) ).build() ); final Context ctx = new MkContext(); ctx.memo().update( new Directives() .xpath("/memo") .add("uri").set("git://github.com/thindeck/test.git") ); final Step step = new ReadConfig(ghub); step.exec(ctx); step.exec(ctx); MatcherAssert.assertThat( ctx.memo().read(), XhtmlMatchers.hasXPaths( " " " " ) ); <START> Assert.assertEquals( <END> 2, ctx.memo().read().nodes(" ); Assert.assertEquals( 2, ctx.memo().read().nodes(" ); }</code><technical_language>MatcherAssert Hamcrest, please follow this convention</technical_language>

Target:
public void fetchesRepoConfigAndUpdatesMemo() throws Exception { final Github ghub = new MkGithub("thindeck"); final Repo repo = ghub.repos().create( Json.createObjectBuilder() .add("name", "test") .build() ); final String config = Joiner.on('\n').join( "domains: [\"example.com\", \"test.example.com\"]", "ports: [80, 443]" ); repo.contents().create( Json.createObjectBuilder() .add("path", ".thindeck.yml") .add("message", "Thindeck config") .add( "content", new String( Base64.encodeBase64( config.getBytes() ) ) ).build() ); final Context ctx = new MkContext(); ctx.memo().update( new Directives() .xpath("/memo") .add("uri").set("git://github.com/thindeck/test.git") ); final Step step = new ReadConfig(ghub); step.exec(ctx); step.exec(ctx); MatcherAssert.assertThat( ctx.memo().read(), XhtmlMatchers.hasXPaths( " " " " ) ); MatcherAssert.assertThat( 2, Matchers.equalTo( ctx.memo().read().nodes(" ) ); MatcherAssert.assertThat( 2, Matchers.equalTo( ctx.memo().read().nodes(" ) ); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_device); mIsCreateMode = getIntent().getBooleanExtra(EXTRA_IS_CREATE, false); registerOnServiceConnectedListener(this::onServiceConnected); setTitle(mIsCreateMode ? R.string.add_device : R.string.edit_device); mIdContainer = findViewById(R.id.idContainer); mIdView = findViewById(R.id.id); mQrButton = findViewById(R.id.qrButton); mNameView = findViewById(R.id.name); mAddressesView = findViewById(R.id.addresses); mCurrentAddressView = findViewById(R.id.currentAddress); mCompressionContainer = findViewById(R.id.compressionContainer); mCompressionValueView = findViewById(R.id.compressionValue); mIntroducerView = findViewById(R.id.introducer); <START> mDevicePaused = findViewById(R.id.devicePauseSync); <END> mSyncthingVersionView = findViewById(R.id.syncthingVersion); mQrButton.setOnClickListener(this); mCompressionContainer.setOnClickListener(this); if (savedInstanceState != null){ if (mDevice == null) { mDevice = new Gson().fromJson(savedInstanceState.getString("device"), Device.class); } restoreDialogStates(savedInstanceState); } if (mIsCreateMode) { if (mDevice == null) { initDevice(); } } else { prepareEditMode(); } }</code><technical_language>devicePause, is type of pause, adding word sync confusing</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_device); mIsCreateMode = getIntent().getBooleanExtra(EXTRA_IS_CREATE, false); registerOnServiceConnectedListener(this::onServiceConnected); setTitle(mIsCreateMode ? R.string.add_device : R.string.edit_device); mIdContainer = findViewById(R.id.idContainer); mIdView = findViewById(R.id.id); mQrButton = findViewById(R.id.qrButton); mNameView = findViewById(R.id.name); mAddressesView = findViewById(R.id.addresses); mCurrentAddressView = findViewById(R.id.currentAddress); mCompressionContainer = findViewById(R.id.compressionContainer); mCompressionValueView = findViewById(R.id.compressionValue); mIntroducerView = findViewById(R.id.introducer); mDevicePaused = findViewById(R.id.devicePause); mSyncthingVersionView = findViewById(R.id.syncthingVersion); mQrButton.setOnClickListener(this); mCompressionContainer.setOnClickListener(this); if (savedInstanceState != null){ if (mDevice == null) { mDevice = new Gson().fromJson(savedInstanceState.getString("device"), Device.class); } restoreDialogStates(savedInstanceState); } if (mIsCreateMode) { if (mDevice == null) { initDevice(); } } else { prepareEditMode(); } }
Source:
<code>public void handle(GlowSession session, UseItemMessage message) { GlowPlayer player = session.getPlayer(); ItemStack holding = player.getItemInHand(); if (!InventoryUtil.isEmpty(holding)) { ItemType type = ItemTable.instance().getItem(holding.getType()); if (type != null) { if (type.getContext() == Context.AIR || type.getContext() == Context.AIR_BLOCK) { type.rightClickAir(player, holding); } else { if (holding.getType() == Material.WATER_BUCKET || holding.getType() == Material.LAVA_BUCKET) { holding.setType(Material.BUCKET); } } } <START> if (!InventoryUtil.isEmpty(holding) && holding.getAmount() <= 0) { <END> holding = InventoryUtil.createEmptyStack(); } player.setItemInHand(holding); } }</code><technical_language>check sense, if amount is <= 0 isEmpty return true, breaking condition. [This](<LINK_0> is do it</technical_language>

Target:
public void handle(GlowSession session, UseItemMessage message) { GlowPlayer player = session.getPlayer(); ItemStack holding = player.getInventory().getItem(message.getEquipmentSlot()); if (!InventoryUtil.isEmpty(holding)) { ItemType type = ItemTable.instance().getItem(holding.getType()); if (type != null) { if (type.getContext() == Context.AIR || type.getContext() == Context.ANY) { type.rightClickAir(player, holding); } else { if (holding.getType() == Material.WATER_BUCKET || holding.getType() == Material.LAVA_BUCKET) { holding.setType(Material.BUCKET); } } } if (holding.getAmount() <= 0) { holding = InventoryUtil.createEmptyStack(); } player.getInventory().setItem(message.getEquipmentSlot(), holding); } }
Source:
<code>public void removeSubscriberFromUpdateNotifications(ILocalBlockUpdateSubscriber subscriber) { if (subscriberMap.containsKey(subscriber.getSubscriberPos())) { <START> subscriberMap.remove(subscriber.getSubscriberPos()); <END> } }</code><technical_language>Change remove call -- contains key call is unnecessary (as remove do check anyway)</technical_language>

Target:
public void removeSubscriberFromUpdateNotifications(ILocalBlockUpdateSubscriber subscriber) { subscriberSet.remove(subscriber); }
Source:
<code>public void testUnhandledExceptionClassSerialisation() throws java.lang.Exception { Report report = reportFromHandledState(HandledState.newInstance( SeverityReasonType.REASON_ERROR_CLASS, <START> Collections.singletonMap("errorClass", "TypeMismatchException"), <END> Severity.INFO, true)); JsonNode payload = getJsonPayloadFromReport(report); assertEquals("info", payload.get("severity").asText()); assertTrue(payload.get("unhandled").booleanValue()); JsonNode severityReason = payload.get("severityReason"); assertNotNull(severityReason); assertEquals(HandledState.SeverityReasonType.REASON_ERROR_CLASS .toString(), severityReason.get("type").asText()); assertEquals(1, severityReason.get("attributes").size()); assertEquals("TypeMismatchException", severityReason.get("attributes").get("errorClass").asText()); }</code><technical_language>more of a dashboard question, I thought a distinction errorClass exceptionClass in wording, case. interested hear reasoning renaming this, in mind Error in Java is is recoverable</technical_language>

Target:
public void testUnhandledExceptionClassSerialisation() throws java.lang.Exception { Report report = reportFromHandledState(HandledState.newInstance( SeverityReasonType.REASON_EXCEPTION_CLASS, Collections.singletonMap("exceptionClass", "TypeMismatchException"), Severity.INFO, true)); JsonNode payload = getJsonPayloadFromReport(report); assertEquals("info", payload.get("severity").asText()); assertTrue(payload.get("unhandled").booleanValue()); JsonNode severityReason = payload.get("severityReason"); assertNotNull(severityReason); assertEquals(HandledState.SeverityReasonType.REASON_EXCEPTION_CLASS .toString(), severityReason.get("type").asText()); assertEquals(1, severityReason.get("attributes").size()); assertEquals("TypeMismatchException", severityReason.get("attributes").get("exceptionClass").asText()); }
Source:
<code><START> public void addListenerOnStartContinueButton(){ <END> startContinue = (Button) findViewById(R.id.start_continue_button_mm); startContinue.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v){ Intent i = new Intent(v.getContext(), PuzzleActivity.class); startActivity(i); } }); }</code><technical_language>method private DONE</technical_language>

Target:
private void addListenerOnStartContinueButton() { startContinue = (Button) findViewById(R.id.start_continue_button_mm); startContinue.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Intent i = new Intent(v.getContext(), PuzzleActivity.class); startActivity(i); } }); }
Source:
<code>public boolean canAccess(Authentication user, ResourceInfo resource, AccessMode mode) { checkPropertyFile(); String workspace; try { workspace = resource.getStore().getWorkspace().getName(); } catch (Exception e) { LOGGER.log(Level.FINE, "Errors occurred trying to gather workspace of resource " + resource.getName()); return true; } <START> <END> SecureTreeNode node = root.getDeepestNode(new String[] { workspace, resource.getName() }); if(!node.canAccess(user, mode)) { return false; } if(!layerGroupContainmentCheckRequired()) { return true; } List<SecureTreeNode> nodes = getNodesContainingResource(resource); if(nodes.isEmpty()) { return true; } if(nodes.stream().anyMatch(n -> n.canAccess(user, mode))) { return true; } Filter containsResource = Predicates.equal("layers.resource.id", resource.getId(), MatchAction.ANY); Filter notSingle = Predicates.notEqual("mode", LayerGroupInfo.Mode.SINGLE); Filter global = Predicates.isNull("workspace"); Filter inSameWorkspace = Predicates.equal("workspace.name", workspace); Filter wsMatch = Predicates.or(global, inSameWorkspace); Filter groupFilter = Predicates.and(wsMatch, notSingle, containsResource); if(hasContainerGroupNotDenied(nodes, groupFilter)) { return true; } return false; }</code><technical_language>unneeded whitespace</technical_language>

Target:
public boolean canAccess(Authentication user, ResourceInfo resource, AccessMode mode) { checkPropertyFile(); String workspace; final String resourceName = resource.getName(); try { workspace = resource.getStore().getWorkspace().getName(); } catch (Exception e) { LOGGER.log(Level.FINE, "Errors occurred trying to gather workspace of resource " + resourceName); return true; } SecureTreeNode catalogNode = root.getDeepestNode(new String[] { workspace, resourceName }); int catalogNodeDepth = catalogNode.getDepth(); final boolean catalogNodeAllowsAccess = catalogNode.canAccess(user, mode); if(catalogNodeDepth == SecureTreeNode.RESOURCE_DEPTH || !layerGroupContainmentCheckRequired()) { return catalogNodeAllowsAccess; } List<SecureTreeNode> nodes = getNodesContainingResource(resource); if(nodes.isEmpty()) { return catalogNodeAllowsAccess; } if(nodes.stream().anyMatch(n -> n.canAccess(user, mode) && n.getDepth() > catalogNodeDepth)) { return true; } Filter containsResource = Predicates.equal("layers.resource.id", resource.getId(), MatchAction.ANY); Filter notSingle = Predicates.notEqual("mode", LayerGroupInfo.Mode.SINGLE); Filter global = Predicates.isNull("workspace"); Filter inSameWorkspace = Predicates.equal("workspace.name", workspace); Filter wsMatch = Predicates.or(global, inSameWorkspace); Filter groupFilter = Predicates.and(wsMatch, notSingle, containsResource); if(hasContainerGroupNotDenied(user, nodes, groupFilter, catalogNodeDepth)) { return true; } if(nodes.stream().anyMatch(n -> !n.canAccess(user, mode) && n.getDepth() > catalogNodeDepth)) { return false; } else { return catalogNodeAllowsAccess; } }
Source:
<code>public void doSave(IProgressMonitor monitor) { setContextClassLoader(); sourceDirty = false; if (getActivePage() == SOURCE_VIEW_PAGE_INDEX) { try { handleDesignViewActivatedEvent(); <START> } catch (Exception e) { <END> printHandleDesignViewActivatedEventErrorMessage(e); } finally { AbstractEsbNodeDeserializer.cleanupData(); firePropertyChange(PROP_DIRTY); } } getEditor(0).doSave(monitor); ENDPOINT)){ try { updateAssociatedXMLFile(monitor); } catch (Exception e) { sourceDirty=true; log.error("Error while saving the diagram", e); String errorMsgHeader = "Save failed. Following error(s) have been detected." + " Please see the error log for more details."; String simpleMessage = ExceptionMessageMapper.getNonTechnicalMessage(e.getMessage()); IStatus editorStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, simpleMessage); ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Error", errorMsgHeader, editorStatus); } EditorUtils.setLockmode(graphicalEditor, true); updateAssociatedDiagrams(); getEditor(0).doSave(monitor); EditorUtils.setLockmode(graphicalEditor, false); }</code><technical_language>Catching a general Exception type is a good practice. Is specific reason catch a general Exception here</technical_language>

Target:
public void doSave(IProgressMonitor monitor) { setContextClassLoader(); if(getActivePage()==SOURCE_VIEW_PAGE_INDEX){ handleDesignViewActivatedEvent(); } sourceDirty=false; getEditor(0).doSave(monitor); EsbServer esbServer = EditorUtils.getEsbServer(graphicalEditor); ENDPOINT)){ try { updateAssociatedXMLFile(monitor); } catch (Exception e) { sourceDirty=true; log.error("Error while saving the diagram", e); String errorMsgHeader = "Save failed. Following error(s) have been detected." + " Please see the error log for more details."; String simpleMessage = ExceptionMessageMapper.getNonTechnicalMessage(e.getMessage()); IStatus editorStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, simpleMessage); ErrorDialog.openError(Display.getCurrent().getActiveShell(), "Error", errorMsgHeader, editorStatus); } EditorUtils.setLockmode(graphicalEditor, true); updateAssociatedDiagrams(); getEditor(0).doSave(monitor); EditorUtils.setLockmode(graphicalEditor, false); }
Source:
<code>public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) { dest.clear(); for (int i = 0; i < timeStamps.size(); i++) { long time = timeStamps.get(i); if (timestampTest.test(time)) { <START> dest.add(new Key(key.getRow(), time), values.get(i)); <END> } } }</code><technical_language>nice avoid creating key object. class access private in dest. add stuff dest.timeStamps dest.values. Alternatively, create a private method private void add(long timestamp, v){...} call method here. I private method is a cleaner</technical_language>

Target:
public void copyTo(ColumnBuffer dest, LongPredicate timestampTest) { dest.clear(); if (key != null) { dest.key = new Key(key); } for (int i = 0; i < timeStamps.size(); i++) { long time = timeStamps.get(i); if (timestampTest.test(time)) { dest.add(time, values.get(i)); } } }
Source:
<code>public Response createGeoAlertsForGeoClusters(Alert alert, @PathParam("alertType") String alertType) { try { <START> String authorizedUser = MultitenantUtils.getTenantAwareUsername( <END> CarbonContext.getThreadLocalCarbonContext().getUsername() ); GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); geoService.createGeoAlert(alert, alertType); return Response.ok().build(); } catch (GeoLocationBasedServiceException e) { String error = "Error occurred while creating " + alertType + " alert"; log.error(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (AlertAlreadyExistException e) { String error = "A geo alert with this name already exists."; log.error(error,e); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } }</code><technical_language>do this assignment local variable 'authorizedUser'</technical_language>

Target:
public Response createGeoAlertsForGeoClusters(Alert alert, @PathParam("alertType") String alertType) { try { GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); geoService.createGeoAlert(alert, alertType); return Response.ok().build(); } catch (GeoLocationBasedServiceException e) { String error = "Error occurred while creating " + alertType + " alert"; log.error(error, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); } catch (AlertAlreadyExistException e) { String error = "A geo alert with this name already exists."; log.error(error,e); return Response.status(Response.Status.BAD_REQUEST).entity(error).build(); } }
Source:
<code>public JType apply(String nodeName, JsonNode mediaNode, JType baseType, Schema schema) { <START> if (!isBase64(mediaNode)) { <END> return baseType; } return baseType.owner().ref(byte[].class); }</code><technical_language>I applying this check. If content "binaryEncoding" represent a byte array, user configure binding library in is required support relevant binary encoding. Gson (for instance) requires a custom serializer/deserializer set - reason this custom serializer/deserializer base64. Do require this strict check for use-case</technical_language>

Target:
public JType apply(String nodeName, JsonNode mediaNode, JType baseType, Schema schema) { if (!mediaNode.has(BINARY_ENCODING)) { return baseType; } return baseType.owner().ref(byte[].class); }
Source:
<code>public List<Contributor> listAllByProjectIdAndPathInCommit( long projectId, String commitHash, String path) { if (fileRepository.fileExistsByPath(projectId, path)) { return mapper.mapNodeEntities( contributorQueryRepository.findAllByProjectIdAndFilepathInCommit( projectId, commitHash, path)); } else { <START> return mapper.mapNodeEntities( <END> contributorQueryRepository.findAllByProjectIdAndModulePathInCommit( projectId, commitHash, path)); } }</code><technical_language>Do want throw some kind of error if directory exists/is invalid return nothing</technical_language>

Target:
public List<Contributor> listAllByProjectIdAndPathInCommit( long projectId, String commitHash, String path) { if (fileRepository.fileWithPathExists(projectId, path)) { return mapper.mapNodeEntities( contributorQueryRepository.findAllByProjectIdAndFilepathInCommit( projectId, commitHash, path)); } else { return mapper.mapNodeEntities( contributorQueryRepository.findAllByProjectIdAndDirectoryInCommit( projectId, commitHash, path)); } }
Source:
<code>private Intent constructResultIntent() { ExpenseClaim claim = new ExpenseClaim( nameField.getText().toString(), descriptionField.getText().toString(), startDateField.getDate(), endDateField.getDate(), user, ExpenseClaim.Status.IN_PROGRESS ); <START> <END> OnlineManager<ExpenseClaim> onlineManager = new OnlineManager<ExpenseClaim>(this); ElasticSearchAPIClient apiClient = new ElasticSearchAPIClient(ElasticSearchConfiguration.getBaseURL()); onlineManager.enqueueCall(apiClient.add(claim)); Intent intent = new Intent(); intent.putExtra(EXTRA_EXPENSE_CLAIM, claim); return intent; }</code><technical_language>This code removed test it, actual implementation (it's in session branch) a central observer calls API client putting this changes</technical_language>

Target:
private Intent constructResultIntent() { ExpenseClaim claim = new ExpenseClaim( nameField.getText().toString(), descriptionField.getText().toString(), startDateField.getDate(), endDateField.getDate(), user, ExpenseClaim.Status.IN_PROGRESS ); Intent intent = new Intent(); intent.putExtra(EXTRA_EXPENSE_CLAIM, claim); return intent; }
Source:
<code>private Locale parseLocaleFrom(String filename, String basename) { Locale result = null; <START> String tmp_filename=filename; <END> if (filename.startsWith(basename)) { tmp_filename = filename.substring(basename.length()); } String localespec = tmp_filename.substring(0, tmp_filename.indexOf('.')); if ("".equals(localespec)) { result = Locale.ENGLISH; } else { localespec = localespec.substring(1); result = LocaleUtility.fromSpecification(localespec); } return result; }</code><technical_language>variable name match naming conventions <LINK_0> need put some space assignment operator "="</technical_language>

Target:
private Locale parseLocaleFrom(String filename, String basename) { Locale result = null; String tempFilename=filename; if (filename.startsWith(basename)) { tempFilename = filename.substring(basename.length()); } String localespec = tempFilename.substring(0, tempFilename.indexOf('.')); if ("".equals(localespec)) { result = Locale.ENGLISH; } else { localespec = localespec.substring(1); result = LocaleUtility.fromSpecification(localespec); } return result; }
Source:
<code>private static void serializePrimitive(Type type, BlockBuilder builder, Object object) { requireNonNull(builder, "builder is null"); if (object == null) { builder.appendNull(); return; } <START> <END> if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); } else if (type.equals(BIGINT)) { type.writeLong(builder, (Long) object); } else if (type.equals(DOUBLE)) { type.writeDouble(builder, (Double) object); } else if (type.equals(INTEGER)) { type.writeLong(builder, (Integer) object); } else if (type.equals(VARCHAR)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else if (type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(String.valueOf(object))); } else { throw new IllegalArgumentException("Unknown primitive type: " + type.getDisplayName()); } }</code><technical_language>if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); } else if (type.equals(BIGINT) || type.equals(INTEGER)) { type.writeLong(builder, (Long) object); } else if (type.equals(DOUBLE)) { type.writeDouble(builder, (Double) object); } else if (type.equals(VARCHAR) || type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(object.toString())); } else { throw new IllegalArgumentException("Unknown primitive type: " + type.getDisplayName()); }</technical_language>

Target:
private static Block serializePrimitive(Type type, BlockBuilder builder, Object object) { requireNonNull(builder, "builder is null"); if (object == null) { builder.appendNull(); return builder.build(); } if (type.equals(BOOLEAN)) { type.writeBoolean(builder, (Boolean) object); } else if (type.equals(BIGINT)) { type.writeLong(builder, (Long) object); } else if (type.equals(DOUBLE)) { type.writeDouble(builder, (Double) object); } else if (type.equals(INTEGER)) { type.writeLong(builder, (Integer) object); } else if (type.equals(VARCHAR) || type.equals(VARBINARY)) { type.writeSlice(builder, utf8Slice(object.toString())); } else { throw new IllegalArgumentException("Unknown primitive type: " + type.getDisplayName()); } return builder.build(); }
Source:
<code>public int getMaxExecutorCores() { if (MAX_EXECUTOR_CORES != -1) return MAX_EXECUTOR_CORES; synchronized (HEngineSqlEnv.class) { byte sparkYarnConfigBytes = getSparkYarnConfigBytes(); if (sparkYarnConfigBytes == null) return DEFAULT_MAX_EXECUTOR_CORES; SparkYarnConfiguration conf = null; try { ByteArrayInputStream bis = new ByteArrayInputStream(sparkYarnConfigBytes); ObjectInput in = new ObjectInputStream(bis); conf = (SparkYarnConfiguration) in.readObject(); } catch (Exception e) { return DEFAULT_MAX_EXECUTOR_CORES; } if (conf == null) return DEFAULT_MAX_EXECUTOR_CORES; int maxExecutorCores = <START> calculateMaxExecutorCores(conf.getYarnNodemanagerResourceMemoryMB(), <END> conf.getDynamicAllocationEnabled(), conf.getExecutorInstances(), conf.getExecutorCores(), conf.getExecutorMemory(), conf.getDynamicAllocationMaxExecutors(), conf.getExecutorMemoryOverhead(), conf.getYarnExecutorMemoryOverhead(), conf.getNumNodes()); if (conf.getNumNodes() > 0) { numSparkNodes = conf.getNumNodes(); MAX_EXECUTOR_CORES = maxExecutorCores; } else return DEFAULT_MAX_EXECUTOR_CORES; } return MAX_EXECUTOR_CORES; }</code><technical_language>this function in OlapServerMaster a class logically close OlapServer, I this class knowledge YARN. Ideally read number of executor cores Zookeeper</technical_language>

Target:
public int getMaxExecutorCores() { if (MAX_EXECUTOR_CORES != -1) return MAX_EXECUTOR_CORES; synchronized (HEngineSqlEnv.class) { byte maxExecutorCoresBytes = getMaxExecutorCoresBytes(); if (maxExecutorCoresBytes == null) return DEFAULT_MAX_EXECUTOR_CORES; int maxExecutorCores; int numNodes; try { ByteArrayInputStream bis = new ByteArrayInputStream(maxExecutorCoresBytes); ObjectInput in = new ObjectInputStream(bis); maxExecutorCores = in.readInt(); numNodes = in.readInt(); } catch (Exception e) { return DEFAULT_MAX_EXECUTOR_CORES; } if (numNodes > 0 && maxExecutorCores > 0) { numSparkNodes = numNodes; MAX_EXECUTOR_CORES = maxExecutorCores; } else return DEFAULT_MAX_EXECUTOR_CORES; } return MAX_EXECUTOR_CORES; }
Source:
<code>public ValidationResult clusterNetworkNotUsedByTemplates() { List<VmTemplate> templatesUsingNetwork = new ArrayList<VmTemplate>(); for (VmTemplate template : getVmTemplateDAO().getAllForVdsGroup(networkCluster.getClusterId())) { <START> for (VmNetworkInterface nic : getVmNetworkInterfaceDao().getAllForTemplate(networkCluster.getClusterId())) { <END> if (nic.getNetworkName() == network.getName()) { templatesUsingNetwork.add(template); } } } return networkNotUsed(templatesUsingNetwork, VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES); }</code><technical_language>I meant: getVmNetworkInterfaceDao().getAllForTemplate(*template.getId()*)</technical_language>

Target:
public ValidationResult clusterNetworkNotUsedByTemplates() { List<VmTemplate> templatesUsingNetwork = new ArrayList<VmTemplate>(); for (VmTemplate template : getVmTemplateDAO().getAllForVdsGroup(networkCluster.getClusterId())) { for (VmNetworkInterface nic : getVmNetworkInterfaceDao().getAllForTemplate(template.getId())) { if (nic.getNetworkName().equals(network.getName())) { templatesUsingNetwork.add(template); } } } return networkNotUsed(templatesUsingNetwork, VdcBllMessages.VAR__ENTITIES__VM_TEMPLATES); }
Source:
<code>public void onErrorResponse(VolleyError error) { int statusCode = VolleyUtils.statusCodeFromVolleyError(error); if (statusCode == 404) { mUrlSkipList.add(mRequestedURL); } <START> if (mUrl != null && !mUrl.equals(mRequestedURL)) { <END> AppLog.w(AppLog.T.UTILS, "WPNetworkImageView > request no longer valid: " + mRequestedURL); return; } showErrorImage(); if (mImageLoadListener != null) { mImageLoadListener.onError(); } }</code><technical_language>this if (mUrl == null || !mUrl.equals(mRequestedURL))? if mUrl is null means request is longer valid</technical_language>

Target:
public void onErrorResponse(VolleyError error) { int statusCode = VolleyUtils.statusCodeFromVolleyError(error); if (statusCode == 404) { mUrlSkipList.add(mRequestedURL); } if (mUrl == null || !mUrl.equals(mRequestedURL)) { AppLog.w(AppLog.T.UTILS, "WPNetworkImageView > request no longer valid: " + mRequestedURL); return; } showErrorImage(); if (mImageLoadListener != null) { mImageLoadListener.onError(); } }
Source:
<code>public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { File mdlRsrc = IgniteUtils.resolveIgnitePath(MODEL_PATH); if (mdlRsrc == null) throw new IllegalArgumentException("Resource not found [resource_path=" + MODEL_PATH + "]"); InfModelReader reader = new DirectoryInfModelReader(mdlRsrc.getPath()); <START> InfModelParser<double[], Long> parser = new TensorFlowSavedModelInfModelParser<double[], Long>("serve") <END> .withInput("Placeholder", doubles -> { float[][][] reshaped = new float[1][28][28]; for (int i = 0; i < doubles.length; i++) reshaped[0][i / 28][i % 28] = (float)doubles[i]; return Tensor.create(reshaped); }) .withOutput(Collections.singletonList("ArgMax"), collectedTensors -> { return collectedTensors.get("ArgMax").copyTo(new long[1])[0]; }); List<MnistUtils.MnistLabeledImage> images = MnistUtils.mnistAsListFromResource( MNIST_IMG_PATH, MNIST_LBL_PATH, new Random(0), 10000 ); long t0 = System.currentTimeMillis(); try (InfModel<double[], Future<Long>> threadedMdl = new IgniteDistributedInfModelBuilder(ignite, 4, 4) .build(reader, parser)) { List<Future<?>> futures = new ArrayList<>(images.size()); for (MnistUtils.MnistLabeledImage image : images) futures.add(threadedMdl.predict(image.getPixels())); for (Future<?> f : futures) f.get(); } long t1 = System.currentTimeMillis(); System.out.println("Threaded model throughput: " + images.size() / ((t1 - t0) / 1000.0) + " req/sec"); } }</code><technical_language>TFModelParser is</technical_language>

Target:
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { File mdlRsrc = IgniteUtils.resolveIgnitePath(MODEL_PATH); if (mdlRsrc == null) throw new IllegalArgumentException("Resource not found [resource_path=" + MODEL_PATH + "]"); InfModelReader reader = new FileSystemInfModelReader(mdlRsrc.getPath()); InfModelParser<double[], Long> parser = new TensorFlowSavedModelInfModelParser<double[], Long>("serve") .withInput("Placeholder", doubles -> { float[][][] reshaped = new float[1][28][28]; for (int i = 0; i < doubles.length; i++) reshaped[0][i / 28][i % 28] = (float)doubles[i]; return Tensor.create(reshaped); }) .withOutput(Collections.singletonList("ArgMax"), collectedTensors -> { return collectedTensors.get("ArgMax").copyTo(new long[1])[0]; }); List<MnistUtils.MnistLabeledImage> images = MnistUtils.mnistAsListFromResource( MNIST_IMG_PATH, MNIST_LBL_PATH, new Random(0), 10000 ); long t0 = System.currentTimeMillis(); try (InfModel<double[], Future<Long>> threadedMdl = new IgniteDistributedInfModelBuilder(ignite, 4, 4) .build(reader, parser)) { List<Future<?>> futures = new ArrayList<>(images.size()); for (MnistUtils.MnistLabeledImage image : images) futures.add(threadedMdl.predict(image.getPixels())); for (Future<?> f : futures) f.get(); } long t1 = System.currentTimeMillis(); System.out.println("Threaded model throughput: " + images.size() / ((t1 - t0) / 1000.0) + " req/sec"); } }
Source:
<code><START> AzureCloudDestination(VerifiableProperties verProps) throws URISyntaxException, InvalidKeyException { <END> String configSpec = verProps.getString(STORAGE_CONFIG_SPEC); azureAccount = CloudStorageAccount.parse(configSpec); azureBlobClient = azureAccount.createCloudBlobClient(); String cosmosServiceEndpoint = verProps.getString(COSMOS_ENDPOINT); String cosmosKey = verProps.getString(COSMOS_KEY); cosmosCollectionLink = verProps.getString(COSMOS_COLLECTION_LINK); documentClient = new DocumentClient(cosmosServiceEndpoint, cosmosKey, ConnectionPolicy.GetDefault(), ConsistencyLevel.Session); try { ResourceResponse<DocumentCollection> response = documentClient.readCollection(cosmosCollectionLink, defaultRequestOptions); if (response.getResource() == null) { throw new IllegalArgumentException("CosmosDB collection not found: " + cosmosCollectionLink); } } catch (DocumentClientException ex) { throw new IllegalArgumentException("Invalid CosmosDB properties", ex); } LOGGER.info("Created Azure destination"); }</code><technical_language>I created CloudConfig file in [PR#1134](<LINK_0> a centralized place for cloud related configs</technical_language>

Target:
AzureCloudDestination(VerifiableProperties verProps) throws URISyntaxException, InvalidKeyException { String configSpec = verProps.getString(STORAGE_CONFIG_SPEC); azureAccount = CloudStorageAccount.parse(configSpec); azureBlobClient = azureAccount.createCloudBlobClient(); String cosmosServiceEndpoint = verProps.getString(COSMOS_ENDPOINT); String cosmosKey = verProps.getString(COSMOS_KEY); cosmosCollectionLink = verProps.getString(COSMOS_COLLECTION_LINK); documentClient = new DocumentClient(cosmosServiceEndpoint, cosmosKey, ConnectionPolicy.GetDefault(), ConsistencyLevel.Session); try { ResourceResponse<DocumentCollection> response = documentClient.readCollection(cosmosCollectionLink, defaultRequestOptions); if (response.getResource() == null) { throw new IllegalArgumentException("CosmosDB collection not found: " + cosmosCollectionLink); } } catch (DocumentClientException ex) { throw new IllegalArgumentException("Invalid CosmosDB properties", ex); } logger.info("Created Azure destination"); }
Source:
<code>private static WebArchive createWar(final String sd) { return ShrinkWrap.create(WebArchive.class, sd + ".war").addClasses(CheckIdentityPermissionServlet.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset(sd), "jboss-web.xml") .addAsManifestResource( <START> PermissionUtils.createPermissionsXmlAsset(new ElytronPermission("*")), "permissions.xml") <END> .addAsManifestResource( Utils.getJBossDeploymentStructure("org.wildfly.extension.batch.jberet", "org.wildfly.transaction.client", "org.jboss.ejb-client", "org.joda.time"), "jboss-deployment-structure.xml") .addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml"); }</code><technical_language>I accurate permissions required allPermission</technical_language>

Target:
private static WebArchive createWar(final String sd) { return ShrinkWrap.create(WebArchive.class, sd + ".war").addClasses(CheckIdentityPermissionServlet.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset(sd), "jboss-web.xml") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new ElytronPermission("authenticate"), new ElytronPermission("getSecurityDomain") ), "permissions.xml") .addAsManifestResource( Utils.getJBossDeploymentStructure("org.wildfly.extension.batch.jberet", "org.wildfly.transaction.client", "org.jboss.ejb-client", "org.joda.time"), "jboss-deployment-structure.xml") .addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml"); }
Source:
<code><START> public static void registerParameterProvider(String analysisId, Class<? extends IAnalysisParameterProvider> paramProvider) { <END> if (!fParameterProviders.containsKey(analysisId)) { fParameterProviders.put(analysisId, new ArrayList<Class<? extends IAnalysisParameterProvider>>()); } fParameterProviders.get(analysisId).add(paramProvider); }</code><technical_language>this called multiple threads? If is a concurrency issue. fParameterProviders needs handle thread safe in this class</technical_language>

Target:
public static void registerParameterProvider(String analysisId, Class<? extends IAnalysisParameterProvider> paramProvider) { synchronized (fParameterProviders) { if (!fParameterProviders.containsKey(analysisId)) { fParameterProviders.put(analysisId, new ArrayList<Class<? extends IAnalysisParameterProvider>>()); } fParameterProviders.get(analysisId).add(paramProvider); } }
Source:
<code>public void configureSSLEngine() { SSLConfig config = new SSLConfig.Builder().setCiphers("someCipher").setEnabled(true) .setProtocols("someProtocol").setRequireAuth(true).setKeystore("someKeystore.jks") .setAlias("someAlias").setTruststore("someTruststore.jks") .setEndpointIdentificationEnabled(true).build(); SSLContext context = mock(SSLContext.class); SSLParameters parameters = mock(SSLParameters.class); SocketCreator socketCreator = new SocketCreator(config, context); SSLEngine engine = mock(SSLEngine.class); when(engine.getSSLParameters()).thenReturn(parameters); engine.setEnableSessionCreation(true); socketCreator.configureSSLEngine(engine, "somehost", 12345, true); verify(engine).setUseClientMode(isA(Boolean.class)); verify(engine).setSSLParameters(parameters); <START> verify(engine).setEnabledCipherSuites(isA(String[].class)); <END> verify(engine).setEnabledProtocols(isA(String[].class)); verify(engine, never()).setNeedClientAuth(isA(Boolean.class)); }</code><technical_language>verify is called a String[] "someCipher"</technical_language>

Target:
public void configureSSLEngine() { SSLConfig config = new SSLConfig.Builder().setCiphers("someCipher").setEnabled(true) .setProtocols("someProtocol").setRequireAuth(true).setKeystore("someKeystore.jks") .setAlias("someAlias").setTruststore("someTruststore.jks") .setEndpointIdentificationEnabled(true).build(); SSLContext context = mock(SSLContext.class); SSLParameters parameters = mock(SSLParameters.class); SocketCreator socketCreator = new SocketCreator(config, context); SSLEngine engine = mock(SSLEngine.class); when(engine.getSSLParameters()).thenReturn(parameters); socketCreator.configureSSLEngine(engine, "somehost", 12345, true); verify(engine).setUseClientMode(isA(Boolean.class)); verify(engine).setSSLParameters(parameters); verify(engine, never()).setNeedClientAuth(isA(Boolean.class)); ArgumentCaptor<String[]> stringArrayCaptor = ArgumentCaptor.forClass(String[].class); verify(engine).setEnabledProtocols(stringArrayCaptor.capture()); assertThat(stringArrayCaptor.getValue()).containsExactly("someProtocol"); verify(engine).setEnabledCipherSuites(stringArrayCaptor.capture()); assertThat(stringArrayCaptor.getValue()).containsExactly("someCipher"); }