auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void canReadSingleTombstoneInSameShard() { int tombstoneShard = putTombstone(writer, TS + 1, DEFAULT_CELL, true); assertThat(reader.getLatestWrites(TS_REF, conservative(tombstoneShard))) <START> .containsExactly(WriteInfo.write(TABLE_REF, DEFAULT_CELL, TS + 1)); <END> }</code><technical_language>This WriteInfo.tombstone</technical_language>

Target:
public void canReadSingleTombstoneInSameShard() { int tombstoneShard = putTombstone(writer, TS + 1, DEFAULT_CELL, TABLE_CONS); List<WriteInfo> latestWrites = reader.getLatestWrites(TS_REF, conservative(tombstoneShard)); assertThat(latestWrites).containsExactly(WriteInfo.tombstone(TABLE_CONS, DEFAULT_CELL, TS + 1)); }
Source:
<code>protected final CompletableFuture<InternalCacheEntry> retrieveFromRemoteSource(Object key, InvocationContext ctx, boolean acquireRemoteLock, FlagAffectedCommand command, boolean isWrite) throws Exception { GlobalTransaction gtx = ctx.isInTxScope() ? ((TxInvocationContext) ctx).getGlobalTransaction() : null; ClusteredGetCommand get = cf.buildClusteredGetCommand(key, command.getFlagsBitSet(), acquireRemoteLock, gtx); get.setWrite(isWrite); RpcOptionsBuilder rpcOptionsBuilder = rpcManager.getRpcOptionsBuilder(ResponseMode.WAIT_FOR_VALID_RESPONSE, DeliverOrder.NONE); <START> int lastTopologyId = -1; <END> return handleRemoteValue(key, null, get, rpcOptionsBuilder, lastTopologyId); }</code><technical_language>removed</technical_language>

Target:
protected final CompletableFuture<InternalCacheEntry> retrieveFromRemoteSource(Object key, InvocationContext ctx, boolean acquireRemoteLock, FlagAffectedCommand command, boolean isWrite) throws Exception { GlobalTransaction gtx = ctx.isInTxScope() ? ((TxInvocationContext) ctx).getGlobalTransaction() : null; ClusteredGetCommand get = cf.buildClusteredGetCommand(key, command.getFlagsBitSet(), acquireRemoteLock, gtx); get.setWrite(isWrite); RpcOptionsBuilder rpcOptionsBuilder = rpcManager.getRpcOptionsBuilder(ResponseMode.WAIT_FOR_VALID_RESPONSE, DeliverOrder.NONE); return handleRemoteValue(key, null, get, rpcOptionsBuilder, -1); }
Source:
<code>public static Archive<?> createTestArchive() { File file = new File(testFilePath); Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists()); WebArchive war = TestUtil.prepareArchive(CustomExceptionMapperTest.class.getSimpleName()) .addClasses(CustomExceptionMapperResource.class) .addClasses(CustomExceptionMapperClassConstraint.class, CustomExceptionMapperClassValidator.class, CustomExceptionMapperReport.class) .addAsLibrary(file, "validation-versioning.jar") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( <START> new RuntimePermission("getClassLoader"), <END> new RuntimePermission("accessDeclaredMembers") ), "permissions.xml"); return war; }</code><technical_language>new RuntimePermission("accessDeclaredMembers") is required test pass, getClassloader permission is required. stacktrace of AccessControll exception (attached in <LINK_0> shows problem is in class: org.jboss.resteasy.plugins.validation.ConstraintTypeUtil11.getMethod(ConstraintTypeUtil11.java:95). is in this case give 'accessDeclaredMembers' permission application, instead of creating AccessController.doPrivileged() block in resteasy code? For example application calls some code reguires permission directly: Thread.currentThread().getContextClassLoader(), is obvious granted permission directly. If getContextClassLoader() is called in resteasy classes handled in resteasy code</technical_language>

Target:
public static Archive<?> createTestArchive() { File file = new File(testFilePath); Assert.assertTrue("File " + testFilePath + " doesn't exists", file.exists()); WebArchive war = TestUtil.prepareArchive(CustomExceptionMapperTest.class.getSimpleName()) .addClasses(CustomExceptionMapperResource.class) .addClasses(CustomExceptionMapperClassConstraint.class, CustomExceptionMapperClassValidator.class, CustomExceptionMapperReport.class) .addAsLibrary(file, "validation-versioning.jar") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); return war; }
Source:
<code>private void createConglomerate(ExecRow templateRow) throws StandardException{ if (!conglomCreated) { TransactionController tc = activation.getTransactionController(); CID = tc.createConglomerate(false, "heap", templateRow.getRowArray(), null, null, properties, TransactionController.IS_TEMPORARY | <START> TransactionController.IS_KEPT, 0); <END> LOG.trace(format("Created temporary conglomerate splice:%d", CID)); conglomCreated = true; cc = tc.openConglomerate(CID, false, TransactionController.OPENMODE_FORUPDATE, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE); } }</code><technical_language>constant</technical_language>

Target:
private void createConglomerate(ExecRow templateRow) throws StandardException{ if (!conglomCreated) { TransactionController tc = activation.getTransactionController(); CID = tc.createConglomerate(false, "heap", templateRow.getRowArray(), null, null, properties, TransactionController.IS_TEMPORARY | TransactionController.IS_KEPT, Conglomerate.Priority.NORMAL); LOG.trace(format("Created temporary conglomerate splice:%d", CID)); conglomCreated = true; cc = tc.openConglomerate(CID, false, TransactionController.OPENMODE_FORUPDATE, TransactionController.MODE_TABLE, TransactionController.ISOLATION_SERIALIZABLE); } }
Source:
<code><START> static String clean(String msg) { <END> return msg. replaceAll("(^|\\n)Signed-off-by:.*(\\n|$)", "$1"). replaceAll("(^|\\n)#.*(\\n|$)", "$1"). replaceAll("\\n+", "\\\n"). replaceAll("\\n*$", ""); }</code><technical_language>Clean necessary in JGit. required in C hook script presented *original* buffer user, cleaned commit creation routine. need drop lines leading #, etc. JGit happen in higher level UI UI invokes ChangeIdUtil class. (Or simply need happen all.)</technical_language>

Target:
static String clean(String msg) { return msg. replaceAll("(^|\\n)Signed-off-by:.*(\\n|$)", "$1"). replaceAll("(^|\\n)#.*(\\n|$)", "$1"). replaceAll("\\n\\n+", "\\\n"). replaceAll("\\n*$", ""); }
Source:
<code>public void close() throws JMSException { if (transactionHelper.isTransactionAvailable()) { <START> transactionHelper.delistResource(xaSession.getXAResource()); <END> if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Delisted " + xaSession + " XA resource from the transaction"); } Synchronization synchronization = new SessionClosingSynchronization(xaSession); transactionHelper.registerSynchronization(synchronization); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Registered synchronization to close the session: " + synchronization); } } else { xaSession.close(); } }</code><technical_language>this return false</technical_language>

Target:
public void close() throws JMSException { if (transactionHelper.isTransactionAvailable()) { transactionHelper.deregisterXAResource(xaSession.getXAResource()); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Delisted " + xaSession + " XA resource from the transaction"); } Synchronization synchronization = new SessionClosingSynchronization(xaSession); transactionHelper.registerSynchronization(synchronization); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Registered synchronization to close the session: " + synchronization); } } else { xaSession.close(); } }
Source:
<code>public void removeChildrenAndResources(Session session) { removeChildrenFromMap(session, triggers); removeChildrenFromMap(session, constraints); boolean modified = true; while (!tablesAndViews.isEmpty()) { boolean newModified = false; for (Table obj : tablesAndViews.values()) { Table dependentTable = database.getDependentTable(obj, obj); if (dependentTable == null) { database.removeSchemaObject(session, obj); newModified = true; } else if (dependentTable.getSchema() != this) { throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(false), dependentTable.getSQL(false)); } else if (!modified) { dependentTable.removeColumnExpressionsDependencies(session); dependentTable.setModified(); <START> database.updateMeta(session, dependentTable); <END> } } modified = newModified; } removeChildrenFromMap(session, indexes); removeChildrenFromMap(session, sequences); removeChildrenFromMap(session, constants); removeChildrenFromMap(session, functions); for (Right right : database.getAllRights()) { if (right.getGrantedObject() == this) { database.removeDatabaseObject(session, right); } } database.removeMeta(session, getId()); owner = null; invalidate(); }</code><technical_language>this modified/newModified stuff is confusing - is here</technical_language>

Target:
public void removeChildrenAndResources(Session session) { removeChildrenFromMap(session, triggers); removeChildrenFromMap(session, constraints); boolean modified = true; while (!tablesAndViews.isEmpty()) { boolean newModified = false; for (Table obj : tablesAndViews.values()) { if (obj.getName() != null) { Table dependentTable = database.getDependentTable(obj, obj); if (dependentTable == null) { database.removeSchemaObject(session, obj); newModified = true; } else if (dependentTable.getSchema() != this) { throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(false), dependentTable.getSQL(false)); } else if (!modified) { dependentTable.removeColumnExpressionsDependencies(session); dependentTable.setModified(); database.updateMeta(session, dependentTable); } } } modified = newModified; } removeChildrenFromMap(session, indexes); removeChildrenFromMap(session, sequences); removeChildrenFromMap(session, constants); removeChildrenFromMap(session, functions); for (Right right : database.getAllRights()) { if (right.getGrantedObject() == this) { database.removeDatabaseObject(session, right); } } database.removeMeta(session, getId()); owner = null; invalidate(); }
Source:
<code>public void onClose(Session session, int status, String reason) { <START> connectedSockets.get(connectedUser.getId()).remove(this); <END> }</code><technical_language>want consider removing connected user connectedSockets map altogether, but, in worst case, get tens of thousands of entries current release cycle length number of unique users</technical_language>

Target:
public void onClose(Session session, int status, String reason) { connectedSockets.get(connectedUser.getId()).remove(this); connectedSockets.remove(connectedUser.getId(), Lists.newArrayList()); }
Source:
<code>public ReadOnlyStorageConfiguration(VoldemortConfig config) { this.storageDir = new File(config.getReadOnlyDataStorageDirectory()); this.numBackups = config.getNumReadOnlyVersions(); this.searcher = (SearchStrategy) ReflectUtils.callConstructor(ReflectUtils.loadClass(config.getReadOnlySearchStrategy() .trim())); this.nodeId = config.getNodeId(); this.deleteBackupMs = config.getReadOnlyDeleteBackupMs(); this.maxValueBufferAllocationSize = config.getReadOnlyMaxValueBufferAllocationSize(); FailedFetchLock failedFetchLockInstance; if (config.getHighAvailabilityStateAutoCleanUp()) { try { <START> failedFetchLockInstance = FailedFetchLock.getLock(config, null); <END> } catch (ClassNotFoundException e) { failedFetchLockInstance = null; } } else { failedFetchLockInstance = null; } this.failedFetchLock = failedFetchLockInstance; }</code><technical_language>HdfsFailedFetchLock initializes HadoopFileSystem constructor. HadoopFileSystem opened constructor is prone connection resets failures. this force store open handle HdfsFileSystem more issues</technical_language>

Target:
public ReadOnlyStorageConfiguration(VoldemortConfig config) { this.config = config; this.storageDir = new File(config.getReadOnlyDataStorageDirectory()); this.numBackups = config.getNumReadOnlyVersions(); this.searcher = (SearchStrategy) ReflectUtils.callConstructor(ReflectUtils.loadClass(config.getReadOnlySearchStrategy() .trim())); this.nodeId = config.getNodeId(); this.deleteBackupMs = config.getReadOnlyDeleteBackupMs(); this.maxValueBufferAllocationSize = config.getReadOnlyMaxValueBufferAllocationSize(); }
Source:
<code>public void shouldUpdateEmailCollectionMode() { Long gatewayAccountId = 100L; PatchRequest request = PatchRequest.from(new ObjectMapper().valueToTree(ImmutableMap.of("op", "replace", "path", "email_collection_mode", "value", "off"))); GatewayAccountEntity entity = mock(GatewayAccountEntity.class); when(gatewayAccountDao.findById(gatewayAccountId)).thenReturn(Optional.of(entity)); Optional<GatewayAccount> optionalGatewayAcc = updater.doPatch(gatewayAccountId, request); assertThat(optionalGatewayAcc.isPresent(), is(true)); <START> verify(entity, times(1)).setEmailCollectionMode(EmailCollectionMode.OFF); <END> verify(gatewayAccountDao, times(1)).merge(entity); }</code><technical_language>need times(1) (it's default)</technical_language>

Target:
public void shouldUpdateEmailCollectionMode() { Long gatewayAccountId = 100L; PatchRequest request = PatchRequest.from(new ObjectMapper().valueToTree(ImmutableMap.of("op", "replace", "path", "email_collection_mode", "value", "off"))); GatewayAccountEntity entity = mock(GatewayAccountEntity.class); when(gatewayAccountDao.findById(gatewayAccountId)).thenReturn(Optional.of(entity)); Optional<GatewayAccount> optionalGatewayAcc = updater.doPatch(gatewayAccountId, request); assertThat(optionalGatewayAcc.isPresent(), is(true)); InOrder inOrder = Mockito.inOrder(entity, gatewayAccountDao); inOrder.verify(entity).setEmailCollectionMode(EmailCollectionMode.OFF); inOrder.verify(gatewayAccountDao).merge(entity); }
Source:
<code><START> @Test public void testIntersectToIntersect1() { <END> final String mv = "" + "select \"deptno\" from\n" + "\"emps\" intersect all select \"deptno\" from \"depts\""; final String query = "" + "select \"deptno\" from\n" + "\"depts\" intersect all select \"deptno\" from \"emps\""; checkMaterialize(mv, query, true); }</code><technical_language>format below: select deptno emps intersect select deptno depts;</technical_language>

Target:
@Test public void testIntersectToIntersect1() { final String mv = "" + "select \"deptno\" from \"emps\"\n" + "intersect all\n" + "select \"deptno\" from \"depts\""; final String query = "" + "select \"deptno\" from \"depts\"\n" + "intersect all\n" + "select \"deptno\" from \"emps\""; checkMaterialize(mv, query, true); }
Source:
<code><START> public static Map<Integer, Map<Version, Boolean>> getBalloonSupportMap() { <END> return balloonSupportMap; }</code><technical_language>need this getter public</technical_language>

Target:
private static Map<Integer, Map<Version, Boolean>> getBalloonSupportMap() { return balloonSupportMap; }
Source:
<code>private RevisionInfo toRevisionInfo(ChangeData cd, PatchSet in) throws OrmException { RevisionInfo out = new RevisionInfo(); out.isCurrent = in.getId().equals(cd.change(db).currentPatchSetId()); out._number = in.getId().get(); out.draft = in.isDraft() ? true : null; <START> out.edit = in.getId().isEdit() ? true : null; <END> out.fetch = makeFetchMap(cd, in); if (has(ALL_COMMITS) || (out.isCurrent && has(CURRENT_COMMIT))) { try { out.commit = toCommit(in); } catch (PatchSetInfoNotAvailableException e) { log.warn("Cannot load PatchSetInfo " + in.getId(), e); } } if (has(ALL_FILES) || (out.isCurrent && has(CURRENT_FILES))) { try { out.files = fileInfoJson.toFileInfoMap(cd.change(db), in); out.files.remove(Patch.COMMIT_MSG); } catch (PatchListNotAvailableException e) { log.warn("Cannot load PatchList " + in.getId(), e); } } if ((out.isCurrent || (out.draft != null && out.draft) || (out.edit != null && out.edit)) && has(CURRENT_ACTIONS) && userProvider.get().isIdentifiedUser()) { out.actions = Maps.newTreeMap(); for (UiAction.Description d : UiActions.from( revisions, new RevisionResource(changes.parse(control(cd)), in), userProvider)) { out.actions.put(d.getId(), new ActionInfo(d)); } } if (has(DRAFT_COMMENTS) && userProvider.get().isIdentifiedUser()) { IdentifiedUser user = (IdentifiedUser)userProvider.get(); out.hasDraftComments = db.get().patchComments() .draftByPatchSetAuthor(in.getId(), user.getAccountId()) .iterator().hasNext() ? true : null; } return out; }</code><technical_language>This set in caller relying PatchSet.Id edit property</technical_language>

Target:
private RevisionInfo toRevisionInfo(ChangeData cd, PatchSet in) throws OrmException { RevisionInfo out = new RevisionInfo(); out.isCurrent = in.getId().equals(cd.change().currentPatchSetId()); out._number = in.getId().get(); out.draft = in.isDraft() ? true : null; out.edit = in.getId().isEdit() ? true : null; out.fetch = makeFetchMap(cd, in); if (has(ALL_COMMITS) || (out.isCurrent && has(CURRENT_COMMIT))) { try { out.commit = toCommit(in); } catch (PatchSetInfoNotAvailableException e) { log.warn("Cannot load PatchSetInfo " + in.getId(), e); } } if (has(ALL_FILES) || (out.isCurrent && has(CURRENT_FILES))) { try { out.files = fileInfoJson.toFileInfoMap(cd.change(), in); out.files.remove(Patch.COMMIT_MSG); } catch (PatchListNotAvailableException e) { log.warn("Cannot load PatchList " + in.getId(), e); } } if ((out.isCurrent || (out.draft != null && out.draft) || (out.edit != null && out.edit)) && has(CURRENT_ACTIONS) && userProvider.get().isIdentifiedUser()) { out.actions = Maps.newTreeMap(); for (UiAction.Description d : UiActions.from( revisions, new RevisionResource(changes.parse(control(cd)), in), userProvider)) { out.actions.put(d.getId(), new ActionInfo(d)); } } if (has(DRAFT_COMMENTS) && userProvider.get().isIdentifiedUser()) { IdentifiedUser user = (IdentifiedUser)userProvider.get(); out.hasDraftComments = db.get().patchComments() .draftByPatchSetAuthor(in.getId(), user.getAccountId()) .iterator().hasNext() ? true : null; } return out; }
Source:
<code>public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, <START> new OsgiClassLoader(), <END> Util.class.getClassLoader(), ClassLoader.getSystemClassLoader() }; }</code><technical_language>I I singleton approach best. ctor get called continously leaves methods static</technical_language>

Target:
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) { return new ClassLoader[] { appClassLoader, OsgiClassLoader.getInstance(), Util.class.getClassLoader(), ClassLoader.getSystemClassLoader() }; }
Source:
<code>public List<CubeFactTable> getAllFactTables(CubeInterface cube) throws HiveException { if (cube instanceof Cube) { List<CubeFactTable> cubeFacts = new ArrayList<CubeFactTable>(); try { for (CubeFactTable fact : getAllFacts()) { <START> if (fact.getCubeName().equalsIgnoreCase(((Cube)cube).getName().toLowerCase())) { <END> cubeFacts.add(fact); } } } catch (HiveException e) { throw new HiveException("Could not get all tables", e); } return cubeFacts; } else { return getAllFactTables(((DerivedCube)cube).getParent()); } }</code><technical_language>do need lowercase fact.getCubeName()</technical_language>

Target:
public List<CubeFactTable> getAllFactTables(CubeInterface cube) throws HiveException { if (cube instanceof Cube) { List<CubeFactTable> cubeFacts = new ArrayList<CubeFactTable>(); try { for (CubeFactTable fact : getAllFacts()) { if (fact.getCubeName().equalsIgnoreCase(((Cube)cube).getName())) { cubeFacts.add(fact); } } } catch (HiveException e) { throw new HiveException("Could not get all fact tables of " + cube, e); } return cubeFacts; } else { return getAllFactTables(((DerivedCube)cube).getParent()); } }
Source:
<code>public void init(ServletConfig config) throws ServletException { super.init(config); <START> EngineLocalConfig config = EngineLocalConfig.getInstance(); <END> pkiResources = new HashMap<String, Details>(); pkiResources.put("ca-certificate", new Details(config.getPKICACert(), "X509-PEM-CA")); pkiResources.put("engine-certificate", new Details(config.getPKIEngineCert(), "X509-PEM", "ovirt-engine")); }</code><technical_language>a variable called config (the parameter). This code compile</technical_language>

Target:
public void init(ServletConfig config) throws ServletException { super.init(config); EngineLocalConfig localconfig = EngineLocalConfig.getInstance(); pkiResources = new HashMap<String, Details>(); pkiResources.put("ca-certificate", new Details(localconfig.getPKICACert(), "X509-PEM-CA")); pkiResources.put("engine-certificate", new Details(localconfig.getPKIEngineCert(), "X509-PEM", "ovirt-engine")); }
Source:
<code>public void setTypePrecedence(TypePrecedence typePrecedence) { <START> this.typePrecedence = typePrecedence; <END> }</code><technical_language>Assert.notNull(typePrecedence, "'typePrecedence' null."); NPE for equals operation in toJavaType()</technical_language>

Target:
public void setTypePrecedence(TypePrecedence typePrecedence) { Assert.notNull(typePrecedence, "'typePrecedence' cannot be null"); this.typePrecedence = typePrecedence; }
Source:
<code>public void onAllRequiredCapabilitiesAvailable() { try { DeploymentConfiguration deploymentConfiguration = DataHolder.getInstance().getConfigProvider() <START> .getConfigurationObject(DeploymentConfiguration.class); <END> logger.debug("Starting Carbon Deployment Engine"); deploymentEngine.start(deploymentConfiguration.getRepositoryLocation()); OSGiServiceHolder.getInstance().setCarbonDeploymentEngine(deploymentEngine); DeploymentService deploymentService = new CarbonDeploymentService(deploymentEngine); BundleContext bundleContext = DataHolder.getInstance().getBundleContext(); serviceRegistration = bundleContext.registerService(DeploymentService.class.getName(), deploymentService, null); logger.debug("Carbon Deployment Engine is successfully started"); } catch (DeploymentEngineException e) { String msg = "Could not initialize carbon deployment engine"; logger.error(msg, e); } catch (CarbonConfigurationException e) { String msg = "Fail to load deployment configuration"; logger.error(msg, e); } }</code><technical_language>reuse this deploymentConfiguration object component. in other places need read configuration</technical_language>

Target:
public void onAllRequiredCapabilitiesAvailable() { try { DeploymentConfiguration deploymentConfiguration = DataHolder.getInstance().getConfigProvider() .getConfigurationObject(DeploymentConfiguration.class); DataHolder.getInstance().setDeploymentConfiguration(deploymentConfiguration); logger.debug("Starting Carbon Deployment Engine"); deploymentEngine.start(deploymentConfiguration.getRepositoryLocation()); OSGiServiceHolder.getInstance().setCarbonDeploymentEngine(deploymentEngine); DeploymentService deploymentService = new CarbonDeploymentService(deploymentEngine); BundleContext bundleContext = DataHolder.getInstance().getBundleContext(); serviceRegistration = bundleContext.registerService(DeploymentService.class.getName(), deploymentService, null); logger.debug("Carbon Deployment Engine is successfully started"); } catch (DeploymentEngineException e) { String msg = "Could not initialize carbon deployment engine"; logger.error(msg, e); } catch (CarbonConfigurationException e) { String msg = "Fail to load deployment configuration"; logger.error(msg, e); } }
Source:
<code>public static File findSecrets(File xmlFile) throws SAXException, IOException, TransformerException { XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) { private String tagName = ""; @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { tagName = qName; super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { tagName = ""; super.endElement(uri, localName, qName); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (!"".equals(tagName)) { String value = new String(ch, start, length).trim(); if (!"".equals(value)) { if ((Secret.decrypt(value)) != null || SecretBytes.isSecretBytes(value)) { ch = SECRET_MARKER.toCharArray(); start = 0; length = ch.length; } } } super.characters(ch, start, length); } }; Source src = new SAXSource(xr, new InputSource(new StringReader(FileUtils.readFileToString(xmlFile)))); <START> File patchedFile = File.createTempFile("patched", ".xml"); <END> Result res = new StreamResult(new FileOutputStream(patchedFile)); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(src, res); return patchedFile; }</code><technical_language>I doubt setups configure java tmp directory private, calling out in JIRA. files created default umask - attempt patch - leak secrets world readable. (but hey big win for windows Linux here!) a :bug: restricting global read access</technical_language>

Target:
public static String findSecrets(File xmlFile) throws SAXException, IOException, TransformerException { XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) { private String tagName = ""; @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { tagName = qName; super.startElement(uri, localName, qName, atts); } public void endElement(String uri, String localName, String qName) throws SAXException { tagName = ""; super.endElement(uri, localName, qName); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (!"".equals(tagName)) { String value = new String(ch, start, length).trim(); if (!"".equals(value)) { if ((Secret.decrypt(value)) != null || SecretBytes.isSecretBytes(value)) { ch = SECRET_MARKER.toCharArray(); start = 0; length = ch.length; } } } super.characters(ch, start, length); } }; Source src = new SAXSource(xr, new InputSource(new StringReader(FileUtils.readFileToString(xmlFile)))); final ByteArrayOutputStream result = new ByteArrayOutputStream(); Result res = new StreamResult(result); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, OUTPUT_ENCODING); transformer.transform(src, res); return result.toString("UTF-8"); }
Source:
<code>public void visitNode(Tree tree) { CompilationUnitTree cut = (CompilationUnitTree) tree; List<ImportClauseTree> staticImports = cut.imports().stream() <START> .filter(importClauseTree -> importClauseTree.is(Tree.Kind.IMPORT) && ((ImportTree) importClauseTree).isStatic()) <END> .collect(Collectors.toList()); if (staticImports.size() > threshold) { reportIssue(staticImports.get(threshold), String.format("Reduce the number of \"static\" imports in this class from %d to the maximum allowed %d.", staticImports.size(), threshold)); } }</code><technical_language>case of import clause is empty statement is covered testcases</technical_language>

Target:
public void visitNode(Tree tree) { CompilationUnitTree cut = (CompilationUnitTree) tree; List<ImportClauseTree> staticImports = cut.imports().stream() .filter(importClauseTree -> importClauseTree.is(Tree.Kind.IMPORT) && ((ImportTree) importClauseTree).isStatic()) .collect(Collectors.toList()); int staticImportsCount = staticImports.size(); if (staticImportsCount > threshold) { List<JavaFileScannerContext.Location> flow = staticImports.stream() .map(importStatement -> new JavaFileScannerContext.Location("+1", importStatement)) .collect(Collectors.toList()); String message = String.format("Reduce the number of \"static\" imports in this class from %d to the maximum allowed %d.", staticImportsCount, threshold); reportIssue(staticImports.get(0), message, flow, null); } }
Source:
<code>Trip mapServiceJourney(ServiceJourney serviceJourney){ org.opentripplanner.model.Route route = resolveRoute(serviceJourney); String serviceId = resolveServiceId(serviceJourney); if(serviceId == null || route == null) { return null; } Trip trip = new Trip(); trip.setId(idFactory.createId(serviceJourney.getId())); trip.setRoute(route); trip.setServiceId(idFactory.createId(serviceId)); trip.setShapeId(getShapeId(serviceJourney)); if (serviceJourney.getPrivateCode() != null) { trip.setInternalPlanningCode(serviceJourney.getPrivateCode().getValue()); } <START> if (serviceJourney.getPublicCode() != null) { trip.setTripShortName(serviceJourney.getPublicCode()); } <END> return trip; }</code><technical_language>need wrap this a if</technical_language>

Target:
Trip mapServiceJourney(ServiceJourney serviceJourney){ org.opentripplanner.model.Route route = resolveRoute(serviceJourney); String serviceId = resolveServiceId(serviceJourney); if(serviceId == null || route == null) { return null; } Trip trip = new Trip(); trip.setId(idFactory.createId(serviceJourney.getId())); trip.setRoute(route); trip.setServiceId(idFactory.createId(serviceId)); trip.setShapeId(getShapeId(serviceJourney)); if (serviceJourney.getPrivateCode() != null) { trip.setInternalPlanningCode(serviceJourney.getPrivateCode().getValue()); } trip.setTripShortName(serviceJourney.getPublicCode()); return trip; }
Source:
<code>public void start() { l1Lifespan = config.clustering().l1().lifespan(); <START> replicationTimeout = config.clustering().sync().replTimeout(); <END> }</code><technical_language>remoteTimeout() is correct one</technical_language>

Target:
public void start() { l1Lifespan = config.clustering().l1().lifespan(); replicationTimeout = config.clustering().remoteTimeout(); }
Source:
<code>private CompressionCodec byName(String name) { <START> Assert.hasText("'name' must not be empty"); <END> CompressionCodec codec = codecs.get(name.toUpperCase()); if (codec == null) { throw new CompressionException(String.format(MISSING_COMPRESSION_MESSAGE, name)); } return codec; }</code><technical_language>invalid assertion - passing in name argument</technical_language>

Target:
private CompressionCodec byName(String name) { Assert.hasText(name, "'name' must not be empty"); CompressionCodec codec = codecs.get(name.toUpperCase()); if (codec == null) { throw new CompressionException(String.format(MISSING_COMPRESSION_MESSAGE, name)); } return codec; }
Source:
<code>public String getDefaultAuthenticator(String idpName) throws IdentityApplicationManagementException { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); try { IdentityProvider idp = idpManager.getIdPByName(idpName, CarbonContext .getThreadLocalCarbonContext().getTenantDomain()); return idp.getDefaultAuthenticatorConfig() != null ? idp .getDefaultAuthenticatorConfig().getName() : null; } catch (IdentityProviderManagementException e) { <START> throw new IdentityApplicationManagementException(e.getMessage(), e); <END> } }</code><technical_language>e.getMessage(). Instead a contextual message</technical_language>

Target:
public String getDefaultAuthenticator(String idpName) throws IdentityApplicationManagementException { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); try { IdentityProvider idp = idpManager.getIdPByName(idpName, CarbonContext .getThreadLocalCarbonContext().getTenantDomain()); return idp.getDefaultAuthenticatorConfig() != null ? idp .getDefaultAuthenticatorConfig().getName() : null; } catch (IdentityProviderManagementException e) { throw new IdentityApplicationManagementException("Error when retrieving default authenticator of idp " + idpName, e); } }
Source:
<code>public void testDeduperStreamCodec() { try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); lma.prepareDAG(new TestDedupApp(), conf); LocalMode.Controller lc = lma.getController(); <START> lc.run(10 * 1000); END> } catch (Exception e) { e.printStackTrace(); Assert.fail("constraint violations: " + e); } Assert.assertFalse(testFailed); }</code><technical_language>run test in async mode of Controller method similar to: com.datatorrent.lib.io.fs.FileSplitterBaseTest.testSplitterInApp This a deterministic of verification cases</technical_language>

Target:
public void testDeduperStreamCodec() throws Exception { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); TestDedupApp app = new TestDedupApp(); lma.prepareDAG(app, conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); app.dedup.latch.await(); Assert.assertFalse(testFailed); }
Source:
<code>private void resyncCustomToTag() { if (!this.manipulators.isEmpty()) { final NBTTagList newList = new NBTTagList(); final List<DataView> manipulatorViews = DataUtil.getSerializedManipulatorList(this.bridge$getCustomManipulators()); for (DataView dataView : manipulatorViews) { newList.appendTag(NbtTranslator.getInstance().translateData(dataView)); } final NBTTagCompound spongeCompound = shadow$getOrCreateSubCompound(Constants.Sponge.SPONGE_DATA); spongeCompound.setTag(Constants.Sponge.CUSTOM_MANIPULATOR_TAG_LIST, newList); } else if (!this.failedData.isEmpty()) { final NBTTagList newList = new NBTTagList(); for (DataView failedDatum : this.failedData) { newList.appendTag(NbtTranslator.getInstance().translateData(failedDatum)); } final NBTTagCompound spongeCompound = shadow$getOrCreateSubCompound(Constants.Sponge.SPONGE_DATA); spongeCompound.setTag(Constants.Sponge.FAILED_CUSTOM_DATA, newList); } else { <START> if (shadow$hasTagCompound()) { <END> this.shadow$getTagCompound().removeTag(Constants.Sponge.SPONGE_DATA); if (this.shadow$getTagCompound().isEmpty()) { this.shadow$setTagCompound(null); } } } }</code><technical_language>suggestion if (this.shadow$hasTagCompound()) {</technical_language>

Target:
private void resyncCustomToTag() { if (!this.manipulators.isEmpty()) { final NBTTagList newList = new NBTTagList(); final List<DataView> manipulatorViews = DataUtil.getSerializedManipulatorList(this.bridge$getCustomManipulators()); for (DataView dataView : manipulatorViews) { newList.appendTag(NbtTranslator.getInstance().translateData(dataView)); } final NBTTagCompound spongeCompound = this.shadow$getOrCreateSubCompound(Constants.Sponge.SPONGE_DATA); spongeCompound.setTag(Constants.Sponge.CUSTOM_MANIPULATOR_TAG_LIST, newList); } else if (!this.failedData.isEmpty()) { final NBTTagList newList = new NBTTagList(); for (DataView failedDatum : this.failedData) { newList.appendTag(NbtTranslator.getInstance().translateData(failedDatum)); } final NBTTagCompound spongeCompound = this.shadow$getOrCreateSubCompound(Constants.Sponge.SPONGE_DATA); spongeCompound.setTag(Constants.Sponge.FAILED_CUSTOM_DATA, newList); } else { if (this.shadow$hasTagCompound()) { this.shadow$getTagCompound().removeTag(Constants.Sponge.SPONGE_DATA); if (this.shadow$getTagCompound().isEmpty()) { this.shadow$setTagCompound(null); } } } }
Source:
<code>private SSLContext getSslContext() { if (!isSslConfigured()) { throw new IllegalArgumentException("KeyStore and TrustStore system properties must be set."); } KeyStore trustStore = getKeyStore(getProperty(TRUST_STORE), getProperty(TRUST_STORE_PASS)); KeyStore keyStore = getKeyStore(getProperty(KEY_STORE), getProperty(KEY_STORE_PASS)); SSLContext sslContext; try { sslContext = SSLContexts.custom() <START> .loadKeyMaterial(keyStore, getProperty(KEY_STORE_PASS).toCharArray()) <END> .loadTrustMaterial(trustStore) .useTLS() .build(); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalArgumentException( "Unable to use javax.net.ssl.keyStorePassword to load key material to create SSL context for Solr client."); } sslContext.getDefaultSSLParameters().setWantClientAuth(true); return sslContext; }</code><technical_language>Potential NullPointerException if property is defined</technical_language>

Target:
private SSLContext getSslContext() { if (!protectedSolrSettings.isSslConfigured()) { throw new IllegalArgumentException("KeyStore and TrustStore system properties must be set."); } KeyStore trustStore = getKeyStore( protectedSolrSettings.getTrustStore(), protectedSolrSettings.getTrustStorePass()); KeyStore keyStore = getKeyStore(protectedSolrSettings.getKeyStore(), protectedSolrSettings.getKeyStorePass()); SSLContext sslContext; try { sslContext = SSLContexts.custom() .loadKeyMaterial(keyStore, protectedSolrSettings.getKeyStorePass().toCharArray()) .loadTrustMaterial(trustStore) .useTLS() .build(); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new IllegalArgumentException( "Unable to use javax.net.ssl.keyStorePassword to load key material to create SSL context for Solr client."); } sslContext.getDefaultSSLParameters().setWantClientAuth(true); return sslContext; }
Source:
<code>public boolean onMapClick(@NonNull LatLng point) { <START> Style style = mapboxMap.getStyle(); <END> if (style != null) { makeElevationRequestToTilequeryApi(style, point); } return true; }</code><technical_language>async callback for getStyle()</technical_language>

Target:
public boolean onMapClick(@NonNull LatLng point) { mapboxMap.getStyle(new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { makeElevationRequestToTilequeryApi(style, point); } }); return true; }
Source:
<code>public void run() { FutureTask[] callbackArray = new FutureTask[_callbacksList.size()]; AtomicReferenceArray<FutureTask> _bufferList = new AtomicReferenceArray<FutureTask>(_callbacksList.toArray(callbackArray)); <START> ExecutorService executor = Executors.newFixedThreadPool(10); <END> try { for (int i = 0; i < _bufferList.length(); i++) { Thread.sleep(_sleepTime); FutureTask f = _bufferList.get(i); if (!f.isDone()) { executor.submit(f).get(); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException ee) { ee.printStackTrace(); } }</code><technical_language>this shared (passed in) instead of call? shut this somewhere</technical_language>

Target:
public void run() { FutureTask[] callbackArray = new FutureTask[_callbacksList.size()]; AtomicReferenceArray<FutureTask> _bufferList = new AtomicReferenceArray<FutureTask>(_callbacksList.toArray(callbackArray)); ExecutorService executor = Executors.newFixedThreadPool(10); try { for (int i = 0; i < _bufferList.length(); i++) { Thread.sleep(_sleepTime); FutureTask f = _bufferList.get(i); if (!f.isDone()) { executor.submit(f).get(); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException ee) { ee.printStackTrace(); } finally { executor.shutdownNow(); } }
Source:
<code>public Connection connection(@Nullable String schema) { if (schema != null && !F.eq(this.schema, schema)) { try { <START> if(schema != null && schema.trim().isEmpty()){ <END> throw new IgniteSQLException("Failed to set schema for DB connection. " + "Schema name could not be an empty string"); } conn.setSchema(schema); this.schema = schema; } catch (SQLException e) { throw new IgniteSQLException("Failed to set schema for DB connection for thread [schema=" + schema + "]", e); } } return conn; }</code><technical_language>schema is null</technical_language>

Target:
public Connection connection(@Nullable String schema) { if (schema != null && !F.eq(this.schema, schema)) { try { if(schema.trim().isEmpty()){ throw new IgniteSQLException("Failed to set schema for DB connection. " + "Schema name could not be an empty string"); } conn.setSchema(schema); this.schema = schema; } catch (SQLException e) { throw new IgniteSQLException("Failed to set schema for DB connection for thread [schema=" + schema + "]", e); } } return conn; }
Source:
<code>boolean generateHtmlFile(List<File> xmlFiles, File htmlFile) { return LicenseHtmlGeneratorFromXml.generateHtml(xmlFiles, htmlFile, <START> mContext.getResources().getString(R.string.notice_header)); <END> }</code><technical_language>nit: mContext.getString()</technical_language>

Target:
boolean generateHtmlFile(List<File> xmlFiles, File htmlFile) { return LicenseHtmlGeneratorFromXml.generateHtml(xmlFiles, htmlFile, mContext.getString(R.string.notice_header)); }
Source:
<code>public InputStream getObjectInputStream(RepoObject repoObject) throws RepoException { InputStream content = null; try { content = objectStore.getInputStream(repoObject); } catch (Exception e) { <START> log.error("Error retrieving content for object. Key: " + repoObject.getKey() + " , bucketName: " <END> + repoObject.getBucketName() + " , versionChecksum: " + repoObject.getVersionChecksum() + " . Error: " + e.getMessage()); throw new RepoException(e); } if (content == null){ log.error("Error retrieving content for object. Content not found. Key: " + repoObject.getKey() + " , bucketName: " + repoObject.getBucketName() + " , versionChecksum: " + repoObject.getVersionChecksum()); throw new RepoException(RepoException.Type.ObjectContentNotFound); } return content; }</code><technical_language>parametrized logging. yay for useful error log statements</technical_language>

Target:
public InputStream getObjectInputStream(RepoObject repoObject) throws RepoException { InputStream content = null; try { content = objectStore.getInputStream(repoObject); } catch (Exception e) { log.error("Error retrieving content for object. Key: , bucketName: , versionChecksum: . Error: {}", repoObject.getKey(), repoObject.getBucketName(), repoObject.getVersionChecksum(), e.getMessage()); throw new RepoException(e); } if (content == null){ log.error("Error retrieving content for object. Content not found. Key: , bucketName: , versionChecksum: ", repoObject.getKey(), repoObject.getBucketName(), repoObject.getVersionChecksum()); throw new RepoException(RepoException.Type.ObjectContentNotFound); } return content; }
Source:
<code>public Set<String> getCollections() { <START> return collections != null ? new TreeSet<>(collections) : null; <END> }</code><technical_language>Avoid logic in this class. This is inconsistent other collection fields. do update this field set null. Also, a tree set</technical_language>

Target:
public Set<String> getCollections() { return collections; }
Source:
<code>public void theDeviceReturnsUpdateFirmwareResponseOverOSLP(final String result) { Oslp.Status oslpStatus = Status.OK; switch (result) { <START> case "OK": <END> oslpStatus = Status.OK; } this.oslpMockServer.mockUpdateFirmwareResponse(oslpStatus); }</code><technical_language>default: for OK status implement other possibilities. I multiple times status is parsed in this class. is wise create a private function for is reused in methods</technical_language>

Target:
public void theDeviceReturnsUpdateFirmwareResponseOverOSLP(final String result) { this.oslpMockServer.mockUpdateFirmwareResponse(this.checkAndGetOslpStatus(result)); }
Source:
<code>private String getExtractionFolder() { <START> String projectPath = System.getProperty("user.dir"); <END> if (new File(projectPath).canWrite()) { return projectPath + PLUGINS_FOLDER; } else { return System.getProperty("user.home") + "/.ganttproject.d" + PLUGINS_FOLDER; } }</code><technical_language>In fact, installation directory user.dir. I more reliable is request /plugins resource Object.class: Object.class.getResource("/plugins") Similar request of /plugins-2.8.6 works for I run ganttproject dist-bin. returns: file:/media/bard/home/bard/ganttproject/desktop/ganttproject-builder/dist-bin/plugins-2.8.6</technical_language>

Target:
private String getExtractionFolder() { URL projectPath = Object.class.getResource(PLUGINS_FOLDER); if (projectPath != null && new File(projectPath.getPath()).canWrite()) { return projectPath.getPath() + PLUGINS_FOLDER; } else { return System.getProperty("user.home") + File.separator + ".ganttproject.d" + PLUGINS_FOLDER; } }
Source:
<code>protected Viewer createViewer(Composite parent) { viewer = ExecutionContextViewerFactory.createViewer(parent, false, this); selectionListener = new RaiseEventSelectionListener(viewer); <START> DebugPlugin.getDefault().addDebugEventListener(this); <END> return viewer; }</code><technical_language>This is implemented AbstractDebugTargetView</technical_language>

Target:
protected Viewer createViewer(Composite parent) { viewer = ExecutionContextViewerFactory.createViewer(parent, false, this); selectionListener = new RaiseEventSelectionListener(viewer); return viewer; }
Source:
<code>public ObservationEntity observationToEntity(Observation obs, long encounterID) { ObservationEntity observationEntity = new ObservationEntity(); observationEntity.setId(obs.getId()); observationEntity.setUuid(obs.getUuid()); <START> observationEntity.setDisplay(obs.getDisplay()); <END> observationEntity.setEncounterKeyID(encounterID); observationEntity.setDisplayValue(obs.getDisplayValue()); observationEntity.setDiagnosisOrder(obs.getDiagnosisOrder()); observationEntity.setDiagnosisList(obs.getDiagnosisList()); observationEntity.setDiagnosisCertainty(obs.getDiagnosisCertainty()); observationEntity.setDiagnosisNote(obs.getDiagnosisNote()); if (obs.getConcept() != null) { observationEntity.setConceptuuid(obs.getConcept().getUuid()); } else { observationEntity.setConceptuuid(null); } return observationEntity; }</code><technical_language>@rishabh-997 Place converter functions respective classes easier read. E.g. move this ObservationEntity.java</technical_language>

Target:
public static ObservationEntity observationToEntity(Observation obs, long encounterID) { ObservationEntity observationEntity = new ObservationEntity(); observationEntity.setId(obs.getId()); observationEntity.setUuid(obs.getUuid()); observationEntity.setDisplay(obs.getDisplay()); observationEntity.setEncounterKeyID(encounterID); observationEntity.setDisplayValue(obs.getDisplayValue()); observationEntity.setDiagnosisOrder(obs.getDiagnosisOrder()); observationEntity.setDiagnosisList(obs.getDiagnosisList()); observationEntity.setDiagnosisCertainty(obs.getDiagnosisCertainty()); observationEntity.setDiagnosisNote(obs.getDiagnosisNote()); if (obs.getConcept() != null) { observationEntity.setConceptuuid(obs.getConcept().getUuid()); } else { observationEntity.setConceptuuid(null); } return observationEntity; }
Source:
<code>public VmBase() { <START> mOs = VmOsType.Unassigned; <END> }</code><technical_language>remove initializing c'tor is done declaration statement: private VmOsType mOs = VmOsType.Unassigned;</technical_language>

Target:
public VmBase() { }
Source:
<code><START> private RequestDescriptor createSpectraRequestDescriptor() { <END> final RequestDescriptor requestDescriptor = new RequestDescriptor(); requestDescriptor.setName(SPECTRA_NAME_BEFORE); requestDescriptor.setClassification(Classification.spectrads3); requestDescriptor.setDescription(SPECTRA_DESCRIPTOR); return requestDescriptor; }</code><technical_language>This static</technical_language>

Target:
private static RequestDescriptor createSpectraRequestDescriptor() { final RequestDescriptor requestDescriptor = new RequestDescriptor(); requestDescriptor.setName(SPECTRA_NAME_BEFORE); requestDescriptor.setClassification(Classification.spectrads3); requestDescriptor.setDescription(SPECTRA_DESCRIPTOR); return requestDescriptor; }
Source:
<code>public void process(final Exchange exchange) throws Exception { final Message message = exchange.getIn(); if(producer == null) { <START> createProducer(); <END> } byte[] body; try { body = exchange.getContext().getTypeConverter() .mandatoryConvertTo(byte[].class, exchange, message.getBody()); } catch (NoTypeConversionAvailableException | TypeConversionException exception) { body = PulsarMessageUtils.serialize(message.getBody()); } producer.send(body); }</code><technical_language>create producer in doStart method</technical_language>

Target:
public void process(final Exchange exchange) throws Exception { final Message message = exchange.getIn(); byte[] body; try { body = exchange.getContext().getTypeConverter() .mandatoryConvertTo(byte[].class, exchange, message.getBody()); } catch (NoTypeConversionAvailableException | TypeConversionException exception) { body = PulsarMessageUtils.serialize(message.getBody()); } producer.send(body); }