auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> default Map<String, Object> getEventStyle(ITimeEvent event) { <END> StateItem stateItem = null; if (event instanceof TimeEvent) { int index = getStateTableIndex(event); StateItem[] stateTable = getStateTable(); if (index >= 0 && index < stateTable.length) { stateItem = stateTable[index]; } } return stateItem != null ? stateItem.getStyleMap() : Collections.emptyMap(); }</code><technical_language>this API... for Cedric's VM, I implement change some style for specific events. able update style value, returned style map is read-only for cause! add a method Map<String, Object> getSpecificEventStyle(event) return difference this method merge 2 maps if empty. This final</technical_language>

Target:
default Map<String, Object> getEventStyle(ITimeEvent event) { StateItem stateItem = null; if (event instanceof TimeEvent) { int index = getStateTableIndex(event); StateItem[] stateTable = getStateTable(); if (index >= 0 && index < stateTable.length) { stateItem = stateTable[index]; } } Map<String, Object> styleMap = new HashMap<>(); if (stateItem != null) { styleMap.putAll(stateItem.getStyleMap()); } styleMap.putAll(getSpecificEventStyle(event)); return styleMap; }
Source:
<code>private void analyse(InputFile inputFile, List<JavaScriptCheck> visitors) { Issuable issuable = perspective(Issuable.class, inputFile); ScriptTree scriptTree; RecognitionException parseException = null; try { scriptTree = (ScriptTree) parser.parse(new java.io.File(inputFile.absolutePath())); scanFile(inputFile, visitors, issuable, scriptTree); } catch (RecognitionException e) { parseException = e; LOG.error("Unable to parse file: " + inputFile.absolutePath()); LOG.error(e.getMessage()); } catch (Exception e) { throw new AnalysisException("Unable to parse file: " + inputFile.absolutePath(), e); } if (parseException != null) { <START> processRecognitionException(parseException, issuable); <END> } }</code><technical_language>@vilchik-elena this done in catch block above</technical_language>

Target:
private void analyse(InputFile inputFile, List<JavaScriptCheck> visitors) { Issuable issuable = perspective(Issuable.class, inputFile); ScriptTree scriptTree; try { scriptTree = (ScriptTree) parser.parse(new java.io.File(inputFile.absolutePath())); scanFile(inputFile, visitors, issuable, scriptTree); } catch (RecognitionException e) { LOG.error("Unable to parse file: " + inputFile.absolutePath()); LOG.error(e.getMessage()); processRecognitionException(e, issuable); } catch (Exception e) { throw new AnalysisException("Unable to parse file: " + inputFile.absolutePath(), e); } }
Source:
<code><START> private ArrayList<String> getTabUrls() { <END> String currentTab = driver.getWindowHandle(); ArrayList<String> result = new ArrayList<>(); for(String windowHandler : driver.getWindowHandles()) { driver.switchTo().window(windowHandler); result.add(driver.getCurrentUrl()); } driver.switchTo().window(currentTab); return result; }</code><technical_language>List interface instead specific implementation</technical_language>

Target:
private List<String> getTabUrls() { String currentTab = driver.getWindowHandle(); List<String> result = new ArrayList<>(); for(String windowHandler : driver.getWindowHandles()) { driver.switchTo().window(windowHandler); result.add(driver.getCurrentUrl()); } driver.switchTo().window(currentTab); return result; }
Source:
<code>private void processFinishedPartitions( final List<Future<StepExecution>> tasks, final Set<StepExecution> result) throws InterruptedException, <START> ExecutionException, Exception { <END> for(int i = 0; i < tasks.size(); i++) { Future<StepExecution> curTask = tasks.get(i); if(curTask.isDone()) { StepExecution curStepExecution = curTask.get(); if(analyzer != null) { analyzer.analyzeStatus(curStepExecution.getStatus().getBatchStatus(), curStepExecution.getExitStatus().getExitCode()); } result.add(curStepExecution); tasks.remove(i); i--; } } }</code><technical_language>Exception is thrown</technical_language>

Target:
private void processFinishedPartitions( final List<Future<StepExecution>> tasks, final Set<StepExecution> result) throws Exception { for(int i = 0; i < tasks.size(); i++) { Future<StepExecution> curTask = tasks.get(i); if(curTask.isDone()) { StepExecution curStepExecution = curTask.get(); if(analyzer != null) { analyzer.analyzeStatus(curStepExecution.getStatus().getBatchStatus(), curStepExecution.getExitStatus().getExitCode()); } result.add(curStepExecution); tasks.remove(i); i--; } } }
Source:
<code>public Integer getMaxVmNameLengthSysprep() { Integer <START> maxVmNameLengthNonWindows = <END> (Integer) getConfigValuePreConverted(ConfigurationValues.MaxVmNameLengthSysprep); if (maxVmNameLengthNonWindows == null) { return 64; } return maxVmNameLengthNonWindows; }</code><technical_language>please rename this maxVmNameLengthSysprep</technical_language>

Target:
public Integer getMaxVmNameLengthSysprep() { Integer maxVmNameLengthSysprep = (Integer) getConfigValuePreConverted(ConfigurationValues.MaxVmNameLengthSysprep); if (maxVmNameLengthSysprep == null) { return 64; } return maxVmNameLengthSysprep; }
Source:
<code>public void close() { <START> healthCheckExecutor.shutdownNow(); <END> log.info("Shutting down health checker for CQL client {}", SafeArg.of("cqlClient", clientName)); boolean shutdown = false; try { shutdown = healthCheckExecutor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error("Interrupted while shutting down health checker for CQL client {}. Should not happen", SafeArg.of("cqlClient", clientName)); Thread.currentThread().interrupt(); } if (!shutdown) { log.error("Failed to shutdown health checker in a timely manner for {}", SafeArg.of("clusterSession", clientName)); } else { log.info("Shut down health checker for {}", SafeArg.of("cqlClient", clientName)); } }</code><technical_language>close method *only* deals health check, actually, need deal underlying Session closed</technical_language>

Target:
public void close() { Cluster cluster = session.getCluster(); session.close(); cluster.close(); }
Source:
<code>public boolean hasValue(@Nullable String value){ boolean ret = false; if (adapter != null) { ret = (getAdapterPosition(value) >= 0); } <START> return ret; <END> }</code><technical_language>public boolean hasValue(@Nullable String value){ if (adapter != null) { return (getAdapterPosition(value) >= 0); } return false; } instantiating a variable here</technical_language>

Target:
public boolean hasValue(@Nullable String value){ if (adapter != null) { return (getAdapterPosition(value) >= 0); } return false; }
Source:
<code>public static IndexedRecord createRecord(Schema recordSchema, Object[] values) { IndexedRecord record = new GenericData.Record(recordSchema); int i = 0; for (Schema.Field f : recordSchema.getFields()) { Schema fieldSchema = f.schema(); if (fieldSchema.getType() == Type.UNION) { for (Schema possible : fieldSchema.getTypes()) { if (possible.getType() != Type.NULL) { fieldSchema = possible; break; } } if (fieldSchema.getType() == Type.UNION) { <START> throw new RuntimeException("No non-null type found in union."); <END> } } if (fieldSchema.getType() == Type.RECORD) { record.put(f.pos(), createRecord(fieldSchema, (Object[]) values[i++])); } else if (fieldSchema.getType() == Type.ARRAY) { record.put(f.pos(), createArray(fieldSchema, (Object[]) values[i++])); } else { record.put(f.pos(), values[i++]); } } return record; }</code><technical_language>TalendRuntimeException instead of RuntimeException please. For of them</technical_language>

Target:
public static IndexedRecord createRecord(Schema recordSchema, Object[] values) { IndexedRecord record = new GenericData.Record(recordSchema); int i = 0; for (Schema.Field f : recordSchema.getFields()) { Schema fieldSchema = f.schema(); if (fieldSchema.getType() == Type.UNION) { for (Schema possible : fieldSchema.getTypes()) { if (possible.getType() != Type.NULL) { fieldSchema = possible; break; } } if (fieldSchema.getType() == Type.UNION) { throw TalendRuntimeException.createUnexpectedException("No non-null type found in union."); } } if (fieldSchema.getType() == Type.RECORD) { record.put(f.pos(), createRecord(fieldSchema, (Object[]) values[i++])); } else if (fieldSchema.getType() == Type.ARRAY) { record.put(f.pos(), createArray(fieldSchema, (Object[]) values[i++])); } else { record.put(f.pos(), values[i++]); } } return record; }
Source:
<code>public Boolean isRestrictedDefaultSpec(Upload testSpec) { <START> if ((testSpec.getType().equals("APPIUM_RUBY_TEST_SPEC") || <END> testSpec.getType().equals("APPIUM_NODE_TEST_SPEC") || testSpec.getType().equals("APPIUM_WEB_RUBY_TEST_SPEC") || testSpec.getType().equals("APPIUM_WEB_NODE_TEST_SPEC")) && (testSpec.getCategory().equals("CURATED"))) { return true; } return false; }</code><technical_language>Reverse equals statement this lead null pointer exception APPIUM_RUBY_TEST_SPEC.equals(testspec.gettype())</technical_language>

Target:
public Boolean isRestrictedDefaultSpec(Upload testSpec) { if (testSpec != null) { if ((APPIUM_RUBY_TEST_SPEC.equals(testSpec.getType()) || APPIUM_NODE_TEST_SPEC.equals(testSpec.getType()) || APPIUM_WEB_RUBY_TEST_SPEC.equals(testSpec.getType()) || APPIUM_WEB_NODE_TEST_SPEC.equals(testSpec.getType())) && (CURATED.equals(testSpec.getCategory()))) { return true; } } return false; }
Source:
<code>public void destroy(final String identifier) throws EhcacheEntityNotFoundException, EntityBusyException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier's maintenance lease held"); } else { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { if (!ref.destroy()) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier in use by other clients"); } } catch (EntityNotProvidedException e) { <START> LOGGER.error("Unable to delete clustered tier manager for id " + identifier, e); <END> silentlyUnlock(localMaintenance, identifier); throw new AssertionError(e); } catch (EntityNotFoundException e) { silentlyUnlock(localMaintenance, identifier); throw new EhcacheEntityNotFoundException(e); } catch (Error e) { silentlyUnlock(localMaintenance, identifier); throw e; } catch (RuntimeException e) { silentlyUnlock(localMaintenance, identifier); throw e; } } if (localMaintenance != null) { localMaintenance.unlock(); } }</code><technical_language>change? previous version is standard pattern for slf4j</technical_language>

Target:
public void destroy(final String identifier) throws EhcacheEntityNotFoundException, EntityBusyException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier's maintenance lease held"); } boolean finished = false; try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { if (!ref.destroy()) { throw new EntityBusyException("Destroy operation failed; " + identifier + " clustered tier in use by other clients"); } finished = true; } catch (EntityNotProvidedException e) { LOGGER.error("Unable to delete clustered tier manager for id {}", identifier, e); throw new AssertionError(e); } catch (EntityNotFoundException e) { throw new EhcacheEntityNotFoundException(e); } } finally { if (localMaintenance != null) { if (finished) { localMaintenance.unlock(); } else { silentlyUnlock(localMaintenance, identifier); } } } }
Source:
<code>public List<String> getNamesByGidsAndPrefixes(final List<Integer> gids, final List<String> prefixes) { try { final StringBuilder sql = new StringBuilder(); sql.append("SELECT nval FROM names WHERE gid IN (:gids) ") .append(" AND ( "); final int prefixesSize = prefixes.size(); <START> for (int i=0; i<prefixesSize; i++) { <END> final String prefix = prefixes.get(i) + "%"; sql.append(" nval LIKE '" + prefix + "'"); if(i+1 != prefixesSize) { sql.append(" OR "); } } sql.append(" ) "); final Query query = this.getSession().createSQLQuery(sql.toString()); query.setParameterList("gids", gids); return query.list(); } catch (final HibernateException e) { final String message = "Error with getNamesByGidsAndPrefixes(gids=" + gids + ", prefixes=" + prefixes +") query from Name " + e.getMessage(); NameDAO.LOG.error(message); throw new MiddlewareQueryException(message, e); } }</code><technical_language>replace this for loop by: final List<String> formattedPrefixes = prefixes.stream().map(prefix -> " nval '" + prefix + "'").collect(Collectors.toList()); sql.append(StringUtils.join(formattedPrefixes, " "));</technical_language>

Target:
public List<String> getNamesByGidsAndPrefixes(final List<Integer> gids, final List<String> prefixes) { try { final StringBuilder sql = new StringBuilder(); sql.append("SELECT nval FROM names WHERE gid IN (:gids) ") .append(" AND ( "); final List<String> formattedPrefixes = prefixes.stream().map(prefix -> " nval LIKE '" + prefix + "%'").collect(Collectors.toList()); sql.append(String.join(" OR ", formattedPrefixes)); sql.append(" ) "); final Query query = this.getSession().createSQLQuery(sql.toString()); query.setParameterList("gids", gids); return query.list(); } catch (final HibernateException e) { final String message = "Error with getNamesByGidsAndPrefixes(gids=" + gids + ", prefixes=" + prefixes +") query from Name " + e.getMessage(); NameDAO.LOG.error(message); throw new MiddlewareQueryException(message, e); } }
Source:
<code>public Comparator getComparator() { <START> return new Comparator() <END> { @Override public int compare(Object o1, Object o2) { return Longs.compare(((SerializablePair<Long, Long>) o1).rhs, ((SerializablePair<Long, Long>) o2).rhs); } }; }</code><technical_language>suggestion static comparator</technical_language>

Target:
public Comparator getComparator() { return VALUE_COMPARATOR; }
Source:
<code>public void logFailure(JoinPoint joinPoint, Throwable e, String service, String version) { if (eventRecorder != null && eventRecorder.isRecordEventEnabled()) { MethodSignature sig = (MethodSignature) joinPoint.getSignature(); Logger log = LoggerFactory.getLogger(sig.getDeclaringType()); log.info("{} threw an exception: {}", sig.getName(), e.getMessage()); ErrorEventBuilder builder = new ErrorEventBuilder(); builder.setAssertion(AssertionExtractor.getAssertion(joinPoint.getArgs())); builder.setThrowable(e); builder.setInvoker(sig.getDeclaringType().toString()); builder.setMethod(sig.getName()); <START> builder.setService(service); <END> builder.setVersion(version); builder.buildMessageID(); builder.buildTransactionID(); builder.buildDescription(); eventRecorder.recordEvent(builder.getEvent()); } }</code><technical_language>familiar EventDirector. Is a reason processing done is removed? Is is needed deleted</technical_language>

Target:
public void logFailure(JoinPoint joinPoint, Throwable e, String service, String version) { MethodSignature sig = (MethodSignature) joinPoint.getSignature(); Logger log = LoggerFactory.getLogger(sig.getDeclaringType()); log.info("{} threw an exception: {}", sig.getName(), e.getMessage()); if (eventRecorder != null && eventRecorder.isRecordEventEnabled()) { ErrorEventBuilder builder = new ErrorEventBuilder(); builder.setAssertion(AssertionExtractor.getAssertion(joinPoint.getArgs())); builder.setThrowable(e); builder.setInvoker(sig.getDeclaringType().getName()); builder.setMethod(sig.getName()); builder.setService(service); builder.setVersion(version); builder.buildMessageID(); builder.buildTransactionID(); builder.buildDescription(); eventRecorder.recordEvent(builder.getEvent()); } }
Source:
<code>public File execute(MCPEnvironment environment) throws Exception { File input = (File)environment.getArguments().get("input"); environment.project.getLogger().lifecycle(input.getAbsolutePath()); File output = environment.getFile("output.jar"); <START> File rejects = environment.getFile("rejects.zip"); <END> File hashFile = environment.getFile("lastinput.sha1"); HashStore hashStore = new HashStore(environment.project).load(hashFile); hashStore.add(input); Files.walk(patchesDir.toPath()) .filter(Files::isRegularFile) .filter(Files::exists) .forEach(e -> hashStore.add(patchesDir.toPath().relativize(e).toString(), e.toFile())); if (hashStore.isSame() && output.exists()) return output; PatchAction action = new PatchAction(environment.project); action.setBase(input); action.setPatches(patchesDir); action.setOutput(output); action.setPatchMode(PatchMode.FUZZY); action.setMaxFuzzOffset(0); action.setVerbose(false); action.setRejects(rejects); boolean success = action.execute() == 0; if (!success) { environment.logger.error("Rejects saved to: {}", rejects); throw new RuntimeException("Patch failure."); } else { hashStore.save(hashFile); } return output; }</code><technical_language>in memory, built do before</technical_language>

Target:
public File execute(MCPEnvironment environment) throws Exception { File input = (File) environment.getArguments().get("input"); File output = environment.getFile("output.jar"); File rejects = environment.getFile("rejects.zip"); File hashFile = environment.getFile("lastinput.sha1"); HashStore hashStore = new HashStore(environment.project).load(hashFile); hashStore.add(input); try (ZipInputStream zin = new ZipInputStream(new FileInputStream(environment.getConfigZip()))) { ZipEntry e; while ((e = zin.getNextEntry()) != null) { if (e.getName().startsWith(path)) { hashStore.add(e.getName().substring(path.length()), IOUtils.toByteArray(zin)); } } } if (hashStore.isSame() && output.exists()) { return output; } CliOperation.Result<PatchOperation.PatchesSummary> result = PatchOperation.builder() .logTo(new LoggingOutputStream(environment.logger, LogLevel.LIFECYCLE)) .basePath(input.toPath()) .patchesPath(environment.getConfigZip().toPath()) .patchesPrefix(path) .outputPath(output.toPath()) .verbose(false) .mode(PatchMode.ACCESS) .rejectsPath(rejects.toPath()) .build() .operate(); boolean success = result.exit == 0; if (!success) { environment.logger.error("Rejects saved to: {}", rejects); throw new RuntimeException("Patch failure."); } else { hashStore.save(hashFile); } return output; }
Source:
<code>public BeanDefinition parse(Element element, ParserContext parserContext) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); parserContext.pushContainingComponent(compositeDef); Map<String, Map<String, String>> providerDetailMap = retrieveProviders(element); List<ClientRegistration> clientRegs = retrieveClientRegistrations(element, providerDetailMap); BeanDefinition inMemClientRegRepoBeanDef = BeanDefinitionBuilder .rootBeanDefinition(InMemoryClientRegistrationRepository.class).addConstructorArgValue(clientRegs) .getBeanDefinition(); String beanName = parserContext.getReaderContext().generateBeanName(inMemClientRegRepoBeanDef); parserContext.registerBeanComponent(new BeanComponentDefinition(inMemClientRegRepoBeanDef, beanName)); <START> BeanDefinition inMemOAuth2AuthorizedClientServiceBeanDef = BeanDefinitionBuilder <END> .rootBeanDefinition(InMemoryOAuth2AuthorizedClientService.class) .addConstructorArgValue(new RuntimeBeanReference(InMemoryClientRegistrationRepository.class)) .getBeanDefinition(); beanName = parserContext.getReaderContext().generateBeanName(inMemOAuth2AuthorizedClientServiceBeanDef); parserContext.registerBeanComponent( new BeanComponentDefinition(inMemOAuth2AuthorizedClientServiceBeanDef, beanName)); parserContext.popAndRegisterContainingComponent(); return null; }</code><technical_language>check if application registered OAuth2AuthorizedClientService OAuth2AuthorizedClientrepository bean default in-memory service</technical_language>

Target:
public BeanDefinition parse(Element element, ParserContext parserContext) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); parserContext.pushContainingComponent(compositeDef); Map<String, Map<String, String>> providerDetailMap = getProviders(element); List<ClientRegistration> clientRegs = getClientRegistrations(element, parserContext, providerDetailMap); BeanDefinition inMemClientRegRepoBeanDef = BeanDefinitionBuilder .rootBeanDefinition(InMemoryClientRegistrationRepository.class).addConstructorArgValue(clientRegs) .getBeanDefinition(); String beanName = parserContext.getReaderContext().generateBeanName(inMemClientRegRepoBeanDef); parserContext.registerBeanComponent(new BeanComponentDefinition(inMemClientRegRepoBeanDef, beanName)); parserContext.popAndRegisterContainingComponent(); return null; }
Source:
<code>private TarArchiveInputStream intoTarArchive(Consumer<TarArchiveOutputStream> consumer) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); <START> final TarArchiveOutputStream taos = new TarArchiveOutputStream(baos); <END> consumer.accept(taos); taos.close(); return new TarArchiveInputStream(new ByteArrayInputStream(baos.toByteArray())); }</code><technical_language>try-with-resources? @Cleanup</technical_language>

Target:
private TarArchiveInputStream intoTarArchive(Consumer<TarArchiveOutputStream> consumer) throws IOException { @Cleanup final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Cleanup final TarArchiveOutputStream taos = new TarArchiveOutputStream(baos); consumer.accept(taos); taos.close(); return new TarArchiveInputStream(new ByteArrayInputStream(baos.toByteArray())); }
Source:
<code>protected IResourceVariant fetchVariant(IResource resource, int depth, IProgressMonitor monitor) throws TeamException { SubMonitor subMonitor = SubMonitor.convert(monitor); if (resource == null) { subMonitor.done(); return null; <START> } <END> subMonitor.beginTask(NLS.bind( CoreText.GitResourceVariantTree_fetchingVariant, resource.getName()), IProgressMonitor.UNKNOWN); try { return fetchVariant(resource, subMonitor); } finally { subMonitor.done(); } }</code><technical_language>prefer single statement if's brackets</technical_language>

Target:
protected IResourceVariant fetchVariant(IResource resource, int depth, IProgressMonitor monitor) throws TeamException { SubMonitor subMonitor = SubMonitor.convert(monitor); if (resource == null) { subMonitor.done(); return null; } subMonitor.beginTask(NLS.bind( CoreText.GitResourceVariantTree_fetchingVariant, resource.getName()), IProgressMonitor.UNKNOWN); try { return fetchVariant(resource, subMonitor); } finally { monitor.done(); } }
Source:
<code>public DefaultSourceConfigurationImpl(final Map<String, Object> configMap) { this.configMap = new HashMap<>(); <START> configMap.keySet().stream() <END> .forEach(s->this.configMap.put(s, configMap.get(s))); }</code><technical_language>putAll(map) method simplify this code</technical_language>

Target:
public DefaultSourceConfigurationImpl(final Map<String, Object> configMap) { this.configMap = new HashMap<>(); this.configMap.putAll(configMap); }
Source:
<code>static Consumer<List<BatchElement<Integer, List<StartIdentifiedAtlasDbTransactionResponse>>>> consumer( LockLeaseService lockLeaseService, LockWatchEventCache lockWatchEventCache) { return batch -> { int numTransactions = batch.stream().map(BatchElement::argument).reduce(0, Integer::sum); List<StartIdentifiedAtlasDbTransactionResponse> startTransactionResponses = getStartTransactionResponses(lockLeaseService, lockWatchEventCache, numTransactions); int start = 0; for (BatchElement<Integer, List<StartIdentifiedAtlasDbTransactionResponse>> batchElement : batch) { int end = start + batchElement.argument(); <START> batchElement.result().set(startTransactionResponses.subList(start, end)); <END> start = end; } }; }</code><technical_language>Hmm, carefully this subList here. @jeremyk-91</technical_language>

Target:
static Consumer<List<BatchElement<Integer, List<StartIdentifiedAtlasDbTransactionResponse>>>> consumer( LockLeaseService lockLeaseService, LockWatchEventCache lockWatchEventCache) { return batch -> { int numTransactions = batch.stream().mapToInt(BatchElement::argument).reduce(0, Integer::sum); List<StartIdentifiedAtlasDbTransactionResponse> startTransactionResponses = getStartTransactionResponses(lockLeaseService, lockWatchEventCache, numTransactions); int start = 0; for (BatchElement<Integer, List<StartIdentifiedAtlasDbTransactionResponse>> batchElement : batch) { int end = start + batchElement.argument(); batchElement.result().set(ImmutableList.copyOf(startTransactionResponses.subList(start, end))); start = end; } }; }
Source:
<code>public Map<byte[], List<byte[]>> rollWal(long now) throws IOException { this.lastRollTime = now; Map<byte[], List<byte[]>> regionsToFlush = wal.rollWriter(true); <START> this.rollRequest.set(false); <END> return regionsToFlush; }</code><technical_language>get. AtomicBoolean is compared boolean wrt repeated roll possibility. In Boolean state in a Map. in this object</technical_language>

Target:
public Map<byte[], List<byte[]>> rollWal(long now) throws IOException { this.lastRollTime = now; this.rollRequest.set(false); return wal.rollWriter(true); }
Source:
<code>private List<? extends ParameterValue> filter(List<ParameterValue> parameters) { if (this.run == null) { return parameters; } if (this.parameterDefinitionNames == null) { return parameters; } String shouldKeepFlag = SystemProperties.getString(KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME); if ("true".equalsIgnoreCase(shouldKeepFlag)) { return parameters; } List<ParameterValue> filteredParameters = new ArrayList<ParameterValue>(); for (ParameterValue v : this.parameters) { if (this.parameterDefinitionNames.contains(v.getName()) || isSafeParameter(v.getName())) { filteredParameters.add(v); } else if ("false".equalsIgnoreCase(shouldKeepFlag)) { LOGGER.log(Level.WARNING, "Skipped parameter `{0}` as it is undefined on `{1}`. Set `-D{2}=true` to allow " + "undefined parameters to be injected as environment variables or `-D{3}=[comma-separated list]` to whitelist specific parameter names, " <START> + "even though it represents a security breach or `-D{2}=false to explicitly forbid it without warning.", <END> new Object { v.getName(), run.getParent().getFullName(), KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME, SAFE_PARAMETERS_SYSTEM_PROPERTY_NAME }); } } return filteredParameters; }</code><technical_language>Misses closing backtick. a sentence: Set -D{2}=false longer show this message</technical_language>

Target:
private List<? extends ParameterValue> filter(List<ParameterValue> parameters) { if (this.run == null) { return parameters; } if (this.parameterDefinitionNames == null) { return parameters; } String shouldKeepFlag = SystemProperties.getString(KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME); if ("true".equalsIgnoreCase(shouldKeepFlag)) { return parameters; } List<ParameterValue> filteredParameters = new ArrayList<ParameterValue>(); for (ParameterValue v : this.parameters) { if (this.parameterDefinitionNames.contains(v.getName()) || isSafeParameter(v.getName())) { filteredParameters.add(v); } else if ("false".equalsIgnoreCase(shouldKeepFlag)) { LOGGER.log(Level.WARNING, "Skipped parameter `{0}` as it is undefined on `{1}`. Set `-D{2}=true` to allow " + "undefined parameters to be injected as environment variables or `-D{3}=[comma-separated list]` to whitelist specific parameter names, " + "even though it represents a security breach or `-D{2}=false` to no longer show this message.", new Object { v.getName(), run.getParent().getFullName(), KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME, SAFE_PARAMETERS_SYSTEM_PROPERTY_NAME }); } } return filteredParameters; }
Source:
<code><START> private String findSchemeIdColumn() { <END> if (DbConnectionFactory.isMySql()) { return MYSQL_FIND_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isPostgres()) { return POSTGRES_FIND_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isMsSql()) { return MSSQL_FIND_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isOracle()) { return ORACLE_FIND_SCHEME_ID_COLUMN; } else { return null; } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Reduce number of returns of this method 5, maximum allowed 3. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private String findSchemeIdColumn() { String sql = null; if (DbConnectionFactory.isMySql()) { sql = MYSQL_FIND_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isPostgres()) { sql = POSTGRES_FIND_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isMsSql()) { sql = MSSQL_FIND_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isOracle()) { sql = ORACLE_FIND_SCHEME_ID_COLUMN; } return sql; }
Source:
<code>public String get(String key) { String value = getTestProperties().getProperty(key); if (value != null) { LOGGER.warn("Overridden '" + key + "=" + value + "' property will be used for current test!"); return value; } value = CONFIG.resourceFile.equals(resourceFile) ? PlaceholderResolver.resolve(propertiesHolder.get(resourceFile), key) : propertiesHolder.get(resourceFile).getProperty(key); <START> String decryptedText = decrypt(value, CRYPTO_PATTERN); <END> if ((null != value) && (null != decryptedText) && (!decryptedText.equals(value))) { value = decryptedText; } return value != null ? value : StringUtils.EMPTY; }</code><technical_language>Logic is pretty broken. in sync naming, i.e. call decrypt if isEncrypted. get method do: if (isEncrypted(...)) { = decrypt(value, CRYPTO_PATTERN); } remove 180-182 if lines..</technical_language>

Target:
public String get(String key) { String value = getTestProperties().getProperty(key); if (value != null) { LOGGER.warn("Overridden '" + key + "=" + value + "' property will be used for current test!"); return value; } value = CONFIG.resourceFile.equals(resourceFile) ? PlaceholderResolver.resolve(propertiesHolder.get(resourceFile), key) : propertiesHolder.get(resourceFile).getProperty(key); if(isEncrypted(value, CRYPTO_PATTERN)) { value = decrypt(value, CRYPTO_PATTERN);; } return value != null ? value : StringUtils.EMPTY; }
Source:
<code>private void staggeredProcessNext(ReplicableCommand command, RspFilter filter, List<Address> dests, <START> ResponseMode mode, DeliverOrder deliverOrder, Marshaller marshaller, <END> CompletableFuture<Responses> theFuture, int destIndex, long deadline, Responses rsps) { if (theFuture.isDone()) { return; } if (timeService.isTimeExpired(deadline)) { theFuture.complete(rsps); return; } try { processCallsStaggered(command, filter, dests, mode, deliverOrder, marshaller, theFuture, destIndex + 1, deadline, rsps); } catch (Exception e) { theFuture.completeExceptionally(e); } }</code><technical_language>In reformatting mood? ;)</technical_language>

Target:
private void staggeredProcessNext(ReplicableCommand command, RspFilter filter, List<Address> dests, ResponseMode mode, DeliverOrder deliverOrder, Marshaller marshaller, CompletableFuture<Responses> theFuture, int destIndex, long deadline, Responses rsps) { if (theFuture.isDone()) { return; } if (timeService.isTimeExpired(deadline)) { rsps.setTimedOut(); theFuture.complete(rsps); return; } try { processCallsStaggered(command, filter, dests, mode, deliverOrder, marshaller, theFuture, destIndex + 1, deadline, rsps); } catch (Exception e) { theFuture.completeExceptionally(e); } }
Source:
<code>protected abstract ConnectionListener createConnectionListener(Credential credential) throws ResourceException; protected abstract void destroyConnectionListener(ConnectionListener cl) throws ResourceException; protected abstract ManagedConnectionPool createManagedConnectionPool(Credential credential); @Override <START> public void prefill(Credential credential) <END> { this.prefillCredential = credential; if (shouldPrefill) { ManagedConnectionPool mcp = getManagedConnectionPool(credential); mcp.prefill(); } }</code><technical_language>Remove 'credential' signature</technical_language>

Target:
protected abstract ConnectionListener createConnectionListener(Credential credential) throws ResourceException; protected abstract void destroyConnectionListener(ConnectionListener cl) throws ResourceException; protected abstract ManagedConnectionPool createManagedConnectionPool(Credential credential); @Override public void prefill() { if (poolConfiguration.isPrefill()) { ManagedConnectionPool mcp = pools.get(getPrefillCredential()); if (mcp == null) { getManagedConnectionPool(getPrefillCredential()); } else { mcp.prefill(); } } }
Source:
<code>public void addEntry(IndexEntry entry, long fileEndOffset) throws StoreException { try { rwLock.readLock().lock(); if (mapped.get()) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " cannot add to a mapped index ", StoreErrorCodes.Illegal_Index_Operation); } logger.trace("IndexSegment inserting key - value - offset size ttl " + "originalMessageOffset fileEndOffset {}", indexFile.getAbsolutePath(), entry.getKey(), entry.getValue().getOffset(), entry.getValue().getSize(), entry.getValue().getTimeToLiveInMs(), entry.getValue().getOriginalMessageOffset(), fileEndOffset); if (index.put(entry.getKey(), entry.getValue()) == null) { numberOfItems.incrementAndGet(); sizeWritten.addAndGet(entry.getKey().sizeInBytes() + IndexValue.Index_Value_Size_In_Bytes); bloomFilter.add(ByteBuffer.wrap(entry.getKey().toBytes())); } endOffset.set(fileEndOffset); <START> lastModifiedSec.set(SystemTime.getInstance().milliseconds()/1000); <END> if (keySize == Key_Size_Invalid_Value) { StoreKey key = entry.getKey(); keySize = key.sizeInBytes(); logger.info("IndexSegment : setting key size to of key for index with start offset {}", indexFile.getAbsolutePath(), key.sizeInBytes(), key.getLongForm(), startOffset); } if (valueSize == Value_Size_Invalid_Value) { valueSize = entry.getValue().getBytes().capacity(); logger.info("IndexSegment : setting value size to for index with start offset {}", indexFile.getAbsolutePath(), valueSize, startOffset); } } finally { rwLock.readLock().unlock(); } }</code><technical_language>reason read lastModified time file</technical_language>

Target:
public void addEntry(IndexEntry entry, long fileEndOffset) throws StoreException { try { rwLock.readLock().lock(); if (mapped.get()) { throw new StoreException("IndexSegment : " + indexFile.getAbsolutePath() + " cannot add to a mapped index ", StoreErrorCodes.Illegal_Index_Operation); } logger.trace("IndexSegment inserting key - value - offset size ttl " + "originalMessageOffset fileEndOffset {}", indexFile.getAbsolutePath(), entry.getKey(), entry.getValue().getOffset(), entry.getValue().getSize(), entry.getValue().getTimeToLiveInMs(), entry.getValue().getOriginalMessageOffset(), fileEndOffset); if (index.put(entry.getKey(), entry.getValue()) == null) { numberOfItems.incrementAndGet(); sizeWritten.addAndGet(entry.getKey().sizeInBytes() + IndexValue.Index_Value_Size_In_Bytes); bloomFilter.add(ByteBuffer.wrap(entry.getKey().toBytes())); } endOffset.set(fileEndOffset); lastModifiedTimeSec.set(SystemTime.getInstance().milliseconds() / 1000); if (keySize == Key_Size_Invalid_Value) { StoreKey key = entry.getKey(); keySize = key.sizeInBytes(); logger.info("IndexSegment : setting key size to of key for index with start offset {}", indexFile.getAbsolutePath(), key.sizeInBytes(), key.getLongForm(), startOffset); } if (valueSize == Value_Size_Invalid_Value) { valueSize = entry.getValue().getBytes().capacity(); logger.info("IndexSegment : setting value size to for index with start offset {}", indexFile.getAbsolutePath(), valueSize, startOffset); } } finally { rwLock.readLock().unlock(); } }
Source:
<code>public byte[] convert(Blob source) { if (source == null) { return null; } try { <START> InputStream blobStream = source.getBinaryStream(); <END> if (blobStream != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamUtils.copy(blobStream, baos); return baos.toByteArray(); } } catch (SQLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return null; }</code><technical_language>Do need close InputStream</technical_language>

Target:
public byte[] convert(Blob source) { if (source == null) { return null; } InputStream blobStream = null; try { blobStream = source.getBinaryStream(); if (blobStream != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamUtils.copy(blobStream, baos); return baos.toByteArray(); } } catch (SQLException e) { throw new DataRetrievalFailureException("Couldn't retrieve data from blob.", e); } catch (IOException e) { throw new DataRetrievalFailureException("Couldn't retrieve data from blob.", e); } finally { if (blobStream != null) { try { blobStream.close(); } catch (IOException e) { throw new CleanupFailureDataAccessException("Couldn't close binary stream for given blob.", e); } } } return null; }
Source:
<code>public Matrix removeRow(int i, Factory factory) { if (i >= this.rows || i < 0) { <START> throw new IllegalArgumentException("Illegal row number, must be 0.." + (this.rows - 1)); <END> } Matrix that = factory.createMatrix(this.rows - 1, this.columns); for (int ii = 0; ii < i; ii++) { that.setRow(ii, this.getRow(ii)); } for (int ii = i + 1; ii < this.rows; ii++) { that.setRow(ii - 1, this.getRow(ii)); } return that; }</code><technical_language>Unnecessary this</technical_language>

Target:
public Matrix removeRow(int i, Factory factory) { if (i >= rows || i < 0) { throw new IndexOutOfBoundsException("Illegal row number, must be 0.." + (rows - 1)); } Matrix result = factory.createMatrix(rows - 1, columns); for (int ii = 0; ii < i; ii++) { result.setRow(ii, getRow(ii)); } for (int ii = i + 1; ii < rows; ii++) { result.setRow(ii - 1, getRow(ii)); } return result; }
Source:
<code>public CourseRoster(List<StudentAttributes> students, List<InstructorAttributes> instructors) { populateStudentListByEmail(students); populateInstructorListByEmail(instructors); <START> for (StudentAttributes studentAttributes : this.getStudents()) { <END> teamToMembersTable.computeIfAbsent(studentAttributes.getTeam(), key -> new ArrayList<>()) .add(studentAttributes); } }</code><technical_language>Apply SLAP principle here: extract this block a private method, matter simple is</technical_language>

Target:
public CourseRoster(List<StudentAttributes> students, List<InstructorAttributes> instructors) { populateStudentListByEmail(students); populateInstructorListByEmail(instructors); buildTeamToMembersTable(); }
Source:
<code>private QueryBuilder buildSearchQuery() { BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); for (ElasticsearchColumnHandle column : columns) { BoolQueryBuilder columnQueryBuilder = new BoolQueryBuilder(); Type type = column.getColumnType(); <START> tupleDomain.getDomains().ifPresent((domains) -> { <END> Domain domain = domains.get(column); if (domain != null) { columnQueryBuilder.should(buildPredicate(column.getColumnJsonPath(), domain, type)); } }); boolQueryBuilder.must(columnQueryBuilder); } return boolQueryBuilder.hasClauses() ? boolQueryBuilder : new MatchAllQueryBuilder(); }</code><technical_language>(domains) -> domains</technical_language>

Target:
private QueryBuilder buildSearchQuery() { BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); for (ElasticsearchColumnHandle column : columns) { BoolQueryBuilder columnQueryBuilder = new BoolQueryBuilder(); Type type = column.getColumnType(); if (tupleDomain.getDomains().isPresent()) { Domain domain = tupleDomain.getDomains().get().get(column); if (domain != null) { columnQueryBuilder.should(buildPredicate(column.getColumnJsonPath(), domain, type)); } } boolQueryBuilder.must(columnQueryBuilder); } if (boolQueryBuilder.hasClauses()) { return boolQueryBuilder; } return new MatchAllQueryBuilder(); }
Source:
<code>public void testEstimatedAndSplitForSmallTable() throws Exception { TableName tableName = newTestTableName(); try (Admin admin = connection.getAdmin()) { admin.createTable( new HTableDescriptor(tableName).addFamily(new HColumnDescriptor(COLUMN_FAMILY))); try (Table table = connection.getTable(tableName)) { table.put(Arrays.asList( new Put(Bytes.toBytes("row1")).addColumn(COLUMN_FAMILY, QUALIFIER1, Bytes.toBytes("1")), new Put(Bytes.toBytes("row2")).addColumn(COLUMN_FAMILY, QUALIFIER1, Bytes.toBytes("2")))); } List<SampleRowKeysResponse> sampleRowKeys = getSampleKeys(tableName); try { CloudBigtableIO.Source source = new CloudBigtableIO.Source(new CloudBigtableScanConfiguration( projectId, zoneId, clusterId, tableName.getQualifierAsString(), new Scan())); long estimatedSizeBytes = source.getEstimatedSizeBytes(null); SampleRowKeysResponse lastSample = sampleRowKeys.get(sampleRowKeys.size() - 1); Assert.assertEquals(lastSample.getOffsetBytes(), estimatedSizeBytes); List<SourceWithKeys> bundles = source.splitIntoBundles(estimatedSizeBytes / 2 + 1, null); <START> Assert.assertEquals(sampleRowKeys.size() * 2 - 1, bundles.size()); <END> } finally { admin.deleteTable(tableName); } } }</code><technical_language>clearer if check sampleRowKeys.size() bundles.size() 1. a check estimatedSizeBytes clearer</technical_language>

Target:
public void testEstimatedAndSplitForSmallTable() throws Exception { TableName tableName = newTestTableName(); try (Admin admin = connection.getAdmin()) { admin.createTable( new HTableDescriptor(tableName).addFamily(new HColumnDescriptor(COLUMN_FAMILY))); try (Table table = connection.getTable(tableName)) { table.put(Arrays.asList( new Put(Bytes.toBytes("row1")).addColumn(COLUMN_FAMILY, QUALIFIER1, Bytes.toBytes("1")), new Put(Bytes.toBytes("row2")).addColumn(COLUMN_FAMILY, QUALIFIER1, Bytes.toBytes("2")))); } List<SampleRowKeysResponse> sampleRowKeys = getSampleKeys(tableName); try { BoundedSource<Result> source = CloudBigtableIO.read(new CloudBigtableScanConfiguration( projectId, zoneId, clusterId, tableName.getQualifierAsString(), new Scan())); long estimatedSizeBytes = source.getEstimatedSizeBytes(null); SampleRowKeysResponse lastSample = sampleRowKeys.get(sampleRowKeys.size() - 1); Assert.assertEquals(lastSample.getOffsetBytes(), estimatedSizeBytes); List<? extends BoundedSource<Result>> bundles = source.splitIntoBundles(estimatedSizeBytes / 2 + 1, null); Assert.assertEquals(sampleRowKeys.size() * 2 - 1, bundles.size()); } finally { admin.deleteTable(tableName); } } }
Source:
<code>void onChunkOperationComplete(PutChunk chunk) { if (chunk.getChunkBlobId() == null) { <START> if (operationException.get() == null) { <END> operationException.set(new RouterException("Could not complete operation", RouterErrorCode.AmbryUnavailable)); } logger.error("Failed putting chunk at index: " + chunk.getChunkIndex() + ", failing the entire operation"); complete(); } else if (numDataChunks == 1 || chunk == metadataPutChunk) { blobId = chunk.getChunkBlobId(); if (chunk.failedAttempts > 0) { logger.info("Slipped put succeeded for blob: " + chunk.getChunkBlobId()); } else { logger.trace("Successfully put blob: " + chunk.getChunkBlobId()); } complete(); } else { logger.trace("Successfully put chunk with blob id: " + chunk.getChunkBlobId()); metadataPutChunk.addChunkId(chunk.chunkBlobId, chunk.chunkIndex); } }</code><technical_language>chance this set</technical_language>

Target:
void onChunkOperationComplete(PutChunk chunk) { if (chunk.getChunkBlobId() == null) { logger.error("Failed putting chunk at index: " + chunk.getChunkIndex() + ", failing the entire operation"); operationCompleted = true; } else if (numDataChunks == 1 || chunk == metadataPutChunk) { blobId = chunk.getChunkBlobId(); if (chunk.failedAttempts > 0) { logger.trace("Slipped put succeeded for chunk: " + chunk.getChunkBlobId()); } else { logger.trace("Successfully put chunk: " + chunk.getChunkBlobId()); } operationCompleted = true; } else { logger.trace("Successfully put chunk with blob id: " + chunk.getChunkBlobId()); metadataPutChunk.addChunkId(chunk.chunkBlobId, chunk.chunkIndex); } chunk.clear(); }
Source:
<code>public void testMultipleClients() throws Throwable { <START> try (Connection clientA = CLUSTER.newConnection()) { <END> VoltronReadWriteLock lockA = new VoltronReadWriteLock(clientA, "test"); Hold hold = lockA.writeLock(); try (Connection clientB = CLUSTER.newConnection()) { Future<Void> waiter = async(() -> { new VoltronReadWriteLock(clientB, "test").writeLock().unlock(); return null; }); try { waiter.get(100, TimeUnit.MILLISECONDS); fail("TimeoutException expected"); } catch (TimeoutException e) { } hold.unlock(); waiter.get(); } } }</code><technical_language>possibly collapse try</technical_language>

Target:
public void testMultipleClients() throws Throwable { try (Connection clientA = CLUSTER.newConnection(); Connection clientB = CLUSTER.newConnection()) { VoltronReadWriteLock lockA = new VoltronReadWriteLock(clientA, "test"); Hold hold = lockA.writeLock(); Future<Void> waiter = async(() -> { new VoltronReadWriteLock(clientB, "test").writeLock().unlock(); return null; }); try { waiter.get(100, TimeUnit.MILLISECONDS); fail("TimeoutException expected"); } catch (TimeoutException e) { } hold.unlock(); waiter.get(); } }
Source:
<code>public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> descriptors= new ArrayList<IPropertyDescriptor>(); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP, NAME_TIMESTAMP)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE, NAME_SOURCE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TYPE, NAME_TYPE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_REFERENCE, NAME_REFERENCE)); if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE_LOOKUP, NAME_SOURCE_LOOKUP)); } if ((fEvent instanceof ITmfModelLookup) && (((ITmfModelLookup)fEvent).getModelUri() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_MODEL_URI, NAME_MODEL_URI)); } descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT)); <START> if((fEvent instanceof CtfTmfEvent) && !((CtfTmfEvent)fEvent).listCustomAttributes().isEmpty()){ <END> if(((CtfTmfEvent)fEvent).listCustomAttributes().size() != 1) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTES)); } else { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTE)); } } return descriptors.toArray(new IPropertyDescriptor[0]); }</code><technical_language>instanceof checks good practice... worth adding a getCustomAttibutes() method ITmfEvent directly. talk this team</technical_language>

Target:
public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> descriptors= new ArrayList<IPropertyDescriptor>(); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TIMESTAMP, NAME_TIMESTAMP)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE, NAME_SOURCE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_TYPE, NAME_TYPE)); descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_REFERENCE, NAME_REFERENCE)); if ((fEvent instanceof ITmfSourceLookup) && (((ITmfSourceLookup)fEvent).getCallsite() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_SOURCE_LOOKUP, NAME_SOURCE_LOOKUP)); } if ((fEvent instanceof ITmfModelLookup) && (((ITmfModelLookup)fEvent).getModelUri() != null)) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_MODEL_URI, NAME_MODEL_URI)); } descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CONTENT, NAME_CONTENT)); if((fEvent instanceof ITmfCustomAttribute) && !((ITmfCustomAttribute)fEvent).listCustomAttributes().isEmpty()){ if(((ITmfCustomAttribute)fEvent).listCustomAttributes().size() != 1) { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTES)); } else { descriptors.add(new ReadOnlyTextPropertyDescriptor(ID_CUSTOM_ATTRIBUTE, NAME_CUSTOM_ATTRIBUTE)); } } return descriptors.toArray(new IPropertyDescriptor[0]); }