auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void write(Record record) throws StageException { try { Date recordTime = getRecordTime(record); RecordWriter writer = getCurrentWriters().get(getBatchTime(), recordTime, record); if (writer != null) { toHdfsRecordsCounter.inc(); toHdfsRecordsMeter.mark(); writer.write(record); getCurrentWriters().release(writer); } else { lateRecordsCounter.inc(); lateRecordsMeter.mark(); switch (lateRecordsAction) { case SEND_TO_ERROR: getContext().toError(record, Errors.HADOOPFS_12, record.getHeader().getSourceId()); break; case SEND_TO_LATE_RECORDS_FILE: RecordWriter lateWriter = getLateWriters().get(getBatchTime(), getBatchTime(), record); lateWriter.write(record); getLateWriters().release(lateWriter); break; default: throw new RuntimeException(Utils.format("Unknown late records action: {}")); } } } catch (IOException ex) { throw new StageException(Errors.HADOOPFS_14, ex.toString(), ex); } catch (StageException ex) { throw new OnRecordErrorException(ex.getErrorCode(), ex.getParams()); } }

Target:
protected void write(Record record) throws StageException { try { Date recordTime = getRecordTime(record); RecordWriter writer = getCurrentWriters().get(getBatchTime(), recordTime, record); if (writer != null) { toHdfsRecordsCounter.inc(); toHdfsRecordsMeter.mark(); writer.write(record); getCurrentWriters().release(writer); } else { lateRecordsCounter.inc(); lateRecordsMeter.mark(); switch (lateRecordsAction) { case SEND_TO_ERROR: getContext().toError(record, Errors.HADOOPFS_12, record.getHeader().getSourceId()); break; case SEND_TO_LATE_RECORDS_FILE: RecordWriter lateWriter = getLateWriters().get(getBatchTime(), getBatchTime(), record); lateWriter.write(record); getLateWriters().release(lateWriter); break; default: throw new RuntimeException(Utils.format("Unknown late records action: {}", lateRecordsAction)); } } } catch (IOException ex) { throw new StageException(Errors.HADOOPFS_14, ex.toString(), ex); } catch (StageException ex) { throw new OnRecordErrorException(ex.getErrorCode(), ex.getParams()); } }
Source:
public void createPartControl(final Composite parent) { super.createPartControl(parent); setGlobalActionBarsToPage((IPageBookViewPage)getDefaultPage()); getSite().getSelectionProvider().addSelectionChangedListener(this); ((IPageBookViewPage)getDefaultPage()).getSite().setSelectionProvider(getViewer()); partActivated(new BreadcrumbWorkbenchPart(getSite())); fContextProviderProxy = new ContextProviderProxy( new IDebugContextProvider[] {fTreeViewerDebugContextProvider, fBreadcrumbPage.getContextProvider()}); DebugUITools.getDebugContextManager().getContextService(getSite().getWorkbenchWindow()).addDebugContextProvider(fContextProviderProxy); createViewModeActions(parent); IPreferenceStore prefStore = DebugUIPlugin.getDefault().getPreferenceStore(); String mode = prefStore.getString(IDebugPreferenceConstants.DEBUG_VIEW_MODE); setViewMode(mode, parent); for (DebugViewModeAction fDebugViewModeAction : fDebugViewModeActions) { fDebugViewModeAction.setChecked(fDebugViewModeAction.getMode().equals(mode)); } createDebugToolBarInViewActions(parent); parent.addControlListener(new ControlListener() { @Override public void controlMoved(ControlEvent e) { } @Override public void controlResized(ControlEvent e) { if (parent.isDisposed()) { return; } if (IDebugPreferenceConstants.DEBUG_VIEW_MODE_AUTO.equals(fCurrentViewMode)) { autoSelectViewPage(parent); } } }); fContextService.addContextManagerListener(this); }

Target:
public void createPartControl(final Composite parent) { super.createPartControl(parent); setGlobalActionBarsToPage((IPageBookViewPage)getDefaultPage()); getSite().getSelectionProvider().addSelectionChangedListener(this); ((IPageBookViewPage)getDefaultPage()).getSite().setSelectionProvider(getViewer()); partActivated(new BreadcrumbWorkbenchPart(getSite())); fContextProviderProxy = new ContextProviderProxy( new IDebugContextProvider[] {fTreeViewerDebugContextProvider, fBreadcrumbPage.getContextProvider()}); DebugUITools.getDebugContextManager().getContextService(getSite().getWorkbenchWindow()).addDebugContextProvider(fContextProviderProxy); createViewModeActions(parent); IPreferenceStore prefStore = DebugUIPlugin.getDefault().getPreferenceStore(); String mode = prefStore.getString(IDebugPreferenceConstants.DEBUG_VIEW_MODE); setViewMode(mode, parent); for (DebugViewModeAction action : fDebugViewModeActions) { action.setChecked(action.getMode().equals(mode)); } createDebugToolBarInViewActions(parent); parent.addControlListener(new ControlListener() { @Override public void controlMoved(ControlEvent e) { } @Override public void controlResized(ControlEvent e) { if (parent.isDisposed()) { return; } if (IDebugPreferenceConstants.DEBUG_VIEW_MODE_AUTO.equals(fCurrentViewMode)) { autoSelectViewPage(parent); } } }); fContextService.addContextManagerListener(this); }
Source:
private String formatValue(Object value) { synchronized ( DateTimeColumnDef.class ) { if ( value instanceof Long && getType().equals("datetime") ) { return formatLong(( Long ) value); } else if ( value instanceof Timestamp ) { int nanos = (( Timestamp ) value).getNanos(); if ( nanos > 0 ) { StringBuilder result = new StringBuilder(); result.append(getDateTimeFormatter().format(( Date ) value)); result.append("."); result.append(String.format("%06d", nanos/1000)); return result.toString(); } else { return getDateTimeFormatter().format(( Timestamp ) value); } } else if ( value instanceof Date ) { return getDateTimeFormatter().format(( Date ) value); } else { return ""; } } }

Target:
protected String formatValue(Object value) { synchronized ( DateTimeColumnDef.class ) { if ( value instanceof Long && getType().equals("datetime") ) { return formatLong(( Long ) value); } else if ( value instanceof Timestamp ) { Timestamp ts = (Timestamp) value; String datetimeAsStr = getDateTimeFormatter().format(ts); return objectWithPrecisionToString(datetimeAsStr, ts, this.columnLength); } else if ( value instanceof Date ) { Timestamp ts = new Timestamp((( Date ) value).getTime()); String dateAsStr = getDateTimeFormatter().format(ts); return objectWithPrecisionToString(dateAsStr, ts, this.columnLength); } else { return ""; } } }
Source:
public void addCommand(String rawLine) { received = true; commands.add(parseCommand(chomp(rawLine))); rawCommands.append(rawLine); }

Target:
public void addCommand(String rawLine) { commands.add(parseCommand(chomp(rawLine))); rawCommands.append(rawLine); }
Source:
private void packageAndAttachDSym(String sdk, String config) throws IOException, NoSuchArchiverException, ArchiverException, XCodeException, MojoExecutionException { final String productName = getProductName(config, sdk); final String fixedProductName = getFixedProductName(productName); final File dsymRoot = new File(XCodeBuildLayout.getAppFolder(getXCodeCompileDirectory(), config, sdk), productName + ".app.dSYM"); if (dsymRoot.canRead()) { final File root = XCodeBuildLayout.getAppFolder(getXCodeCompileDirectory(), config, sdk); Archiver archiver = archiverManager.getArchiver("zip"); File destination = new File(new File(new File(project.getBuild().getDirectory()), config + "-" + sdk), fixedProductName + ".app.dSYM.zip"); archiver.addDirectory(root, new String[] { productName + ".app.dSYM *" }, null); archiver.setDestFile(destination); archiver.createArchive(); getLog().info("dSYM packaged (" + destination + ")"); prepareDSymFileForDeployment(project, config, sdk, destination); } else { getLog().info("dSYM packaging skipped. " + productName + ".app.dSYM does not exists for configuration '" + config + "' and sdk ' " + sdk + "' ."); } }

Target:
private void packageAndAttachDSym(String sdk, String config) throws IOException, NoSuchArchiverException, ArchiverException, XCodeException, MojoExecutionException { final String productName = getProductName(config, sdk); final String fixedProductName = getFixedProductName(productName); final File root = XCodeBuildLayout.getAppFolder(getXCodeCompileDirectory(), config, sdk); final File dsymRoot = new File(root, productName + ".app.dSYM"); if (dsymRoot.canRead()) { Archiver archiver = archiverManager.getArchiver("zip"); File destination = new File(new File(new File(project.getBuild().getDirectory()), config + "-" + sdk), fixedProductName + ".app.dSYM.zip"); archiver.addDirectory(root, new String[] { productName + ".app.dSYM *" }, null); archiver.setDestFile(destination); archiver.createArchive(); getLog().info("dSYM packaged (" + destination + ")"); prepareDSymFileForDeployment(project, config, sdk, destination); } else { if (shouldExistDSym(sdk, config)) { throw new XCodeException( "DSym file should be created but could not be found at the expected location: '" + dsymRoot + "'. In case you prefere not to have dSym files set Xcode properties '" + EffectiveBuildSettings.GCC_GENERATE_DEBUGGING_SYMBOLS + "' and '" + EffectiveBuildSettings.DEBUG_INFORMATION_FORMAT + "' accordingly."); } } }
Source:
public Map<Class<? extends Annotation>, List<FrameworkField>> getAnnotationToFields() { return Collections.unmodifiableMap(fFieldsForAnnotations); }

Target:
public Map<Class<? extends Annotation>, List<FrameworkField>> getAnnotationToFields() { return fFieldsForAnnotations; }
Source:
public ProbeStatus run() { Map<String, BlobProvider> providers = Framework.getService(BlobManager.class).getBlobProviders(); for (Map.Entry<String, BlobProvider> en : providers.entrySet()) { String id = en.getKey(); BlobProvider blobProvider = en.getValue(); BinaryManager bm = blobProvider.getBinaryManager(); if (bm instanceof S3BinaryManager && !((S3BinaryManager) bm).canAccessBucket()) { return ProbeStatus.newFailure("S3BinaryManager cannot access the configured bucket: " + id); } } return ProbeStatus.newSuccess("S3BinaryManager can access the configured buckets"); }

Target:
public ProbeStatus run() { Map<String, BlobProvider> providers = Framework.getService(BlobManager.class).getBlobProviders(); boolean someSuccess = false; for (Map.Entry<String, BlobProvider> en : providers.entrySet()) { String id = en.getKey(); BlobProvider blobProvider = en.getValue(); BinaryManager bm = blobProvider.getBinaryManager(); if (bm == null || !(bm instanceof S3BinaryManager)) { continue; } if (!((S3BinaryManager) bm).canAccessBucket()) { return ProbeStatus.newFailure("S3BinaryManager cannot access the configured bucket: " + id); } someSuccess = true; } if (someSuccess) { return ProbeStatus.newSuccess("S3BinaryManager can access the configured buckets"); } else { return ProbeStatus.newSuccess("No S3BinaryManager bucket configured"); } }
Source:
public CompletableSource apply(Completable upstream) { return Completable.amb( Arrays.asList( upstream, lifecycle .flatMap(Functions.CANCEL_COMPLETABLE) .ignoreElements() ) ); }

Target:
public CompletableSource apply(Completable upstream) { return Completable.ambArray( upstream, lifecycle .flatMap(Functions.CANCEL_COMPLETABLE) .ignoreElements() ); }
Source:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); FileStore s; try { if (Files.exists(dir)) { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } if (!Files.isWritable(dir)) { return FALLBACK_TIMESTAMP_RESOLUTION; } } else { return FALLBACK_TIMESTAMP_RESOLUTION; } CompletableFuture<Optional<Duration>> f = CompletableFuture .supplyAsync(() -> { Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (!lock.tryLock()) { return Optional.empty(); } Optional<Duration> resolution; try { resolution = measureFsTimestampResolution(s, dir); if (resolution.isPresent()) { FileStoreAttributeCache cache = new FileStoreAttributeCache( resolution.get()); attributeCache.put(s, cache); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } } } finally { lock.unlock(); locks.remove(s); } return resolution; }); Optional<Duration> d = f.get(background.get() ? 50 : 5000, TimeUnit.MILLISECONDS); if (d.isPresent()) { return d.get(); } } catch (IOException | InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } catch (TimeoutException e) { } return FALLBACK_TIMESTAMP_RESOLUTION; }

Target:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); FileStore s; try { if (Files.exists(dir)) { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } if (!Files.isWritable(dir)) { return FALLBACK_TIMESTAMP_RESOLUTION; } } else { return FALLBACK_TIMESTAMP_RESOLUTION; } CompletableFuture<Optional<Duration>> f = CompletableFuture .supplyAsync(() -> { Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (!lock.tryLock()) { return Optional.empty(); } Optional<Duration> resolution; FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return Optional .of(c.getFsTimestampResolution()); } try { resolution = measureFsTimestampResolution(s, dir); if (resolution.isPresent()) { FileStoreAttributeCache cache = new FileStoreAttributeCache( resolution.get()); attributeCache.put(s, cache); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } } } finally { lock.unlock(); locks.remove(s); } return resolution; }); Optional<Duration> d = f.get(background.get() ? 50 : 2000, TimeUnit.MILLISECONDS); if (d.isPresent()) { return d.get(); } } catch (IOException | InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } catch (TimeoutException e) { } return FALLBACK_TIMESTAMP_RESOLUTION; }
Source:
private void invokeForKey(AggregationRepository repo, String key, Method method, Object[] args) { try { invokeForKeyOrDie(repo, key, method, args); } catch (RepositoryLockWaitException e) { logger.warn("Failed to process the plugin's '{}' method '{}' invocation: {}!", plugin.getId(), method.getName(), e.getMessage()); repo.confirm(camelContext, key); } catch (RepositoryUnreachableException | RepositoryDirtyWriteAttemptException e) { logger.warn("Failed to process the plugin's '{}' method '{}' invocation: {}!", plugin.getId(), method.getName(), e.getMessage()); } catch (InvocationTargetException e) { logger.trace("Sonar cheat", e); logger.error("Failed to process the plugin's '{}' method '{}' invocation!", plugin.getId(), method.getName(), e.getTargetException()); } catch (Exception e) { logger.error("Failed to process the plugin's '{}' method '{}' invocation!", plugin.getId(), method.getName(), e); } finally { unlockQuietly(repo, key); } }

Target:
private void invokeForKey(AggregationRepository repo, String key, Method method, Object[] args) { try { invokeForKeyOrDie(repo, key, method, args); } catch (RepositoryLockWaitException e) { logger.warn("Failed to process the plugin's '{}' method '{}' invocation: {}!", plugin.getId(), method.getName(), e.getMessage()); repo.confirm(camelContext, key); } catch (RepositoryUnreachableException | RepositoryDirtyWriteAttemptException e) { logger.warn("Failed to process the plugin's '{}' method '{}' invocation: {}!", plugin.getId(), method.getName(), e.getMessage()); } catch (InvocationTargetException e) { logger.error("Failed to process the plugin's '{}' method '{}' invocation!", plugin.getId(), method.getName(), e.getTargetException()); } catch (Exception e) { logger.error("Failed to process the plugin's '{}' method '{}' invocation!", plugin.getId(), method.getName(), e); } finally { unlockQuietly(repo, key); } }
Source:
private static void handleAssignmentStatement(AssignmentStatement assignmentStatement, SubscriptionContext ctx) { if (assignmentStatement.lhsExpressions().get(0).expressions().get(0) instanceof HasSymbol) { Symbol symbol = ((HasSymbol) assignmentStatement.lhsExpressions().get(0).expressions().get(0)).symbol(); if (symbol == null) { return; } String symbolTypeName = SymbolUtils.getTypeName(symbol); if (symbolTypeName != null && symbolTypeName.equals("smtplib.SMTP")) { boolean usesEncryption = symbol.usages().stream().anyMatch(u -> { Tree tree = TreeUtils.firstAncestorOfKind(u.tree(), Tree.Kind.CALL_EXPR); if (tree != null) { Symbol calleeSymbol = ((CallExpression) tree).calleeSymbol(); return calleeSymbol != null && "smtplib.SMTP.starttls".equals(calleeSymbol.fullyQualifiedName()); } return false; }); if (!usesEncryption) { ctx.addIssue(assignmentStatement.assignedValue(), "Make sure STARTTLS is used to upgrade to a secure connection using SSL/TLS."); } } } }

Target:
private static void handleAssignmentStatement(AssignmentStatement assignmentStatement, SubscriptionContext ctx) { if (assignmentStatement.lhsExpressions().size() > 1) { return; } if (assignmentStatement.lhsExpressions().get(0).expressions().get(0) instanceof HasSymbol) { Symbol symbol = ((HasSymbol) assignmentStatement.lhsExpressions().get(0).expressions().get(0)).symbol(); if (symbol == null) { return; } String symbolTypeName = SymbolUtils.getTypeName(symbol); if (symbolTypeName != null && symbolTypeName.equals("smtplib.SMTP")) { boolean usesEncryption = symbol.usages().stream().anyMatch(u -> { Tree tree = TreeUtils.firstAncestorOfKind(u.tree(), Tree.Kind.CALL_EXPR); if (tree != null) { Symbol calleeSymbol = ((CallExpression) tree).calleeSymbol(); return calleeSymbol != null && "smtplib.SMTP.starttls".equals(calleeSymbol.fullyQualifiedName()); } return false; }); if (!usesEncryption) { ctx.addIssue(assignmentStatement.assignedValue(), "Make sure STARTTLS is used to upgrade to a secure connection using SSL/TLS."); } } } }
Source:
public ValidationResult validate(HostSetupNetworksParameters params, List<VdsNetworkInterface> existingInterfaces, BusinessEntityMap<VdsNetworkInterface> existingInterfacesMap){ List<VdsNetworkInterface> nicWithUnmanagedNetworks = filterNicsWithUnmanagedNetworks( existingInterfaces, params.getRemovedUnmanagedNetworks()); try{ for (VdsNetworkInterface unmgmtNic : nicWithUnmanagedNetworks){ validateAttachements(unmgmtNic, params.getNetworkAttachments()); validateLabels(unmgmtNic, params.getLabels()); validateBonds(unmgmtNic, params.getBonds(), existingInterfacesMap); validateRemovedLabels(unmgmtNic, params.getRemovedLabels()); } }catch(ValidationException validationException){ return validationException.getValidationResult(); } return ValidationResult.VALID; }

Target:
public ValidationResult validate(HostSetupNetworksParameters params, List<VdsNetworkInterface> existingInterfaces, BusinessEntityMap<VdsNetworkInterface> existingInterfacesMap){ List<VdsNetworkInterface> nicsWithUnmanagedNetworks = filterNicsWithUnmanagedNetworks( existingInterfaces, params.getRemovedUnmanagedNetworks()); for (VdsNetworkInterface unmgmtNic : nicsWithUnmanagedNetworks){ ValidationResult result = validateAttachements(unmgmtNic, params.getNetworkAttachments()); if (!result.isValid()) { return result; } result = validateLabels(unmgmtNic, params.getLabels()); if (!result.isValid()) { return result; } result = validateBonds(unmgmtNic, params.getBonds(), existingInterfacesMap); if (!result.isValid()) { return result; } } return ValidationResult.VALID; }
Source:
PyClassDefTree getParentClassDef(Tree current) { if(current == null) { return null; } else if (current.is(Tree.Kind.CLASSDEF)) { return (PyClassDefTree) current; } else { return getParentClassDef(current.parent()); } }

Target:
private static PyClassDefTree getParentClassDef(Tree current) { while (current != null) { if (current.is(Tree.Kind.CLASSDEF)) { return (PyClassDefTree) current; } current = current.parent(); } return null; }
Source:
private void signJar(File outputFile) { SecurityLogger.audit("Signing exported data. file: [{}]", outputFile.getName()); console.println("Signing zip file..."); Instant start = Instant.now(); try { String alias = System.getProperty(SystemBaseUrl.EXTERNAL_HOST); String password = System.getProperty("javax.net.ssl.keyStorePassword"); byte[] signature = signer.createDigitalSignature(new FileInputStream(outputFile), alias, password); if (signature != null) { String signatureFilepath = Paths.get(System.getProperty("ddf.home"), FILE_NAMER.apply("sig")).toString(); FileUtils.writeByteArrayToFile(new File(signatureFilepath), signature); console.println("zip file signed in: " + getFormattedDuration(start)); } else { console.println("An error occurred while signing export"); } } catch (CatalogCommandRuntimeException | IOException e) { String message = "Unable to sign export of data"; LOGGER.debug(message, e); console.println(message); } }

Target:
private void signJar(File outputFile) { SecurityLogger.audit("Signing exported data. file: [{}]", outputFile.getName()); console.println("Signing zip file..."); Instant start = Instant.now(); try (InputStream inputStream = new FileInputStream(outputFile)) { String alias = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty(SystemBaseUrl.EXTERNAL_HOST)); String password = AccessController.doPrivileged( (PrivilegedAction<String>) () -> System.getProperty("javax.net.ssl.keyStorePassword")); byte[] signature = signer.createDigitalSignature(inputStream, alias, password); if (signature != null) { String signatureFilepath = Paths.get(System.getProperty("ddf.home"), FILE_NAMER.apply("sig")).toString(); FileUtils.writeByteArrayToFile(new File(signatureFilepath), signature); console.println("zip file signed in: " + getFormattedDuration(start)); } else { console.println("An error occurred while signing export"); } } catch (CatalogCommandRuntimeException | IOException e) { String message = "Unable to sign export of data"; LOGGER.debug(message, e); console.println(message); } }
Source:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList(Tree.Kind.METHOD); }

Target:
public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.METHOD, Tree.Kind.CONSTRUCTOR); }
Source:
public void start(ComponentContext context) { Collection<AvroReplacementDescriptor> replacements = replacementDescriptors.getDescriptors(); Collection<AvroSchemaFactoryDescriptor> descriptors = schemaFactoryDescriptors.getDescriptors(); AvroSchemaFactoryServiceImpl schemaFactoryService = new AvroSchemaFactoryServiceImpl(replacements); AvroSchemaFactoryContext avroContext = schemaFactoryService.createContext(); Map<Class<?>, Class<AvroSchemaFactory<?>>> factories = new HashMap<>(descriptors.size()); for (AvroSchemaFactoryDescriptor d : descriptors) { try { Class<Object> type = (Class<Object>) Class.forName(d.type); Class<AvroSchemaFactory<?>> factory = (Class<AvroSchemaFactory<?>>) Class.forName(d.clazz); Constructor<AvroSchemaFactory<?>> constructor = factory.getConstructor(AvroSchemaFactoryContext.class); constructor.newInstance(avroContext); factories.put(type, factory); } catch (ReflectiveOperationException | SecurityException e) { log.error(e); } } schemaFactoryService.setFactories(factories); this.schemaFactoryService = schemaFactoryService; schemaStoreService = new AvroSchemaStoreServiceImpl(); for (AvroSchemaDescriptor descriptor : schemaDescriptors.getDescriptors()) { URL url = context.getRuntimeContext().getResource(descriptor.file); try (InputStream stream = url == null ? null : url.openStream()) { if (stream == null) { log.error(String.format("Could not load stream for file %s.", descriptor.file)); return; } schemaStoreService.addSchema(new Schema.Parser().parse(stream)); } catch (IOException e) { log.error(e); } } }

Target:
public void start(ComponentContext context) { buildSchemaFactoryService(); buildSchemaStoreService(context); }
Source:
Definitions toDefinitions(final InputStream inputStream) { try (InputStreamReader reader = toInputStreamReader(inputStream)) { return marshaller.unmarshal(reader); } catch (IOException ioe) { } finally { try { inputStream.close(); } catch (IOException ioe) { } } return null; }

Target:
Definitions toDefinitions(final InputStream inputStream) { try (InputStream inputStreamAutoClosable = inputStream; InputStreamReader reader = toInputStreamReader(inputStreamAutoClosable)) { return marshaller.unmarshal(reader); } catch (IOException ioe) { } return null; }
Source:
public void mergeEmptyUserMetadata(ProjectMetadata metadata) { if (metadata == null) return; JSONArray userMetadataPreference = null; JSONArray jsonObjArray = metadata.getUserMetadata(); initDispaly(jsonObjArray); try { String userMeta = (String)_preferenceStore.get(PreferenceStore.USER_METADATA_KEY); if (userMeta == null) return; userMetadataPreference = new JSONArray(userMeta); } catch (JSONException e1) { logger.error(ExceptionUtils.getFullStackTrace(e1)); } if (userMetadataPreference == null) { logger.warn("wrong definition of userMetadata format. Please use form [{\"name\": \"client name\", \"display\":true}, {\"name\": \"progress\", \"display\":false}]"); return; } for (int index = 0; index < userMetadataPreference.length(); index++) { try { boolean found = false; JSONObject placeHolderJsonObj = userMetadataPreference.getJSONObject(index); if (!isValidUserMetadataDefinition(placeHolderJsonObj)) { logger.warn("Skipped invalid user metadata definition" + placeHolderJsonObj.toString()); continue; } for (int i = 0; i < jsonObjArray.length(); i++) { JSONObject jsonObj = jsonObjArray.getJSONObject(i); if (jsonObj.getString("name").equals(placeHolderJsonObj.getString("name"))) { found = true; jsonObj.put("display", placeHolderJsonObj.get("display")); break; } } if (!found) { placeHolderJsonObj.put("value", ""); metadata.getUserMetadata().put(placeHolderJsonObj); logger.info("Put the placeholder for project {}", placeHolderJsonObj.getString("name"), metadata.getName()); } } catch (JSONException e) { logger.warn("Exception when mergeEmptyUserMetadata",e); } } }

Target:
public void mergeEmptyUserMetadata(ProjectMetadata metadata) { if (metadata == null) return; JSONArray userMetadataPreference = null; JSONArray jsonObjArray = metadata.getUserMetadata(); initDisplay(jsonObjArray); try { String userMeta = (String)_preferenceStore.get(PreferenceStore.USER_METADATA_KEY); if (userMeta == null) return; userMetadataPreference = new JSONArray(userMeta); } catch (JSONException e1) { logger.warn("wrong definition of userMetadata format. Please use form [{\"name\": \"client name\", \"display\":true}, {\"name\": \"progress\", \"display\":false}]"); logger.error(ExceptionUtils.getFullStackTrace(e1)); } for (int index = 0; index < userMetadataPreference.length(); index++) { try { boolean found = false; JSONObject placeHolderJsonObj = userMetadataPreference.getJSONObject(index); if (!isValidUserMetadataDefinition(placeHolderJsonObj)) { logger.warn("Skipped invalid user metadata definition" + placeHolderJsonObj.toString()); continue; } for (int i = 0; i < jsonObjArray.length(); i++) { JSONObject jsonObj = jsonObjArray.getJSONObject(i); if (jsonObj.getString("name").equals(placeHolderJsonObj.getString("name"))) { found = true; jsonObj.put("display", placeHolderJsonObj.get("display")); break; } } if (!found) { placeHolderJsonObj.put("value", ""); metadata.getUserMetadata().put(placeHolderJsonObj); logger.info("Put the placeholder for project {}", placeHolderJsonObj.getString("name"), metadata.getName()); } } catch (JSONException e) { logger.warn("Exception when mergeEmptyUserMetadata",e); } } }
Source:
CommandExecutor(CommandCoordinatorImpl coco) { this.coco = coco; SchedulerUtil scheduler = Injector.get(SchedulerUtilQuartzImpl.class); scheduler.scheduleAFixedDelayJob(this, "invokeCallbackMethods", new Class[]{}, new Object[]{}, 1, 1, TimeUnit.SECONDS); }

Target:
CommandExecutor(CommandCoordinatorImpl coco) { this.coco = coco; SchedulerUtil scheduler = Injector.get(SchedulerUtilQuartzImpl.class); scheduler.scheduleAFixedDelayJob(this, "invokeCallbackMethods", new Class[]{}, new Object[]{}, POLLING_RATE, POLLING_RATE, TimeUnit.SECONDS); }
Source:
protected LogLag getLagForPartition(String name, int partition, String group) { long pos; File path = new File(basePath.toFile(), name); try (ChronicleLogOffsetTracker offsetTracker = new ChronicleLogOffsetTracker(path.toString(), partition, group)) { pos = offsetTracker.readLastCommittedOffset(); } ChronicleLogAppender appender = (ChronicleLogAppender) getAppender(name); if (pos == 0) { pos = appender.firstOffset(partition); } long end = appender.endOffset(partition); long lag = appender.countMessages(partition, pos, end); long firstOffset = appender.firstOffset(partition); long endMessages = appender.countMessages(partition, firstOffset, end); return new LogLag(pos, end, lag, endMessages); }

Target:
protected LogLag getLagForPartition(String name, int partition, String group) { long pos; Path path = basePath.resolve(name); try (ChronicleLogOffsetTracker offsetTracker = new ChronicleLogOffsetTracker(path.toString(), partition, group)) { pos = offsetTracker.readLastCommittedOffset(); } ChronicleLogAppender appender = (ChronicleLogAppender) getAppender(name); if (pos == 0) { pos = appender.firstOffset(partition); } long end = appender.endOffset(partition); long lag = appender.countMessages(partition, pos, end); long firstOffset = appender.firstOffset(partition); long endMessages = appender.countMessages(partition, firstOffset, end); return new LogLag(pos, end, lag, endMessages); }
Source:
protected void trackString(GrammarAST t) { if ( currentRuleName==null && grammar.type==Grammar.LEXER ) { ErrorManager.grammarError(ErrorManager.MSG_CANNOT_ALIAS_TOKENS_IN_LEXER, grammar, t.token, t.getText()); return; } if ( grammar.getGrammarIsRoot() && grammar.type==Grammar.PARSER && grammar.getTokenType(t.getText())== Label.INVALID ) { ErrorManager.grammarError(ErrorManager.MSG_LITERAL_NOT_ASSOCIATED_WITH_LEXER_RULE, grammar, t.token, t.getText()); } if ( grammar.type==Grammar.LEXER ) { return; } String tokenVocab = (String) grammar.getOption("tokenVocab"); boolean hasTokenVocabAndIsParserOrCombined = tokenVocab != null && (grammar.type == Grammar.PARSER || grammar.type == Grammar.COMBINED); if ( (currentRuleName==null || Character.isLowerCase(currentRuleName.charAt(0))) && (hasTokenVocabAndIsParserOrCombined || grammar.getTokenType(t.getText())==Label.INVALID )) { stringLiterals.put(t.getText(), UNASSIGNED_IN_PARSER_RULE); } }

Target:
protected void trackString(GrammarAST t) { if ( currentRuleName==null && grammar.type==Grammar.LEXER ) { ErrorManager.grammarError(ErrorManager.MSG_CANNOT_ALIAS_TOKENS_IN_LEXER, grammar, t.token, t.getText()); return; } if ( grammar.getGrammarIsRoot() && grammar.type==Grammar.PARSER && grammar.getTokenType(t.getText())== Label.INVALID ) { ErrorManager.grammarError(ErrorManager.MSG_LITERAL_NOT_ASSOCIATED_WITH_LEXER_RULE, grammar, t.token, t.getText()); } if ( grammar.type==Grammar.LEXER ) { return; } String tokenVocab = (String) grammar.getOption("tokenVocab"); boolean hasTokenVocabAndIsCombinedParser = tokenVocab != null && grammar.type == Grammar.COMBINED; if ( (currentRuleName==null || Character.isLowerCase(currentRuleName.charAt(0))) && (hasTokenVocabAndIsCombinedParser || grammar.getTokenType(t.getText())==Label.INVALID )) { stringLiterals.put(t.getText(), UNASSIGNED_IN_PARSER_RULE); } }
Source:
public boolean isReviewer(ReviewDb db, @Nullable ChangeData cd) throws OrmException { if (getCurrentUser().isIdentifiedUser()) { Collection<Account.Id> results; if (cd != null) { results = cd.reviewers(Providers.of(db)).values(); } else { results = approvalsUtil.getReviewers(db, change.getId()).values(); } IdentifiedUser user = (IdentifiedUser) getCurrentUser(); return results.contains(user.getAccountId()); } return false; }

Target:
public boolean isReviewer(ReviewDb db, @Nullable ChangeData cd) throws OrmException { if (getCurrentUser().isIdentifiedUser()) { Collection<Account.Id> results = cd != null ? cd.reviewers(Providers.of(db)).values() : approvalsUtil.getReviewers(db, change.getId()).values(); IdentifiedUser user = (IdentifiedUser) getCurrentUser(); return results.contains(user.getAccountId()); } return false; }
Source:
private void scheduleJobs(long regularInterval, long initialInterval) { executor.scheduleWithFixedDelay(() -> refresh(), initialInterval, regularInterval, TimeUnit.MINUTES); }

Target:
private void scheduleJobs(long regularInterval, long initialInterval) { executor.scheduleWithFixedDelay(this::refresh, initialInterval, regularInterval, TimeUnit.MINUTES); }
Source:
private Direction getOpposite(){ return opposite; }

Target:
public Direction getOpposite() { return this.opposite; }
Source:
public void testPartialSpecializationResolution_525288() throws Exception { CPPASTNameBase.sAllowNameComputation = true; String code = getAboveComment(); IFile file = importFile("testBug525288.cpp", code); int offset = code.indexOf("a0") - 5; IASTNode target = testF3(file, offset); assertInstance(target, IASTName.class); assertEquals("A<0>", ((IASTName) target).toString()); offset = code.indexOf("a1") - 5; target = testF3(file, offset); assertInstance(target, IASTName.class); assertEquals("A", ((IASTName) target).toString()); offset = code.indexOf("a1") - 7; target = testF3(file, offset); }

Target:
public void testPartialSpecializationResolution_525288() throws Exception { CPPASTNameBase.sAllowNameComputation = true; String code = getAboveComment(); IFile file = importFile("testBug525288.cpp", code); int offset = code.indexOf("a0") - 5; IASTNode target = testF3(file, offset); assertInstance(target, IASTName.class); assertEquals("A<0>", ((IASTName) target).toString()); offset = code.indexOf("a1") - 5; target = testF3(file, offset); assertInstance(target, IASTName.class); assertEquals("A", ((IASTName) target).toString()); }
Source:
public SecretClientBuilder vaultUrl(String vaultUrl) { try { this.vaultUrl = new URL(vaultUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException( "The Azure Key Vault endpoint url is malformed.")); } return this; }

Target:
public SecretClientBuilder vaultUrl(String vaultUrl) { try { this.vaultUrl = new URL(vaultUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException( "The Azure Key Vault url is malformed.", e)); } return this; }
Source:
public Map<?, ?> merge(Map<?, ?>... items) { if (ArrayUtils.isEmpty(items)) { return Collections.emptyMap(); } Map<Object, Object> result = new HashMap<Object, Object>(); Arrays.stream(items).filter(Objects::nonNull).forEach(item -> result.putAll(item)); return result; }

Target:
public Map<?, ?> merge(Map<?, ?>... items) { if (ArrayUtils.isEmpty(items)) { return Collections.emptyMap(); } Map<Object, Object> result = Arrays.stream(items).filter(Objects::nonNull).map(Map::entrySet) .flatMap(Set::stream).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return result; }
Source:
protected BufferedMergeJoinIterator(Iterator<ExecRow> sourceIterator) throws StandardException { this.sourceIterator = Iterators.peekingIterator(sourceIterator);; joinOperation = getOperation(); initialized = true; fillBuffer(); if (bufferedRowList.isEmpty()) { mergeJoinIterator = Collections.emptyIterator(); } }

Target:
protected BufferedMergeJoinIterator(Iterator<ExecRow> sourceIterator) throws StandardException { this.sourceIterator = Iterators.peekingIterator(sourceIterator); joinOperation = getOperation(); initialized = true; fillBuffer(); if (bufferedRowList.isEmpty()) { mergeJoinIterator = Collections.emptyIterator(); } }
Source:
public void test_FhirResourceGetHistory() throws Exception { FhirResourcePatch.fhirResourcePatch( fhirResourceName, "[{\"op\": \"add\", \"path\": \"/active\", \"value\": false}]"); String versionId; Matcher idMatcher = Pattern.compile("\"versionId\": \"(.*)\"").matcher(bout.toString()); assertTrue(idMatcher.find()); versionId = idMatcher.group(1); FhirResourceGetHistory.fhirResourceGetHistory(fhirResourceName, versionId); String output = bout.toString(); assertThat(output, containsString("FHIR resource history list retrieved:")); }

Target:
public void test_FhirResourceGetHistory() throws Exception { JsonObject json = new JsonObject(); json.add("op", new JsonPrimitive("add")); json.add("path", new JsonPrimitive("/active")); json.add("value", new JsonPrimitive(false)); JsonArray jarray = new JsonArray(); jarray.add(json); FhirResourcePatch.fhirResourcePatch(fhirResourceName, jarray.toString()); String versionId; Matcher idMatcher = Pattern.compile("\"versionId\": \"(.*)\"").matcher(bout.toString()); assertTrue(idMatcher.find()); versionId = idMatcher.group(1); FhirResourceGetHistory.fhirResourceGetHistory(fhirResourceName, versionId); String output = bout.toString(); assertThat(output, containsString("FHIR resource history list retrieved:")); }
Source:
void prepare() throws IOException { }

Target:
public void prepare() throws IOException { }
Source:
public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) { checkIfOpen(); if (rowColumns.size() == 0) { return Collections.emptyMap(); } ParallelSnapshotScanner pss = new ParallelSnapshotScanner(rowColumns, env, startTs, stats); Map<Bytes, Map<Column, Bytes>> ret = pss.scan(); Map<RowColumn, Bytes> bet = new HashMap<>(); for (Entry<Bytes, Map<Column, Bytes>> entry : ret.entrySet()) { updateColumnsRead(entry.getKey(), entry.getValue().keySet()); for (Entry<Column, Bytes> cols : entry.getValue().entrySet()) { bet.put(new RowColumn(cols.getValue()), cols.getValue()); } } return bet; }

Target:
public Map<RowColumn, Bytes> get(Collection<RowColumn> rowColumns) { checkIfOpen(); if (rowColumns.size() == 0) { return Collections.emptyMap(); } ParallelSnapshotScanner pss = new ParallelSnapshotScanner(rowColumns, env, startTs, stats); Map<Bytes, Map<Column, Bytes>> scan = pss.scan(); Map<RowColumn, Bytes> ret = new HashMap<>(); for (Entry<Bytes, Map<Column, Bytes>> entry : scan.entrySet()) { updateColumnsRead(entry.getKey(), entry.getValue().keySet()); for (Entry<Column, Bytes> colVal : entry.getValue().entrySet()) { ret.put(new RowColumn(entry.getKey(), colVal.getKey()), colVal.getValue()); } } return ret; }
Source:
protected VirtualMachineMO findVmOnDatacenter(VmwareContext context, VmwareHypervisorHost hyperHost, VolumeTO vol) throws Exception { DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); if (dcMo.getMor() == null) { String msg = "Unable to find VMware DC"; s_logger.error(msg); throw new CloudRuntimeException(msg); } VirtualMachineMO vmMo = dcMo.findVm(vol.getPath()); return vmMo; }

Target:
protected VirtualMachineMO findVmOnDatacenter(VmwareContext context, VmwareHypervisorHost hyperHost, VolumeTO vol) throws Exception { DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); if (dcMo.getMor() == null) { String msg = "Unable to find VMware DC"; s_logger.error(msg); throw new CloudRuntimeException(msg); } return dcMo.findVm(vol.getPath()); }
Source:
protected Map<String, ServerImpl> resolveExternalServers(String machineName) { Map<String, ServerImpl> serverMap = new HashMap<>(); serverMap.putAll(nativeServerResolver.resolveExternalServers(machineName)); serverMap.putAll( configMaps .get(machineName) .stream() .map(this::fillGatewayServers) .flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (s1, s2) -> s2))); return serverMap; }

Target:
public Map<String, ServerImpl> resolveExternalServers(String machineName) { Map<String, ServerImpl> serverMap = new HashMap<>(); serverMap.putAll(nativeServerResolver.resolveExternalServers(machineName)); serverMap.putAll( configMaps .get(machineName) .stream() .map(this::fillGatewayServers) .flatMap(m -> m.entrySet().stream()) .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (s1, s2) -> s2))); return serverMap; }
Source:
public String getNamespaceString() { if (namespace().isPresent()) { String namespace = namespace().get(); keyValueService().namespace().ifPresent(kvsNamespace -> Preconditions.checkState(kvsNamespace.equals(namespace), "If present, keyspace/dbName/sid config should be the same as the" + " atlas root-level namespace config.")); timelock().ifPresent(timelock -> timelock.client().ifPresent(client -> Preconditions.checkState(client.equals(namespace), "If present, the TimeLock client config should be the same as the" + " atlas root-level namespace config."))); return namespace; } else if (!(keyValueService() instanceof InMemoryAtlasDbConfig)) { Preconditions.checkState(keyValueService().namespace().isPresent(), "Either the atlas root-level namespace" + " or the keyspace/dbName/sid config needs to be set."); String keyValueServiceNamespace = keyValueService().namespace().get(); if (timelock().isPresent()) { TimeLockClientConfig timeLockConfig = timelock().get(); Preconditions.checkState(timeLockConfig.client().isPresent(), "Either the atlas root-level namespace config or the TimeLock client config" + " should be present."); Preconditions.checkState(timeLockConfig.client().equals(Optional.of(keyValueServiceNamespace)), "AtlasDB refused to start, in order to avoid potential data corruption." + " Please contact AtlasDB support to remediate this. Specific steps are required;" + " DO NOT ATTEMPT TO FIX THIS YOURSELF."); } return keyValueServiceNamespace; } else if (timelock().isPresent()) { Preconditions.checkState(timelock().get().client().isPresent(), "For InMemoryKVS, the TimeLock client should not be empty"); return timelock().get().client().get(); } return UNSPECIFIED_NAMESPACE; }

Target:
public String getNamespaceString() { if (namespace == null) { namespace = checkNamespaceConfigAndGetNamespace(); } return namespace; }
Source:
public void listModifyingBatchEnsureOnlyModifying() { Date startDate = createDate(2010, 1, 1); Date endDate = createDate(2050, 1, 1); Entitlement ent = setUpModifyingEntitlements(startDate, endDate, 3, "1"); Date startDate1 = createDate(2010, 1, 1); Date endDate1 = createDate(2050, 1, 1); Entitlement ent1 = setUpModifyingEntitlements(startDate1, endDate1, 2, "2"); Date startDate2 = createDate(2030, 1, 1); Date endDate2 = createDate(2040, 1, 1); Entitlement ent2 = setUpModifyingEntitlements(startDate2, endDate2, 2, "3"); Set<Entitlement> ents = entitlementCurator.listModifying(Arrays.asList(ent, ent1)); assertEquals(5, ents.size()); assertTrue(!ents.contains(ent)); assertTrue(!ents.contains(ent1)); assertTrue(!ents.contains(ent2)); }

Target:
public void listModifyingBatchEnsureOnlyModifying() { Date startDate = createDate(2010, 1, 1); Date endDate = createDate(2050, 1, 1); Entitlement ent = setUpModifyingEntitlements(startDate, endDate, 3, "1"); Date startDate1 = createDate(2010, 1, 1); Date endDate1 = createDate(2050, 1, 1); Entitlement ent1 = setUpModifyingEntitlements(startDate1, endDate1, 2, "2"); Date startDate2 = createDate(2030, 1, 1); Date endDate2 = createDate(2040, 1, 1); Entitlement ent2 = setUpModifyingEntitlements(startDate2, endDate2, 2, "3"); Set<Entitlement> ents = entitlementCurator.listModifying(Arrays.asList(ent, ent1)); assertEquals(5, ents.size()); assertThat(ents, not(hasItems(ent))); assertThat(ents, not(hasItems(ent1))); assertThat(ents, not(hasItems(ent2))); }
Source:
public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) { return ConfigurationBuilder .begin() .addRule() .when(FileContent.matches("{ip}").inFileNamed("{*}.{type}")) .perform(new AbstractIterationOperation<FileLocationModel>() { public void perform(GraphRewrite event, EvaluationContext context, FileLocationModel payload) { if (InetAddressValidator.getInstance().isValid(payload.getSourceSnippit())) { if (ignoreLine(event.getGraphContext(), payload)) { return; } if (payload.getFile() instanceof SourceFileModel) ((SourceFileModel) payload.getFile()).setGenerateSourceReport(true); HardcodedIPLocationModel location = GraphService.addTypeToModel(event.getGraphContext(), payload, HardcodedIPLocationModel.class); location.setRuleID(((Rule) context.get(Rule.class)).getId()); location.setTitle("Hard-coded IP Address Detected"); StringBuilder hintBody = new StringBuilder("**Hard-coded IP: "); hintBody.append(payload.getSourceSnippit()); hintBody.append("**"); hintBody.append("\n\n"); hintBody.append("When migrating environments, hard-coded IP addresses may need to be modified or eliminated."); location.setHint(hintBody.toString()); location.setIssueCategory(IssueCategoryRegistry.loadFromGraph(context, "cloud-mandatory"); location.setEffort(0); } } }) .where("ip").matches(IP_PATTERN) .where("type").matches("java|properties|xml") .withId(getClass().getSimpleName()); }

Target:
public Configuration getConfiguration(RuleLoaderContext ruleLoaderContext) { return ConfigurationBuilder .begin() .addRule() .when(FileContent.matches("{ip}").inFileNamed("{*}.{type}")) .perform(new AbstractIterationOperation<FileLocationModel>() { public void perform(GraphRewrite event, EvaluationContext context, FileLocationModel payload) { if (InetAddressValidator.getInstance().isValid(payload.getSourceSnippit())) { if (ignoreLine(event.getGraphContext(), payload)) { return; } if (payload.getFile() instanceof SourceFileModel) ((SourceFileModel) payload.getFile()).setGenerateSourceReport(true); HardcodedIPLocationModel location = GraphService.addTypeToModel(event.getGraphContext(), payload, HardcodedIPLocationModel.class); location.setRuleID(((Rule) context.get(Rule.class)).getId()); location.setTitle("Hard-coded IP Address Detected"); StringBuilder hintBody = new StringBuilder("**Hard-coded IP: "); hintBody.append(payload.getSourceSnippit()); hintBody.append("**"); hintBody.append("\n\n"); hintBody.append("When migrating environments, hard-coded IP addresses may need to be modified or eliminated."); location.setHint(hintBody.toString()); location.setIssueCategory(IssueCategoryRegistry.loadFromGraph(event.getGraphContext(), IssueCategoryRegistry.CLOUD_MANDATORY)); location.setEffort(1); } } }) .where("ip").matches(IP_PATTERN) .where("type").matches("java|properties|xml") .withId(getClass().getSimpleName()); }
Source:
protected void displayViewStateText(EnumSet<LayerViewStatus> layerViewStatus) { List<String> stringList = new ArrayList<String>(); if (layerViewStatus.contains(LayerViewStatus.ACTIVE)) { stringList.add(getString(R.string.activeStateTextViewString)); } if (layerViewStatus.contains(LayerViewStatus.ERROR)) { stringList.add(getString(R.string.errorStateTextViewString)); } if (layerViewStatus.contains(LayerViewStatus.LOADING)) { stringList.add(getString(R.string.loadingStateTextViewString)); } if (layerViewStatus.contains(LayerViewStatus.NOT_VISIBLE)) { stringList.add(getString(R.string.notVisibleStateTextViewString)); } if (layerViewStatus.contains(LayerViewStatus.OUT_OF_SCALE)) { stringList.add(getString(R.string.outOfScaleStateTextViewString)); } if (layerViewStatus.contains(LayerViewStatus.WARNING)) { stringList.add(getString(R.string.warningStateTextViewString)); } activeStateTextView.setText(TextUtils.join(", ", stringList)); }

Target:
protected void displayViewStateText(EnumSet<LayerViewStatus> layerViewStatus) { List<String> stringList = new ArrayList<String>(); if (layerViewStatus.contains(LayerViewStatus.ACTIVE)) { stringList.add(getString(R.string.active_state)); } if (layerViewStatus.contains(LayerViewStatus.ERROR)) { stringList.add(getString(R.string.error_state)); } if (layerViewStatus.contains(LayerViewStatus.LOADING)) { stringList.add(getString(R.string.loading_state)); } if (layerViewStatus.contains(LayerViewStatus.NOT_VISIBLE)) { stringList.add(getString(R.string.not_visible_state)); } if (layerViewStatus.contains(LayerViewStatus.OUT_OF_SCALE)) { stringList.add(getString(R.string.out_of_scale_state)); } if (layerViewStatus.contains(LayerViewStatus.WARNING)) { stringList.add(getString(R.string.warning_state)); } activeStateTextView.setText(TextUtils.join(", ", stringList)); }