auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void addInputPort(InputPort<?> portObject, Field field, InputPortFieldAnnotation portAnnotation, AppData.QueryPort adqAnnotation) { if (!OperatorMeta.this.inputStreams.isEmpty()) { for (Map.Entry<LogicalPlan.InputPortMeta, LogicalPlan.StreamMeta> e : OperatorMeta.this.inputStreams.entrySet()) { LogicalPlan.InputPortMeta pm = e.getKey(); if (pm.operatorMeta == OperatorMeta.this && pm.fieldName.equals(field.getName())) { inPortMap.put(portObject, pm); markInputPortIfHidden(pm.getPortName(), pm, field.getDeclaringClass()); return; } } } InputPortMeta metaPort = new InputPortMeta(); metaPort.operatorMeta = OperatorMeta.this; metaPort.fieldName = field.getName(); metaPort.portAnnotation = portAnnotation; metaPort.adqAnnotation = adqAnnotation; inPortMap.put(portObject, metaPort); markInputPortIfHidden(metaPort.getPortName(), metaPort, field.getDeclaringClass()); if (metaPort.getStreamCodec() == null) { metaPort.setStreamCodec(portObject.getStreamCodec()); } else if (portObject.getStreamCodec() != null) { <START> LOG.info("Input port overwrites codec with {}.", metaPort, metaPort.getStreamCodec(), portObject.getStreamCodec()); <END> } }</code><technical_language>arguments flipped? log level debug? is log level in other scenarios overriding partitioner</technical_language>

Target:
public void addInputPort(InputPort<?> portObject, Field field, InputPortFieldAnnotation portAnnotation, AppData.QueryPort adqAnnotation) { if (!OperatorMeta.this.inputStreams.isEmpty()) { for (Map.Entry<LogicalPlan.InputPortMeta, LogicalPlan.StreamMeta> e : OperatorMeta.this.inputStreams.entrySet()) { LogicalPlan.InputPortMeta pm = e.getKey(); if (pm.operatorMeta == OperatorMeta.this && pm.fieldName.equals(field.getName())) { inPortMap.put(portObject, pm); markInputPortIfHidden(pm.getPortName(), pm, field.getDeclaringClass()); return; } } } InputPortMeta metaPort = new InputPortMeta(); metaPort.operatorMeta = OperatorMeta.this; metaPort.fieldName = field.getName(); metaPort.portAnnotation = portAnnotation; metaPort.adqAnnotation = adqAnnotation; inPortMap.put(portObject, metaPort); markInputPortIfHidden(metaPort.getPortName(), metaPort, field.getDeclaringClass()); if (metaPort.getStreamCodec() == null) { metaPort.setStreamCodec(portObject.getStreamCodec()); } else if (portObject.getStreamCodec() != null) { LOG.info("Input port attribute overrides codec with codec", metaPort.getPortName(), STREAM_CODEC.getSimpleName(), portObject.getStreamCodec(), metaPort.getStreamCodec()); } }
Source:
<code>public void testAlterReplicaLogDirsSuccess() throws Exception { <START> Node node0 = new Node(0, "localhost", 8120); <END> Node node1 = new Node(1, "localhost", 8121); try (AdminClientUnitTestEnv env = mockClientEnv()) { createAlterLogDirsResponse(env, node0, Errors.NONE, 0); createAlterLogDirsResponse(env, node1, Errors.NONE, 0); TopicPartitionReplica tpr0 = new TopicPartitionReplica("topic", 0, 0); TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic", 0, 1); Map<TopicPartitionReplica, String> logDirs = new HashMap<>(); logDirs.put(tpr0, "/data0"); logDirs.put(tpr1, "/data1"); AlterReplicaLogDirsResult result = env.adminClient().alterReplicaLogDirs(logDirs); result.values().get(tpr0).get(); result.values().get(tpr1).get(); } }</code><technical_language>nit: mocked environment creates 3 nodes (by default) create them. get env.getCluster().nodeById(..)</technical_language>

Target:
public void testAlterReplicaLogDirsSuccess() throws Exception { try (AdminClientUnitTestEnv env = mockClientEnv()) { createAlterLogDirsResponse(env, env.cluster().nodeById(0), Errors.NONE, 0); createAlterLogDirsResponse(env, env.cluster().nodeById(1), Errors.NONE, 0); TopicPartitionReplica tpr0 = new TopicPartitionReplica("topic", 0, 0); TopicPartitionReplica tpr1 = new TopicPartitionReplica("topic", 0, 1); Map<TopicPartitionReplica, String> logDirs = new HashMap<>(); logDirs.put(tpr0, "/data0"); logDirs.put(tpr1, "/data1"); AlterReplicaLogDirsResult result = env.adminClient().alterReplicaLogDirs(logDirs); assertNull(result.values().get(tpr0).get()); assertNull(result.values().get(tpr1).get()); } }
Source:
<code>public Optional<Axis> toAxis() { <START> switch ((BlockLog.EnumAxis) (Object) this) { <END> case X: return Optional.of(Axis.X); case Y: return Optional.of(Axis.Y); case Z: return Optional.of(Axis.Z); default: return Optional.empty(); } }</code><technical_language>sense stick o.s.a.Axis a bridge method EnumAxis? I switch statements is</technical_language>

Target:
public Optional<Axis> toAxis() { return Constants.DirectionFunctions.convertLogAxisToSponge((BlockLog.EnumAxis) (Object) this); }
Source:
<code>public void testService() throws Exception { <START> HttpClient http = (HttpClient) Runtime.start("http", "HttpClient"); <END> http.attach(catcher); catcher.clear(); String data = http.get("<LINK_0>"); log.info(data); Message msg = catcher.getMsg(1000); assertNotNull("msg from get is null", msg); assertTrue("didn't get HttpData", HttpData.class.equals(msg.data[0].getClass())); assertTrue("response code != 200", ((HttpData) (msg.data[0])).responseCode == 200); http.postForm("<LINK_2>", "foo1", "bar1", "foo2", "bar2", "foo3", "bar with spaces"); log.info(data); data = http.get("<LINK_6>"); log.info(data); String response = http.post("<LINK_1>"); log.info(response); response = http.post("<LINK_1>"); log.info(response); response = http.get("<LINK_5>"); log.info(response); String json = http.get("<LINK_3>"); log.info(json); http.detach(catcher); }</code><technical_language>this created in createService() method. this.service is httpClient created already</technical_language>

Target:
public void testService() throws Exception { if (hasInternet()) { TestCatcher catcher = (TestCatcher) Runtime.start("catcher", "TestCatcher"); HttpClient http = (HttpClient) Runtime.start("http", "HttpClient"); http.attach(catcher); catcher.clear(); String data = http.get("<LINK_0>"); log.info(data); Message msg = catcher.getMsg(1000); assertNotNull("msg from get is null", msg); assertTrue("didn't get HttpData", HttpData.class.equals(msg.data[0].getClass())); assertTrue("response code != 200", ((HttpData) (msg.data[0])).responseCode == 200); http.postForm("<LINK_2>", "foo1", "bar1", "foo2", "bar2", "foo3", "bar with spaces"); log.info(data); data = http.get("<LINK_6>"); log.info(data); String response = http.post("<LINK_1>"); log.info(response); response = http.post("<LINK_1>"); log.info(response); response = http.get("<LINK_5>"); log.info(response); http.detach(catcher); } }
Source:
<code>public URLClassLoader loadDependencies() { URL[] dependencies = launchDependencies.toArray(new URL[launchDependencies.size()]); <START> ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); <END> URLClassLoader cl = URLClassLoader.newInstance(dependencies, currentContextClassLoader); Thread.currentThread().setContextClassLoader(cl); StringCodecs.check(); return cl; }</code><technical_language>created URL class loaders cached, necessary create a new class loader time loadDependencies() is called</technical_language>

Target:
public URLClassLoader loadDependencies() { if (this.loaderThread == null && this.initialClassLoader == null) { this.loaderThread = Thread.currentThread(); this.initialClassLoader = Thread.currentThread().getContextClassLoader(); } if (Thread.currentThread() != this.loaderThread) { throw new RuntimeException("Calls to loadDependencies can only be made on the same thread that loadDependencies was called on for the first time"); } else { URL[] dependencies = launchDependencies.toArray(new URL[launchDependencies.size()]); ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader cl = URLClassLoader.newInstance(dependencies, currentContextClassLoader); Thread.currentThread().setContextClassLoader(cl); StringCodecs.check(); return cl; } }
Source:
<code>boolean isHandleWritable() { <START> return !getLedgerMetadata().isClosed(); <END> }</code><technical_language>do deal readonly ledger handle</technical_language>

Target:
protected boolean isHandleWritable() { return !getLedgerMetadata().isClosed(); }
Source:
<code>public static DataIndexer getDataIndexer(TrainingParameters parameters,Map<String,String> reportMap) { String indexerKey = parameters.getStringParameter(AbstractEventTrainer.DATA_INDEXER_PARAM, AbstractEventTrainer.DATA_INDEXER_TWO_PASS_VALUE); if (reportMap == null) reportMap = new HashMap<>(); <START> if (_indexers.containsKey(indexerKey)) { <END> Class<? extends DataIndexer> type = _indexers.get(indexerKey); DataIndexer indexer; try { indexer = type.newInstance(); } catch (Exception e) { String msg = "Could not instantiate the indexer " + type.getCanonicalName() + ". The initialization threw an exception."; System.err.println(msg); e.printStackTrace(); throw new IllegalArgumentException(msg, e); } indexer.init(parameters, reportMap); return indexer; } DataIndexer indexer = ExtensionLoader.instantiateExtension(DataIndexer.class, indexerKey); indexer.init(parameters, reportMap); return indexer; }</code><technical_language>code nicer if a switch new instantiate built-in ones. If work is else block call ExtensionLoader</technical_language>

Target:
public static DataIndexer getDataIndexer(TrainingParameters parameters,Map<String,String> reportMap) { String indexerParam = parameters.getStringParameter(AbstractEventTrainer.DATA_INDEXER_PARAM, AbstractEventTrainer.DATA_INDEXER_TWO_PASS_VALUE); if (reportMap == null) reportMap = new HashMap<>(); DataIndexer indexer = null; switch (indexerParam) { case AbstractEventTrainer.DATA_INDEXER_ONE_PASS_VALUE : indexer = new OnePassDataIndexer(); break; case AbstractEventTrainer.DATA_INDEXER_TWO_PASS_VALUE : indexer = new TwoPassDataIndexer(); break; case AbstractEventTrainer.DATA_INDEXER_ONE_PASS_REAL_VALUE : indexer = new OnePassRealValueDataIndexer(); break; default: indexer = ExtensionLoader.instantiateExtension(DataIndexer.class, indexerParam); } indexer.init(parameters, reportMap); return indexer; }
Source:
<code><START> void onCanvasElementSelectedEvent(@Observes CanvasElementSelectedEvent event) { <END> checkNotNull("event", event); final String uuid = event.getElementUUID(); if (isSameCanvas(event) && isRegistered(uuid)) { final HasControlPoints<?> hasControlPoints = getControlPointsInstance(uuid); if (!hasControlPoints.areControlsVisible()) { showCPs(hasControlPoints); } else { hideCPs(hasControlPoints); } } }</code><technical_language>Is package private intentionally? this method test and, probably, used</technical_language>

Target:
private void onCanvasElementSelectedEvent(@Observes CanvasElementSelectedEvent event) { checkNotNull("event", event); final String uuid = event.getElementUUID(); if (isSameCanvas(event) && isRegistered(uuid)) { final HasControlPoints<?> hasControlPoints = getControlPointsInstance(uuid); if (!hasControlPoints.areControlsVisible()) { showCPs(hasControlPoints); } else { hideCPs(hasControlPoints); } } }
Source:
<code>private static void matchDns(String name, X509Certificate cert) throws CertificateException { Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames(); if (subjAltNames != null) { List<String> nonMatchingDnsAltnames = new LinkedList<>(); for (List<?> san : subjAltNames) { if (((Integer) san.get(0)).intValue() != ALTNAME_DNS) { continue; } String dnsName = (String) san.get(1); if (matchesPerRfc2818(name, dnsName)) { return; } else { nonMatchingDnsAltnames.add(dnsName); } } if (!nonMatchingDnsAltnames.isEmpty()) { StringBuilder sb = new StringBuilder("No subject alternative DNS name matching " + name + " found. Tried: "); for (String nonMatchingDnsAltname : nonMatchingDnsAltnames) { sb.append(nonMatchingDnsAltname).append(","); } throw new CertificateException(sb.toString()); } } try { LdapName dn = new LdapName(cert.getSubjectX500Principal().getName()); for (Rdn rdn : dn.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { if (matchesPerRfc2818(name, rdn.getValue().toString())) { return; } break; } } <START> } catch (Exception e) { <END> LOGGER.warning("Invalid DN: " + e.getMessage()); } throw new CertificateException("No name matching " + name + " found"); }</code><technical_language>Ahh, I see. Please catch more specific restrict try block places throw is expected occur. if log level warning, other logs 'info'. a warning is justified in this case</technical_language>

Target:
private static void matchDns(String name, X509Certificate cert) throws CertificateException { Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames(); if (subjAltNames != null) { List<String> nonMatchingDnsAltnames = new LinkedList<>(); for (List<?> san : subjAltNames) { if (((Integer) san.get(0)).intValue() != ALTNAME_DNS) { continue; } String dnsName = (String) san.get(1); if (matchesPerRfc2818(name, dnsName)) { return; } else { nonMatchingDnsAltnames.add(dnsName); } } if (!nonMatchingDnsAltnames.isEmpty()) { StringBuilder sb = new StringBuilder("No subject alternative DNS name matching " + name + " found. Tried: "); for (String nonMatchingDnsAltname : nonMatchingDnsAltnames) { sb.append(nonMatchingDnsAltname).append(","); } throw new CertificateException(sb.toString()); } } LdapName dn = null; try { dn = new LdapName(cert.getSubjectX500Principal().getName()); } catch (InvalidNameException e) { LOGGER.warning("Invalid DN: " + e.getMessage()); } if (dn != null) { for (Rdn rdn : dn.getRdns()) { if (rdn.getType().equalsIgnoreCase("CN")) { if (matchesPerRfc2818(name, rdn.getValue().toString())) { return; } break; } } } throw new CertificateException("No name matching " + name + " found"); }
Source:
<code><START> public void testStateChangeWithUnknownInstance() throws InterruptedException { <END> AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); Instance inst = new Instance( "inst" ).status( InstanceStatus.DEPLOYED_STOPPED ).component( new Component( "unknown" )); processor.processMessage( new MsgCmdChangeInstanceState( inst, InstanceStatus.DEPLOYED_STARTED )); Assert.assertEquals( InstanceStatus.DEPLOYED_STOPPED, inst.getStatus()); processor.scopedInstance = new TestApplicationTemplate().getMySqlVm(); processor.processMessage( new MsgCmdChangeInstanceState( inst, InstanceStatus.DEPLOYED_STARTED )); Assert.assertEquals( InstanceStatus.DEPLOYED_STOPPED, inst.getStatus()); }</code><technical_language>No, this method throw interrupted exceptions</technical_language>

Target:
public void testStateChangeWithUnknownInstance() { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); Instance inst = new Instance( "inst" ).status( InstanceStatus.DEPLOYED_STOPPED ).component( new Component( "unknown" )); processor.processMessage( new MsgCmdChangeInstanceState( inst, InstanceStatus.DEPLOYED_STARTED )); Assert.assertEquals( InstanceStatus.DEPLOYED_STOPPED, inst.getStatus()); processor.scopedInstance = new TestApplicationTemplate().getMySqlVm(); processor.processMessage( new MsgCmdChangeInstanceState( inst, InstanceStatus.DEPLOYED_STARTED )); Assert.assertEquals( InstanceStatus.DEPLOYED_STOPPED, inst.getStatus()); }
Source:
<code>public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof CompoundObjectId)) { return false; } CompoundObjectId compoundObjectId = (CompoundObjectId)object; <START> <END> if (this.id.keySet().size() != compoundObjectId.size()) { return false; } for (Map.Entry<String, Object> entry : ((Map<String, Object>)compoundObjectId.get()).entrySet()) { String entryKey = entry.getKey(); Object entryValue = entry.getValue(); if (entryValue == null) { if (this.id.get(entryKey) != null || !this.id.containsKey(entryKey)) { return false; } } else { if (!this.id.get(entryKey).equals(entryValue)) { return false; } } } return true; }</code><technical_language>is code there? this line replaced id.equals(other.id)... equals hashCode require unit tests</technical_language>

Target:
public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof CompoundObjectId)) { return false; } return id.equals(((CompoundObjectId)object).id); }
Source:
<code>protected void executeVdsBrokerCommand() { <START> _result = getBroker().getStorageDomainStats(getParameters().getStorageDomainId().toString()); <END> proceedProxyReturnValue(); StorageDomain domain = buildStorageDynamicFromXmlRpcStruct(_result.storageStats); domain.setId(getParameters().getStorageDomainId()); setReturnValue(domain); }</code><technical_language>please rename _result</technical_language>

Target:
protected void executeVdsBrokerCommand() { result = getBroker().getStorageDomainStats(getParameters().getStorageDomainId().toString()); proceedProxyReturnValue(); StorageDomain domain = buildStorageDynamicFromXmlRpcStruct(result.storageStats); domain.setId(getParameters().getStorageDomainId()); setReturnValue(domain); }
Source:
<code>public Metacard toQueryTemplateMetacard(Map<String, Object> formTemplate) { <START> Map<String, Object> filterJson = (Map) formTemplate.get("filterTemplate"); <END> String title = (String) formTemplate.get("title"); String description = (String) formTemplate.get("description"); TransformVisitor<JAXBElement> visitor = new TransformVisitor<>(new XmlModelBuilder()); try { VisitableJsonElementImpl.create(new FilterNodeMapImpl(filterJson)).accept(visitor); JAXBElement filter = visitor.getResult(); if (!filter.getDeclaredType().equals(FilterType.class)) { LOGGER.error( "Error occurred during filter processing, root type should be a but was {}", FilterType.class.getName(), filter.getDeclaredType().getName()); return null; } String id = (String) formTemplate.get("id"); QueryTemplateMetacard metacard = (id == null) ? new QueryTemplateMetacard(title, description) : new QueryTemplateMetacard(title, description, id); String filterXml = writer.marshal(filter); metacard.setFormsFilter(filterXml); Map<String, Object> querySettings = (Map<String, Object>) formTemplate.get("querySettings"); if (querySettings != null) { metacard.setQuerySettings(querySettings); } return metacard; } catch (JAXBException e) { LOGGER.error("XML generation failed for query template metacard's filter", e); } catch (FilterProcessingException e) { LOGGER.error("Could not use filter JSON for template - {}", e.getMessage()); } return null; }</code><technical_language>Do need a default some error handling if filterTemplate is (null)</technical_language>

Target:
public Metacard toQueryTemplateMetacard(Map<String, Object> formTemplate) { Map<String, Object> filterJson = (Map) formTemplate.get("filterTemplate"); String title = (String) formTemplate.get("title"); String description = (String) formTemplate.get("description"); if (filterJson == null) { return null; } TransformVisitor<JAXBElement> visitor = new TransformVisitor<>(new XmlModelBuilder()); try { VisitableJsonElementImpl.create(new FilterNodeMapImpl(filterJson)).accept(visitor); JAXBElement filter = visitor.getResult(); if (!filter.getDeclaredType().equals(FilterType.class)) { LOGGER.error( "Error occurred during filter processing, root type should be a but was {}", FilterType.class.getName(), filter.getDeclaredType().getName()); return null; } String id = (String) formTemplate.get("id"); QueryTemplateMetacard metacard = (id == null) ? new QueryTemplateMetacard(title, description) : new QueryTemplateMetacard(title, description, id); String filterXml = writer.marshal(filter); metacard.setFormsFilter(filterXml); Map<String, Object> querySettings = (Map<String, Object>) formTemplate.get("querySettings"); if (querySettings != null) { metacard.setQuerySettings(querySettings); } return metacard; } catch (JAXBException e) { LOGGER.error("XML generation failed for query template metacard's filter", e); } catch (FilterProcessingException e) { LOGGER.error("Could not use filter JSON for template - {}", e.getMessage()); } return null; }
Source:
<code>public void test() { connect(); sendKeys(jq("$d1").toWidget().$n("real"), "Aug 32, 2018"); waitResponse(); click(jq("body")); waitResponse(true); Assert.assertEquals("Sep 1, 2018", jq("$d1").toWidget().$n("real").get("value")); sendKeys(jq("$d2").toWidget().$n("real"), "Aug 32, 2018"); waitResponse(); click(jq("body")); waitResponse(); Assert.assertTrue(jq(".z-errorbox").exists()); click(jq("body")); waitResponse(); <START> sendKeys(jq("$d2").toWidget().$n("real"), "Feb 30, 2018"); <END> waitResponse(); click(jq("body")); waitResponse(); Assert.assertTrue(jq(".z-errorbox").exists()); click(jq("body")); waitResponse(); sendKeys(jq("$d2").toWidget().$n("real"), "Feb 0, 2018"); waitResponse(); click(jq("body")); waitResponse(); Assert.assertTrue(jq(".z-errorbox").exists()); }</code><technical_language>new test case zul</technical_language>

Target:
public void test() { connect(); JQuery dummyButton = jq("$dummy"); sendKeys(jq("$d1").toWidget().$n("real"), "Aug 32, 2018"); waitResponse(); click(dummyButton); waitResponse(); Assert.assertEquals("Sep 1, 2018", jq("$d1").toWidget().$n("real").get("value")); sendKeys(jq("$d2").toWidget().$n("real"), "Aug 32, 2018"); waitResponse(); click(dummyButton); waitResponse(); Assert.assertTrue(jq(".z-errorbox").exists()); sendKeys(jq("$d2").toWidget().$n("real"), "Feb 30, 2018"); waitResponse(); click(dummyButton); waitResponse(); Assert.assertTrue(jq(".z-errorbox").exists()); sendKeys(jq("$d2").toWidget().$n("real"), "Feb 0, 2018"); waitResponse(); click(dummyButton); waitResponse(); Assert.assertTrue(jq(".z-errorbox").exists()); }
Source:
<code>public byte[] signJWT(String assertion) throws APIManagementException { PrivateKey privateKey; <START> KeyStoreManager tenantKSM = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); <END> try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { String msg = "Error while obtaining private key for super tenant"; log.error("Error while obtaining private key for super tenant", e); throw new APIManagementException(msg, e); } return APIUtil.signJwt(assertion, privateKey, signatureAlgorithm); }</code><technical_language>rename variable superTenantKSM</technical_language>

Target:
public byte[] signJWT(String assertion) throws APIManagementException { PrivateKey privateKey; KeyStoreManager superTenantKSM = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); try { privateKey = superTenantKSM.getDefaultPrivateKey(); } catch (Exception e) { String msg = "Error while obtaining private key for super tenant"; log.error(msg, e); throw new APIManagementException(msg, e); } return APIUtil.signJwt(assertion, privateKey, signatureAlgorithm); }
Source:
<code>public void process(Exchange exchange) throws Exception { final Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String binaryPath = (String) in.getHeader(CdrBinaryPath); String binarySubPath = (String) in.getHeader(CdrBinarySubPath); String text; try { text = extractText(binaryPath); } catch (TikaException e) { log.error("Failed to extract text for due to parsing error", binaryUri, e); return; } <START> String filepath = derivativeBasePath + "/" + binarySubPath + ".txt"; <END> File derivative = new File(filepath); File parentDir = derivative.getParentFile(); if (parentDir != null) { parentDir.mkdirs(); } try (PrintWriter fulltext = new PrintWriter(filepath)) { fulltext.println(text); } }</code><technical_language>safer do File derivative = Paths.get(derivativeBasePath, binarySubPath + ".txt").toFile(); in case of stray slashes</technical_language>

Target:
public void process(Exchange exchange) throws Exception { final Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String binaryPath = (String) in.getHeader(CdrBinaryPath); String binaryId = PIDs.get(binaryUri).getId(); String binarySubPath = RepositoryPaths .idToPath(binaryId, HASHED_PATH_DEPTH, HASHED_PATH_SIZE); String text; try { text = extractText(binaryPath); } catch (TikaException e) { log.error("Failed to extract text for due to parsing error", binaryUri, e); return; } Path derivativePath = Paths.get(derivativeBasePath, binarySubPath + "/" + binaryId + ".txt"); File derivative = derivativePath.toFile(); File parentDir = derivative.getParentFile(); if (parentDir != null && !parentDir.mkdirs()) { throw new IOException("Failed to create parent directories for " + derivativePath); } try (PrintWriter fulltext = new PrintWriter(derivativePath.toString())) { fulltext.println(text); } }
Source:
<code>public Path createCourseFolder(Path path, String folderName) { if (!isNullOrEmpty(folderName)) { path = path.resolve(folderName); } if (!Files.exists(path)) { <START> path.toFile().mkdirs(); <END> } return path; }</code><technical_language>Prefer [java.nio.Files#createDirectories(Path dir, FileAttribute<?>... attrs)](<LINK_1>,%20java.nio.file.attribute.FileAttribute...%29) (and [java.nio.Files#notExists(Path path, LinkOption... options)](<LINK_0>,%20java.nio.file.LinkOption...%29) line above, this slightly semantics)</technical_language>

Target:
public Path createCourseFolder(Path path, String folderName) throws IOException{ if (!isNullOrEmpty(folderName)) { path = path.resolve(folderName); } if (Files.notExists(path)) { Files.createDirectories(path); } return path; }
Source:
<code>private void handleRefreshCapabilitiesResponse(VDS vds, VDSReturnValue caps, boolean throwException) { try { invokeGetHardwareInfo(vds, caps); processRefreshCapabilitiesResponse(new AtomicBoolean(), vds, vds.clone(), caps); } catch (Throwable t) { logRefreshCapabilitiesFailure(t); if (throwException) { throw t; } } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); <START> updateStaticData(vds.getStaticData()); <END> monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }</code><technical_language>Updating static table periodically monitoring is a good idea. IIUC, host's data is split static dynamic DB tables, dynamic table updated monitoring. FIPS field moved copied VdsDynamic? If not, static table updated needed</technical_language>

Target:
private void handleRefreshCapabilitiesResponse(VDS vds, VDSReturnValue caps, boolean throwException) { try { invokeGetHardwareInfo(vds, caps); processRefreshCapabilitiesResponse(new AtomicBoolean(), vds, vds.clone(), caps); } catch (Throwable t) { logRefreshCapabilitiesFailure(t); if (throwException) { throw t; } } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); maybeUpdateStaticData(vds.getStaticData()); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }
Source:
<code>private InnerBuilder() { <START> this.cepInputType = cepInputType; <END> this.cepInputConfiguration = new HashMap<>(); this.fields = new ArrayList<>(); this.propertyNames = new HashSet<>(); }</code><technical_language>type assigned in this case</technical_language>

Target:
private InnerBuilder() { this.cepInputType = null; this.cepInputConfiguration = new HashMap<>(); this.fields = new ArrayList<>(); this.propertyNames = new HashSet<>(); }
Source:
<code>public void cloneSupported() { HtmlDocumentHandler documentHandler = new HtmlDocumentHandler() { @Override public void endDocument(HtmlDocumentBuilder builder, XmlStreamWriter writer) { } @Override public void beginDocument(HtmlDocumentBuilder builder, XmlStreamWriter writer) { } }; HtmlSubsetLanguage language = new HtmlSubsetLanguage("Test", documentHandler, 6, Sets.newHashSet(BlockType.PARAGRAPH, BlockType.DIV, BlockType.QUOTE), Sets.newHashSet(SpanType.CITATION, SpanType.EMPHASIS), ImmutableMap.of(SpanType.ITALIC, "italic"), Collections.<SpanHtmlElementStrategy> emptyList()); HtmlSubsetLanguage cloned = language.clone(); assertEquals(language.getName(), cloned.getName()); assertEquals(language.getSupportedBlockTypes(), cloned.getSupportedBlockTypes()); assertEquals(language.getSupportedHeadingLevel(), cloned.getSupportedHeadingLevel()); <START> assertEquals(language.getSupportedSpanTypes(), cloned.getSupportedSpanTypes()); <END> }</code><technical_language>some assertion passed values in fact</technical_language>

Target:
public void cloneSupported() { HtmlDocumentHandler documentHandler = new HtmlDocumentHandler() { @Override public void endDocument(HtmlDocumentBuilder builder, XmlStreamWriter writer) { } @Override public void beginDocument(HtmlDocumentBuilder builder, XmlStreamWriter writer) { } }; HtmlSubsetLanguage language = new HtmlSubsetLanguage("Test", documentHandler, 6, Sets.newHashSet(BlockType.PARAGRAPH, BlockType.DIV, BlockType.QUOTE), Sets.newHashSet(SpanType.CITATION, SpanType.EMPHASIS), ImmutableMap.of(SpanType.BOLD, "new-bold"), Collections.<SpanHtmlElementStrategy> emptyList()); HtmlSubsetLanguage cloned = language.clone(); assertEquals(language.getName(), cloned.getName()); assertEquals(language.getSupportedBlockTypes(), cloned.getSupportedBlockTypes()); assertEquals(language.getSupportedHeadingLevel(), cloned.getSupportedHeadingLevel()); assertEquals(language.getSupportedSpanTypes(), cloned.getSupportedSpanTypes()); assertEquals(language.getTagNameSubstitutions(), cloned.getTagNameSubstitutions()); }
Source:
<code>public Producer createProducer() throws Exception { if (endpointType == EndpointType.dataset) { return new DataSetFlinkProducer(this); } <START> else if (endpointType == EndpointType.datastream) { <END> return new DataStreamFlinkProducer(this); } else return null; }</code><technical_language>Run command line this goal: mvn install -Psourcecheck in camel-flink directory fix checkstyle issues reports</technical_language>

Target:
public Producer createProducer() throws Exception { if (endpointType == EndpointType.dataset) { return new DataSetFlinkProducer(this); } else if (endpointType == EndpointType.datastream) { return new DataStreamFlinkProducer(this); } else { return null; } }
Source:
<code>protected N performAdd(N incoming) { ClusterPolicy entity = getClusterPolicy(); <START> validateUpdate(incoming, map(entity)); <END> performAction(VdcActionType.EditClusterPolicy, getParametersProvider().getParameters(incoming, entity)); entity = getClusterPolicy(); updateIncomingId(incoming); N model = map(entity, incoming); return addLinks(doPopulate(model, entity)); }</code><technical_language>remove this line</technical_language>

Target:
protected N performAdd(N incoming) { ClusterPolicy entity = getClusterPolicy(); performAction(VdcActionType.EditClusterPolicy, getAddParametersProvider().getParameters(incoming, entity)); entity = getClusterPolicy(); updateIncomingId(incoming); N model = map(entity, incoming); return addLinks(doPopulate(model, entity)); }
Source:
<code>public void replaceExisting() throws Exception { client.apply(new AddSecretAuthentication.Builder(TEST_REALM_NAME) .password("secret") .build()); <START> ops.exists(TEST_SECRET_IDENTITY_ADDRESS); <END> client.apply(new AddSecretAuthentication.Builder(TEST_REALM_NAME) .password(PASSWORD) .replaceExisting() .build()); assertTrue("Server identity should be created", ops.exists(TEST_SECRET_IDENTITY_ADDRESS)); ModelNodeResult result = ops.readAttribute(TEST_SECRET_IDENTITY_ADDRESS, "value"); result.assertSuccess(); assertEquals("Password should be encoded properly.", PASSWORD, new String(BaseEncoding.base64().decode(result.stringValue()))); }</code><technical_language>Result used</technical_language>

Target:
public void replaceExisting() throws Exception { client.apply(new AddSecretAuthentication.Builder(TEST_REALM_NAME) .password("secret") .build()); assertTrue("Server identyty should be created", ops.exists(TEST_SECRET_IDENTITY_ADDRESS)); client.apply(new AddSecretAuthentication.Builder(TEST_REALM_NAME) .password(PASSWORD) .replaceExisting() .build()); assertTrue("Server identity should be created", ops.exists(TEST_SECRET_IDENTITY_ADDRESS)); ModelNodeResult result = ops.readAttribute(TEST_SECRET_IDENTITY_ADDRESS, "value"); result.assertSuccess(); assertEquals("Password should be encoded properly.", PASSWORD, new String(BaseEncoding.base64().decode(result.stringValue()), "UTF-8")); }
Source:
<code>public void completeCheckout(Checkout checkout, final Callback<Payment> callback) { if (checkout == null) { throw new NullPointerException("checkout cannot be null"); } <START> PaymentRequest paymentRequest = new PaymentRequest(); <END> String paymentSessionId = checkout.getPaymentSessionId(); if (!TextUtils.isEmpty(paymentSessionId)) { paymentRequest.setPaymentSessionId(paymentSessionId); } PaymentRequestWrapper paymentRequestWrapper = new PaymentRequestWrapper(paymentRequest); retrofitService.completeCheckout(paymentRequestWrapper, checkout.getToken()).observeOn(getCallbackScheduler()).subscribe(new InternalCallback<PaymentWrapper>() { @Override public void success(PaymentWrapper paymentWrapper, Response response) { callback.success(paymentWrapper.getPayment(), response); } @Override public void failure(RetrofitError error) { callback.failure(error); } }); }</code><technical_language>a constructor takes sessionId, is a write object</technical_language>

Target:
public void completeCheckout(Checkout checkout, final Callback<Payment> callback) { if (checkout == null) { throw new NullPointerException("checkout cannot be null"); } PaymentRequest paymentRequest = new PaymentRequest(checkout.getPaymentSessionId()); PaymentRequestWrapper paymentRequestWrapper = new PaymentRequestWrapper(paymentRequest); retrofitService.completeCheckout(paymentRequestWrapper, checkout.getToken()).observeOn(getCallbackScheduler()).subscribe(new InternalCallback<PaymentWrapper>() { @Override public void success(PaymentWrapper paymentWrapper, Response response) { callback.success(paymentWrapper.getPayment(), response); } @Override public void failure(RetrofitError error) { callback.failure(error); } }); }
Source:
<code>public void setUp() { classInstance = new urn_perun_user_facility_attribute_def_virt_shell(); session = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); preffered = new Attribute(); <START> def_def_shell = new Attribute(); <END> facilityShell = new Attribute(); resourceShell = new ArrayList(); listOfMntPts = new ArrayList<String>(); for(int i=0;i<5;i++) listOfMntPts.add("/mnt/bash" + i); preffered.setValue(new ArrayList(listOfMntPts)); listOfMntPts.clear(); listOfMntPts.add("/mnt/bash2"); facilityShell.setValue(listOfMntPts); resourceShell.addAll(listOfMntPts); user = new User(); facility = new Facility(); resource = new Resource(); resource.setName("myResource"); resource.setDescription("desc"); resource1 = new Resource(); resource1.setId(1); resource1.setName("myResource"); resource1.setDescription("desc"); resourceList = new ArrayList<Resource>(); resourceList.add(resource1); }</code><technical_language>in Java. camelCase good reason for to</technical_language>

Target:
public void setUp() { classInstance = new urn_perun_user_facility_attribute_def_virt_shell(); session = mock(PerunSessionImpl.class, RETURNS_DEEP_STUBS); preffered = new Attribute(); defDefShell = new Attribute(); facilityShell = new Attribute(); resourceShell = new ArrayList(); listOfMntPts = new ArrayList<String>(); for(int i=0;i<5;i++) listOfMntPts.add("/mnt/bash" + i); preffered.setValue(new ArrayList(listOfMntPts)); listOfMntPts.clear(); listOfMntPts.add("/mnt/bash2"); facilityShell.setValue(listOfMntPts); resourceShell.addAll(listOfMntPts); user = new User(); facility = new Facility(); resource = new Resource(); resource.setName("myResource"); resource.setDescription("desc"); resource1 = new Resource(); resource1.setId(1); resource1.setName("myResource"); resource1.setDescription("desc"); resourceList = new ArrayList<Resource>(); resourceList.add(resource1); }
Source:
<code>protected boolean isDataStall() { Boolean result = null; if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) && (SystemClock.elapsedRealtime() - getLastProbeTime() < mDataStallMinEvaluateTime)) { return false; } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP)) { if (getTcpSocketTracker().getSentSinceLastRecv() > 0) { result = false; } <START> if ((result == null) && <END> getTcpSocketTracker().isDataStallSuspected()) { result = true; } } if ((result == null) && dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { result = true; logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); } } if (VDBG_STALL) { log("isDataStall: result=" + result + ", consecutive dns timeout count=" + mDnsStallDetector.getConsecutiveTimeoutCount() + ", tcp packets received=" + getTcpSocketTracker().getSentSinceLastRecv() + ", tcp fail rate=" + getTcpSocketTracker().getLatestPacketFailRate()); } return (result == null) ? false : result; }</code><technical_language>'else if'</technical_language>

Target:
protected boolean isDataStall() { Boolean result = null; if (!mNetworkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) && (SystemClock.elapsedRealtime() - getLastProbeTime() < mDataStallMinEvaluateTime)) { return false; } if (dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_TCP)) { if (getTcpSocketTracker().getSentSinceLastRecv() > 0) { result = false; } else if (getTcpSocketTracker().isDataStallSuspected()) { result = true; } } if ((result == null) && dataStallEvaluateTypeEnabled(DATA_STALL_EVALUATION_TYPE_DNS)) { if (mDnsStallDetector.isDataStallSuspected(mConsecutiveDnsTimeoutThreshold, mDataStallValidDnsTimeThreshold)) { result = true; logNetworkEvent(NetworkEvent.NETWORK_CONSECUTIVE_DNS_TIMEOUT_FOUND); } } if (VDBG_STALL) { log("isDataStall: result=" + result + ", consecutive dns timeout count=" + mDnsStallDetector.getConsecutiveTimeoutCount() + ", tcp packets received=" + getTcpSocketTracker().getSentSinceLastRecv() + ", tcp fail rate=" + getTcpSocketTracker().getLatestPacketFailRate()); } return (result == null) ? false : result; }
Source:
<code>private void writeGitPatchHeader(StringBuilder sb) { String template = headerFormat.getTemplate(); String[] segments = template.split("\\$\\{"); Stack<String> evaluated = new Stack<String>(); evaluated.add(segments[0]); <START> for (int i = 1; i < segments.length; i++) { <END> String segment = segments[i]; String value = null; int brace = segment.indexOf('}'); if (brace > 0) { String keyword = segment.substring(0, brace); keyword = keyword.toUpperCase().replaceAll(" ", "_"); value = processKeyword(commit, DiffHeaderKeyword.valueOf(keyword)); } String trailingCharacters = segment.substring(brace + 1); if (value != null) { evaluated.add(value); evaluated.add(trailingCharacters); } else if (!evaluated.isEmpty()) { evaluated.add(trailingCharacters); } } StringBuffer buffer = new StringBuffer(); for (String string : evaluated) { buffer.append(string); } sb.append(buffer); }</code><technical_language>is reason foreach loop</technical_language>

Target:
private void writeGitPatchHeader(StringBuilder sb) { String template = headerFormat.getTemplate(); String[] segments = template.split("\\$\\{"); Stack<String> evaluated = new Stack<String>(); evaluated.add(segments[0]); for (int i = 1; i < segments.length; i++) { String segment = segments[i]; String value = null; int brace = segment.indexOf('}'); if (brace > 0) { String keyword = segment.substring(0, brace); keyword = keyword.toUpperCase().replaceAll(" ", "_"); value = processKeyword(commit, DiffHeaderKeyword.valueOf(keyword)); } String trailingCharacters = segment.substring(brace + 1); if (value != null) { evaluated.add(value); evaluated.add(trailingCharacters); } else if (!evaluated.isEmpty()) evaluated.add(trailingCharacters); } StringBuffer buffer = new StringBuffer(); for (String string : evaluated) buffer.append(string); sb.append(buffer); }
Source:
<code>findSourceFields(ImmutableList<FieldRef> references, FieldDescriptor enrichmentField) { int refCount = references.size(); checkArgument(refCount > 0, "References may not be empty"); Set<FieldDescriptor> result = new HashSet<>(refCount); FieldDescriptor.Type basicType = null; Descriptor messageType = null; for (FieldRef ref : references) { <START> boolean strict = refCount == 1; <END> FieldDescriptor field = findSourceField(ref, enrichmentField, strict); if (field == null) { continue; } if (basicType == null) { basicType = field.getType(); if (basicType == MESSAGE) { messageType = field.getMessageType(); } } else { checkState(basicType == field.getType(), differentTypesErrorMessage(enrichmentField)); if (basicType == MESSAGE) { checkState(messageType.equals(field.getMessageType()), differentTypesErrorMessage(enrichmentField)); } } boolean noDuplicateFiled = result.add(field); checkState( noDuplicateFiled, "Enrichment target field names may contain no duplicates. " + "Found duplicate field: %s", ref ); } return result; }</code><technical_language>I guess strict out of for cycle. is modified refCount is a constant</technical_language>

Target:
findSourceFields(ImmutableList<FieldRef> references, FieldDescriptor enrichmentField) { int refCount = references.size(); checkArgument(refCount > 0, "References may not be empty"); Set<FieldDescriptor> result = new HashSet<>(refCount); FieldDescriptor.Type basicType = null; Descriptor messageType = null; boolean strict = refCount == 1; for (FieldRef ref : references) { FieldDescriptor field = findSourceField(ref, enrichmentField, strict); if (field == null) { continue; } if (basicType == null) { basicType = field.getType(); if (basicType == MESSAGE) { messageType = field.getMessageType(); } } else { checkState(basicType == field.getType(), differentTypesErrorMessage(enrichmentField)); if (basicType == MESSAGE) { checkState(messageType.equals(field.getMessageType()), differentTypesErrorMessage(enrichmentField)); } } boolean noDuplicateFiled = result.add(field); checkState( noDuplicateFiled, "Enrichment target field names may contain no duplicates. " + "Found duplicate field: %s", ref ); } return result; }
Source:
<code>public TaskResult runTask() { Config params = request.getConfig() .mergeDefault(request.getConfig().getNestedOrGetEmpty("sh")); String shell = params.get("shell", String.class, "/bin/sh -c"); String command = params.get("_command", String.class); <START> List<String> cmdline = new ArrayList<String>(Arrays.asList(shell.split(" "))); <END> cmdline = cmdline.stream().filter(cmd -> !cmd.isEmpty()).collect(Collectors.toList()); cmdline.add(command); ProcessBuilder pb = new ProcessBuilder(cmdline); final Map<String, String> env = pb.environment(); params.getKeys() .forEach(key -> { if (isValidEnvKey(key)) { JsonNode value = params.get(key, JsonNode.class); String string; if (value.isTextual()) { string = value.textValue(); } else { string = value.toString(); } env.put(key, string); } else { logger.trace("Ignoring invalid env var key: {}", key); } }); String pathEnv = System.getenv("PATH"); if (pathEnv == null) { pathEnv = workspacePath.toAbsolutePath().toString(); } else { pathEnv = pathEnv + File.pathSeparator + workspacePath.toAbsolutePath().toString(); } pb.redirectErrorStream(true); int ecode; try { Process p = exec.start(workspacePath, request, pb); p.getOutputStream().close(); clog.copyStdout(p, System.out); ecode = p.waitFor(); } catch (IOException | InterruptedException ex) { throw Throwables.propagate(ex); } if (ecode != 0) { throw new RuntimeException("Command failed with code " + ecode); } return TaskResult.empty(request); }</code><technical_language>Splitting whitespace a brittle. making shell a list instead</technical_language>

Target:
public TaskResult runTask() { Config params = request.getConfig() .mergeDefault(request.getConfig().getNestedOrGetEmpty("sh")); List<String> shell = params.getListOrEmpty("shell", String.class); String command = params.get("_command", String.class); ImmutableList.Builder<String> cmdline = ImmutableList.builder(); if (shell.isEmpty()) { cmdline.addAll(ImmutableList.of("/bin/sh", "-c")); } else { cmdline.addAll(shell); } cmdline.add(command); ProcessBuilder pb = new ProcessBuilder(cmdline.build()); final Map<String, String> env = pb.environment(); params.getKeys() .forEach(key -> { if (isValidEnvKey(key)) { JsonNode value = params.get(key, JsonNode.class); String string; if (value.isTextual()) { string = value.textValue(); } else { string = value.toString(); } env.put(key, string); } else { logger.trace("Ignoring invalid env var key: {}", key); } }); String pathEnv = System.getenv("PATH"); if (pathEnv == null) { pathEnv = workspacePath.toAbsolutePath().toString(); } else { pathEnv = pathEnv + File.pathSeparator + workspacePath.toAbsolutePath().toString(); } pb.redirectErrorStream(true); int ecode; try { Process p = exec.start(workspacePath, request, pb); p.getOutputStream().close(); clog.copyStdout(p, System.out); ecode = p.waitFor(); } catch (IOException | InterruptedException ex) { throw Throwables.propagate(ex); } if (ecode != 0) { throw new RuntimeException("Command failed with code " + ecode); } return TaskResult.empty(request); }
Source:
<code><START> private boolean operandsAreOnSameLine(BinaryExpressionTree formatStringTree) { <END> return FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.leftOperand()).line() == FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.rightOperand()).line(); }</code><technical_language>![MAJOR](<LINK_0> "operandsAreOnSameLine" a "static" method. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
private static boolean operandsAreOnSameLine(BinaryExpressionTree formatStringTree) { return FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.leftOperand()).line() == FirstSyntaxTokenFinder.firstSyntaxToken(formatStringTree.rightOperand()).line(); }
Source:
<code>public TarArchiveEntry(final Path file) { <START> this(file, file.toString()); <END> }</code><technical_language>happen if file is absolute</technical_language>

Target:
public TarArchiveEntry(final Path file) throws IOException { this(file, file.toString()); }
Source:
<code>public void destroyBlockingChannel(BlockingChannel blockingChannel) { rwlock.readLock().lock(); try { boolean changed = blockingChannelActiveConnections.remove(blockingChannel); if (!changed) { logger.error("Invalid connection being destroyed. " + "Channel does not belong to this queue. queue host port channel host port {}", host, port.getPort(), blockingChannel.getRemoteHost(), blockingChannel.getRemotePort()); throw new IllegalArgumentException("Invalid connection. Channel does not belong to this queue"); } blockingChannel.disconnect(); BlockingChannel channel = getBlockingChannelBasedOnPortType(blockingChannel.getRemoteHost(), blockingChannel.getRemotePort()); channel.connect(); logger.trace("Destroying connection and adding new connection for host port {}", host, port.getPort()); blockingChannelAvailableConnections.add(channel); currentConnectFailuresToCleanUp.set(0); } catch (Exception e) { logger .error("Connection failure to remote host and port when destroying and recreating the connection", host, port.getPort()); synchronized (lock) { numberOfConnections.decrementAndGet(); currentConnectFailuresToCleanUp.incrementAndGet(); if(currentConnectFailuresToCleanUp.get() >= maxConnectFailuresToCleanUp) { while(!blockingChannelAvailableConnections.isEmpty()){ blockingChannelAvailableConnections.poll().disconnect(); } currentConnectFailuresToCleanUp.set(0); <START> } <END> } } finally { rwlock.readLock().unlock(); } }</code><technical_language>if destroying in pool, need set numberOfConnections accordingly</technical_language>

Target:
public void destroyBlockingChannel(BlockingChannel blockingChannel) { rwlock.readLock().lock(); try { boolean changed = blockingChannelActiveConnections.remove(blockingChannel); if (!changed) { logger.error("Invalid connection being destroyed. " + "Channel does not belong to this queue. queue host port channel host port {}", host, port.getPort(), blockingChannel.getRemoteHost(), blockingChannel.getRemotePort()); throw new IllegalArgumentException("Invalid connection. Channel does not belong to this queue"); } blockingChannel.disconnect(); BlockingChannel channel = getBlockingChannelBasedOnPortType(blockingChannel.getRemoteHost(), blockingChannel.getRemotePort()); channel.connect(); logger.trace("Destroying connection and adding new connection for host port {}", host, port.getPort()); blockingChannelAvailableConnections.add(channel); } catch (Exception e) { logger.error("Connection failure to remote host and port when destroying and recreating the connection", host, port.getPort()); synchronized (lock) { numberOfConnections.decrementAndGet(); do { BlockingChannel channel = blockingChannelAvailableConnections.poll(); if (channel == null) { break; } channel.disconnect(); numberOfConnections.decrementAndGet(); } while (true); } } finally { rwlock.readLock().unlock(); } }