auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void updateRepoState(IFileBuffer buffer) { IFile file = getResource(buffer); if (file != null) { return; } Repository repo = getRepository(buffer); if (repo == null || repo.isBare()) { return; } IPath relativePath = getRelativePath(repo, buffer); if (relativePath == null) { return; } IndexDiffCacheEntry diffEntry = Activator .getDefault().getIndexDiffCache() .getIndexDiffCacheEntry(repo); if (diffEntry != null) { if (GITIGNORE_NAME.equals(relativePath.lastSegment())) { diffEntry.refresh(); } else { diffEntry.refreshFiles( Collections.singleton(relativePath.toString())); } } }

Target:
private void updateRepoState(IFileBuffer buffer) { IFile file = getResource(buffer); if (file != null) { return; } Repository repo = getRepository(buffer); if (repo == null || repo.isBare()) { return; } IPath relativePath = getRelativePath(repo, buffer); if (relativePath == null) { return; } IndexDiffCacheEntry diffEntry = getIndexDiffCacheEntry(repo); if (diffEntry != null) { if (GITIGNORE_NAME.equals(relativePath.lastSegment())) { diffEntry.refresh(); } else { diffEntry.refreshFiles( Collections.singleton(relativePath.toString())); } } }
Source:
public static Map<String, String> buildData(long userId, Event event, Position position) { Map<String, String> data = new HashMap<>(); try { if (event != null) { String eventJson = Context.getObjectMapper().writeValueAsString(event); data.put("eventJson", eventJson); } if (position != null) { String positionJson = Context.getObjectMapper().writeValueAsString(position); data.put("positionJson", positionJson); } } catch (JsonProcessingException e) { LOGGER.warn("Notification JSON formatting error", e); } return data; }

Target:
public static Map<String, String> buildData(long userId, Event event, Position position) { Map<String, String> data = new HashMap<>(); try { if (event != null) { data.put(KEY_DATA_EVENT, Context.getObjectMapper().writeValueAsString(event)); } if (position != null) { data.put(KEY_DATA_POSITION, Context.getObjectMapper().writeValueAsString(position)); } } catch (JsonProcessingException e) { LOGGER.warn("Notification JSON formatting error", e); } return data; }
Source:
public void done() throws CommitException { commit(); close(); }

Target:
public void done() throws CommitException { try { commit(); } finally { close(); } }
Source:
protected void clientInit() { configuration.setApi(new OrcidApi20()); configuration.setProfileDefinition(new OrcidProfileDefinition()); configuration.setTokenAsHeader(true); configuration.setHasBeenCancelledFactory(ctx -> { final Optional<String> error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final Optional<String> errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION); if ("access_denied".equals(error.orElse(null)) && "User denied access".equals(errorDescription.orElse(null))) { return true; } else { return false; } }); super.clientInit(); }

Target:
protected void clientInit() { configuration.setApi(new OrcidApi20()); configuration.setProfileDefinition(new OrcidProfileDefinition()); configuration.setTokenAsHeader(true); configuration.setHasBeenCancelledFactory(ctx -> { final Optional<String> error = ctx.getRequestParameter(OAuthCredentialsException.ERROR); final Optional<String> errorDescription = ctx.getRequestParameter(OAuthCredentialsException.ERROR_DESCRIPTION); return error.map(e -> "access_denied".equals(e)).orElse(false) && errorDescription.map(e -> "User denied access".equals(e)).orElse(false); }); super.clientInit(); }
Source:
private Contentlet createContentlet() throws DotDataException, DotSecurityException { final ContentletDataGen contentletDataGen = new ContentletDataGen( contentTypeAPI.find("Youtube").id()); Contentlet contentlet = contentletDataGen.next(); contentlet.setStringProperty("widgetTitle", "New YouTube Content"); contentlet.setStringProperty("url", "new-youtube-content"); contentlet = contentletDataGen.persist(contentlet); return contentlet; }

Target:
private Contentlet createContentlet() throws DotDataException, DotSecurityException { return new ContentletDataGen(contentTypeAPI.find("Youtube").id()) .setProperty("widgetTitle", "New YouTube Content") .setProperty("url", "new-youtube-content").nextPersisted(); }
Source:
public void deleteRow(final String tableName, final Object rowKey) { if (tableName == null || rowKey == null) { throw new IllegalArgumentException("Can't delete a row without having tableName or rowKey"); } byte[] rowKeyAsByteArray = getValueAsByteArray(rowKey); if (rowKeyAsByteArray.length > 0) { try (final Table table = _connection.getTable(TableName.valueOf(tableName))) { if (rowExists(table, rowKeyAsByteArray)) { table.delete(new Delete(rowKeyAsByteArray)); } else { logger.warn("Rowkey with value doesn't exist in the table", rowKey.toString()); } } catch (IOException e) { throw new MetaModelException(e); } } else { logger.info("Have not deleted a row, which has an empty (\"\") rowKey."); } }

Target:
public void deleteRow(final String tableName, final Object rowKey) { if (tableName == null || rowKey == null) { throw new IllegalArgumentException("Can't delete a row without having tableName or rowKey"); } byte[] rowKeyAsByteArray = getValueAsByteArray(rowKey); if (rowKeyAsByteArray.length > 0) { try (final Table table = _connection.getTable(TableName.valueOf(tableName))) { if (rowExists(table, rowKeyAsByteArray)) { table.delete(new Delete(rowKeyAsByteArray)); } else { logger.warn("Rowkey with value doesn't exist in the table", rowKey.toString()); } } catch (IOException e) { throw new MetaModelException(e); } } else { throw new IllegalArgumentException("Can't delete a row without an empty rowKey."); } }
Source:
private byte[] readKeyData() throws IOException { final File keyFile = new File(mContext.getDir(mContext.getPackageName(), Context.MODE_PRIVATE), ADALKS); if (!keyFile.exists()) { throw new IOException("Key file to read does not exist"); } Logger.v(TAG, "Reading key data from a file"); final InputStream in = new FileInputStream(keyFile); try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } finally { in.close(); } }

Target:
private byte[] readKeyData() throws IOException { final File keyFile = new File(mContext.getDir(mContext.getPackageName(), Context.MODE_PRIVATE), ADALKS); if (!keyFile.exists()) { throw new IOException("Key file to read does not exist"); } Logger.v(TAG, "Reading key data from a file"); final InputStream in = new FileInputStream(keyFile); try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final byte[] buffer = new byte[KEY_FILE_SIZE]; int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } finally { in.close(); } }
Source:
public MatrixServiceImpl(DataService dataService, FileStore fileStore) { this.dataService = dataService; this.fileStore = fileStore; }

Target:
public MatrixServiceImpl(DataService dataService, FileStore fileStore) { this.dataService = Objects.requireNonNull(dataService); this.fileStore = Objects.requireNonNull(fileStore); }
Source:
public DynamicTableSink createDynamicTableSink(Context context) { final FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); helper.validate(); final JdbcOptions jdbcOptions = getJdbcOptions(helper.getOptions()); final DataType rowDataType = context.getCatalogTable().getSchema().toPhysicalRowDataType(); final TableSchema formatSchema = TableSchemaUtils.getPhysicalSchema(context.getCatalogTable().getSchema()); final DataType[] fieldDataTypes = formatSchema.getFieldDataTypes(); return new JdbcDynamicTableSink( jdbcOptions, getJdbcExecutionOptions(helper.getOptions()), getJdbcDmlOptions(jdbcOptions, context.getCatalogTable().getSchema()), rowDataType, fieldDataTypes); }

Target:
public DynamicTableSink createDynamicTableSink(Context context) { final FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); final ReadableConfig config = helper.getOptions(); helper.validate(); validateConfigOptions(config); JdbcOptions jdbcOptions = getJdbcOptions(config); TableSchema physicalSchema = TableSchemaUtils.getPhysicalSchema(context.getCatalogTable().getSchema()); return new JdbcDynamicTableSink( jdbcOptions, getJdbcExecutionOptions(config), getJdbcDmlOptions(jdbcOptions, physicalSchema), physicalSchema); }
Source:
@Nonnull private Set<SourceExpression> parseSourceList() throws DirectiveParseException { Set<SourceExpression> sourceExpressions = new LinkedHashSet<>(); boolean parseException = false; Map<String, Boolean> seenStates = new HashMap<>(); seenStates.put("seenNone", false); seenStates.put("seenUnsafeInline", false); seenStates.put("seenHashOrNonce", false); while (this.hasNext(SubDirectiveValueToken.class)) { try { SourceExpression se = this.parseSourceExpression(seenStates, !sourceExpressions.isEmpty()); if (se == None.INSTANCE) { seenStates.put("seenNone", true); } else if (se == KeywordSource.UnsafeInline) { seenStates.put("seenUnsafeInline", true); } else if (se instanceof HashSource || se instanceof NonceSource) { seenStates.put("seenHashOrNonce", true); } sourceExpressions.add(se); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SOURCE_LIST; } return sourceExpressions; }

Target:
@Nonnull private Set<SourceExpression> parseSourceList() throws DirectiveParseException { Set<SourceExpression> sourceExpressions = new LinkedHashSet<>(); boolean parseException = false; Set<SeenStates> seenStates = new HashSet<>(); while (this.hasNext(SubDirectiveValueToken.class)) { try { SourceExpression se = this.parseSourceExpression(seenStates, !sourceExpressions.isEmpty()); if (se == None.INSTANCE) { seenStates.add(SeenStates.SEEN_NONE); } else if (se == KeywordSource.UnsafeInline) { seenStates.add(SeenStates.SEEN_UNSAFE_INLINE); } else if (se instanceof HashSource) { seenStates.add(SeenStates.SEEN_HASH); } else if (se instanceof NonceSource) { seenStates.add(SeenStates.SEEN_NONCE); } sourceExpressions.add(se); } catch (DirectiveValueParseException e) { parseException = true; } } if (parseException) { throw INVALID_SOURCE_LIST; } return sourceExpressions; }
Source:
public List<ConditionHistory> getConditionHistory(Patient patient) { List<Condition> conditionList = conditionDAO.getConditionHistory(patient); List<ConditionHistory> conditionHistoryList = new ArrayList<ConditionHistory>(); List<Condition> groupedConditions = new ArrayList<Condition>(); if (CollectionUtils.isEmpty(conditionList)) return new ArrayList<ConditionHistory>(); ConditionHistory conditionhistory = createConditionHistory(conditionList.get(0)); groupedConditions.add(conditionList.get(0)); for (int i = 1; i < conditionList.size(); i++) { Condition condition = conditionList.get(i); if (condition.getConcept().equals(conditionhistory.getCondition())) { groupedConditions.add(condition); } else { conditionhistory.setConditions(groupedConditions); conditionHistoryList.add(conditionhistory); conditionhistory = createConditionHistory(condition); groupedConditions = new ArrayList<Condition>(); groupedConditions.add(condition); } } if (CollectionUtils.isNotEmpty(groupedConditions)) { updateConditionHistoryList(conditionHistoryList, groupedConditions, conditionhistory); } return conditionHistoryList; }

Target:
public Map<String, ConditionHistory> getConditionHistory(Patient patient) { List<Condition> conditionList = conditionDAO.getConditionHistory(patient); Map<String, ConditionHistory> allConditions = new HashMap<String, ConditionHistory>(); for (Condition condition : conditionList) { Concept concept = condition.getConcept(); ConditionHistory conditionHistory; String nonCodedConceptUuid = administrationService.getGlobalProperty(ConditionListConstants.GLOBAL_PROPERTY_NON_CODED_UUID); String key = concept.getUuid().equals(nonCodedConceptUuid) ? condition.getConditionNonCoded() : concept.getName().getName(); if (allConditions.containsKey(key)) { conditionHistory = allConditions.get(key); List<Condition> existingConditions = allConditions.get(condition.getConcept().getName().getName()).getConditions(); existingConditions.add(condition); conditionHistory.setConditions(existingConditions); } else { conditionHistory = new ConditionHistory(); ArrayList<Condition> conditions = new ArrayList<Condition>(); conditions.add(condition); conditionHistory.setConditions(conditions); conditionHistory.setCondition(condition.getConcept()); if (concept.getUuid().equals(nonCodedConceptUuid)) { conditionHistory.setNonCodedCondition(condition.getConcept().getUuid()); } } allConditions.put(key,conditionHistory); } return allConditions; }
Source:
public BatchStatement build() { return new DefaultBatchStatement( batchType, statementsBuilder.build(), executionProfileName, executionProfile, keyspace, routingKeyspace, routingKey, routingToken, buildCustomPayload(), idempotent, tracing, timestamp, pagingState, pageSize, consistencyLevel, serialConsistencyLevel, timeout, null); }

Target:
public BatchStatement build() { return new DefaultBatchStatement( batchType, statementsBuilder.build(), executionProfileName, executionProfile, keyspace, routingKeyspace, routingKey, routingToken, buildCustomPayload(), idempotent, tracing, timestamp, pagingState, pageSize, consistencyLevel, serialConsistencyLevel, timeout, node); }
Source:
public void testCacheManagerAttributes() throws Exception { assertEquals(3, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "CreatedCacheCount"))); assertEquals(3, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "DefinedCacheCount"))); assertEquals("clustered", getAttribute(provider, cacheManagerMBean, "Name")); assertEquals(2, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "ClusterSize"))); assertEquals("RUNNING", getAttribute(provider, cacheManagerMBean, "CacheManagerStatus")); assertNotEquals(0, getAttribute(provider, cacheManagerMBean, "ClusterMembers").length()); assertNotEquals(0, getAttribute(provider, cacheManagerMBean, "NodeAddress").length()); assertEquals(3, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "RunningCacheCount"))); assertNotEquals(0, getAttribute(provider, cacheManagerMBean, "PhysicalAddresses").length()); assertEquals(Version.VERSION, getAttribute(provider, cacheManagerMBean, "Version")); String names = getAttribute(provider, cacheManagerMBean, "DefinedCacheNames"); assertTrue(names.contains("default") && names.contains("memcachedCache") && names.contains("hotRodTopologyCache")); }

Target:
public void testCacheManagerAttributes() throws Exception { assertEquals(4, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "CreatedCacheCount"))); assertEquals(4, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "DefinedCacheCount"))); assertEquals("clustered", getAttribute(provider, cacheManagerMBean, "Name")); assertEquals(2, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "ClusterSize"))); assertEquals("RUNNING", getAttribute(provider, cacheManagerMBean, "CacheManagerStatus")); assertNotEquals(0, getAttribute(provider, cacheManagerMBean, "ClusterMembers").length()); assertNotEquals(0, getAttribute(provider, cacheManagerMBean, "NodeAddress").length()); assertEquals(4, Integer.parseInt(getAttribute(provider, cacheManagerMBean, "RunningCacheCount"))); assertNotEquals(0, getAttribute(provider, cacheManagerMBean, "PhysicalAddresses").length()); assertEquals(Version.VERSION, getAttribute(provider, cacheManagerMBean, "Version")); String names = getAttribute(provider, cacheManagerMBean, "DefinedCacheNames"); assertTrue(names.contains("default") && names.contains("memcachedCache") && names.contains("hotRodTopologyCache")); }
Source:
private void assertBranchesExist(Set<Branch> branches, String ... names) throws InterruptedException { Collection<String> branchNames = getBranchNames(branches); for (String name : names) { assertTrue(name + " branch not found in " + branchNames, branchNames.contains(name)); } }

Target:
private void assertBranchesExist(Set<Branch> branches, String ... names) throws InterruptedException { Collection<String> branchNames = getBranchNames(branches); for (String name : names) { assertThat(branchNames, hasItem(name)); } }
Source:
private void addSubscriptions(String... notifications) { NuxeoPrincipal principal = session.getPrincipal(); String subscriber = NotificationConstants.USER_PREFIX + principal.getName(); for (String notif : notifications) { notificationService.addSubscription(subscriber, notif, annotatedDocumentModel, false, principal, notif); } }

Target:
protected void addSubscriptions(String... notifications) { NuxeoPrincipal principal = session.getPrincipal(); String subscriber = NotificationConstants.USER_PREFIX + principal.getName(); for (String notif : notifications) { notificationService.addSubscription(subscriber, notif, annotatedDocumentModel, false, principal, notif); } }
Source:
public static void main(String[] args) { URL resource = Thread.currentThread().getContextClassLoader().getResource("netty-transports.yml"); if (resource != null) { System.setProperty(YAMLTransportConfigurationBuilder.NETTY_TRANSPORT_CONF, resource.getPath()); } else { log.error("netty-transports.yml not found in resources - proceeding with default netty configuration"); } new MicroservicesRunner() .deploy(new InterceptorService()) .addGlobalRequestInterceptor(new LogTextRequestInterceptor(), new PropertyAddRequestInterceptor()) .addGlobalResponseInterceptor(new LogTextResponseInterceptor(), new PropertyGetResponseInterceptor()) .start(); }

Target:
public static void main(String[] args) { new MicroservicesRunner() .deploy(new InterceptorService()) .addGlobalRequestInterceptor(new LogTextRequestInterceptor(), new PropertyAddRequestInterceptor()) .addGlobalResponseInterceptor(new LogTextResponseInterceptor(), new PropertyGetResponseInterceptor()) .start(); }
Source:
private void addErrorMetric(String transaction, String responseCode, String responseMessage, long count) { final int MAX_RES_CODE_LENGTH_FOR_UDP = 50; if (count > 0) { StringBuilder tag = new StringBuilder(70); tag.append(TAG_APPLICATION).append(application); tag.append(TAG_TRANSACTION).append(transaction); tag.append(TAG_RESPONSE_CODE).append(AbstractInfluxdbMetricsSender.tagToStringValue(responseCode)); if(this.influxdbMetricsManager instanceof UdpMetricsSender && responseMessage.length() > MAX_RES_CODE_LENGTH_FOR_UDP) { String trimmedMessage = responseMessage.substring(0, MAX_RES_CODE_LENGTH_FOR_UDP); tag.append(TAG_RESPONSE_MESSAGE).append(AbstractInfluxdbMetricsSender.tagToStringValue(trimmedMessage + "...")); } else { tag.append(TAG_RESPONSE_MESSAGE).append(AbstractInfluxdbMetricsSender.tagToStringValue(responseMessage)); } tag.append(userTag); StringBuilder field = new StringBuilder(30); field.append(METRIC_COUNT).append(count); influxdbMetricsManager.addMetric(measurement, tag.toString(), field.toString()); } }

Target:
private void addErrorMetric(String transaction, String responseCode, String responseMessage, long count) { if (count > 0) { StringBuilder tag = new StringBuilder(70); tag.append(TAG_APPLICATION).append(application); tag.append(TAG_TRANSACTION).append(transaction); tag.append(TAG_RESPONSE_CODE).append(AbstractInfluxdbMetricsSender.tagToStringValue(responseCode)); if (this.influxdbMetricsManager instanceof UdpMetricsSender && responseMessageSize > 0 && responseMessage.length() > responseMessageSize) { String trimmedMessage = responseMessage.substring(0, responseMessageSize); tag.append(TAG_RESPONSE_MESSAGE).append(AbstractInfluxdbMetricsSender.tagToStringValue(trimmedMessage + "...")); } else { tag.append(TAG_RESPONSE_MESSAGE).append(AbstractInfluxdbMetricsSender.tagToStringValue(responseMessage)); } tag.append(userTag); StringBuilder field = new StringBuilder(30); field.append(METRIC_COUNT).append(count); influxdbMetricsManager.addMetric(measurement, tag.toString(), field.toString()); } }
Source:
public void testFinalFieldReference() throws Exception { Builder b = new Builder(); b.setProperty(Constants.DSANNOTATIONS, "test.component.*FinalClassNonFinalField*"); b.setProperty("Private-Package", "test.component"); b.addClasspath(new File("bin_test")); b.build(); assertOk(b); }

Target:
public void testFinalFieldReference() throws Exception { try (Builder b = new Builder()) { b.setProperty(Constants.DSANNOTATIONS, "test.component.*FinalClassNonFinalField*"); b.setProperty("Private-Package", "test.component"); b.addClasspath(new File("bin_test")); b.build(); assertOk(b); } }
Source:
public void cleanup() { final double[] b = new double[vecXArray.length]; for (int index = 0; index < b.length; index++) { b[index] = worker.pull(index); if (b[index] != 0) { LOG.log(Level.INFO, "Index {0}: value {1}", new Object[]{index, b[index]}); } } }

Target:
public void cleanup() { final double[] vecModel = new double[vecXArray.length]; for (int index = 0; index < vecModel.length; index++) { vecModel[index] = worker.pull(index); if (vecModel[index] != 0) { LOG.log(Level.INFO, "Index {0}: value {1}", new Object[]{index, vecModel[index]}); } } }
Source:
private boolean containsCodeQName(AttributeMap unknownAttributes) { for(QName qName : unknownAttributes.keySet()) { if(qName.getLocalPart().equals(NhincConstants.CE_CODE_ID)) { return true; } } return false; }

Target:
private static boolean containsCodeQName(AttributeMap unknownAttributes) { for(QName qName : unknownAttributes.keySet()) { if(NhincConstants.CE_CODE.equals(qName.getLocalPart())) { return true; } } return false; }
Source:
public String getGoogleId() { return googleId; }

Target:
public String getGoogleId() { return account.googleId; }
Source:
protected EmbeddedCacheManager createBackingEmbeddedCacheManager() throws IOException { if (configurationFileLocation != null) { ConfigurationBuilderHolder configurationBuilderHolder = new ParserRegistry(Thread.currentThread().getContextClassLoader()) .parse(configurationFileLocation.getInputStream()); if(gcb != null) { configurationBuilderHolder.setGlobalConfigurationBuilder(gcb); } if (builder != null) { configurationBuilderHolder.setDefaultConfigurationBuilder(builder); } return new DefaultCacheManager(configurationBuilderHolder, true); } else { if (gcb == null) { if (logger.isDebugEnabled()) logger.debug("GlobalConfigurationBuilder is null. Using default new " + "instance."); gcb = new GlobalConfigurationBuilder(); gcb.globalJmxStatistics().allowDuplicateDomains(true); } if (builder == null) { if (logger.isDebugEnabled()) logger.debug("ConfigurationBuilder is null. Using default new instance."); builder = new ConfigurationBuilder(); } return createCacheManager(gcb, builder); } }

Target:
protected EmbeddedCacheManager createBackingEmbeddedCacheManager() throws IOException { if (configurationFileLocation != null) { ConfigurationBuilderHolder configurationBuilderHolder = new ParserRegistry(Thread.currentThread().getContextClassLoader()) .parse(configurationFileLocation.getInputStream()); if(gcb != null) { configurationBuilderHolder.getGlobalConfigurationBuilder().read(gcb.build()); } if (builder != null) { configurationBuilderHolder.getDefaultConfigurationBuilder().read(builder.build()); } return new DefaultCacheManager(configurationBuilderHolder, true); } else { if (gcb == null) { if (logger.isDebugEnabled()) logger.debug("GlobalConfigurationBuilder is null. Using default new " + "instance."); gcb = new GlobalConfigurationBuilder(); gcb.globalJmxStatistics().allowDuplicateDomains(true); } if (builder == null) { if (logger.isDebugEnabled()) logger.debug("ConfigurationBuilder is null. Using default new instance."); builder = new ConfigurationBuilder(); } return createCacheManager(gcb, builder); } }
Source:
public void testInsertAllNulls_ENG_19237() throws Exception { Client client = getClient(m_cluster); streamNames.remove("t_2"); streamNames.add("nullable"); ClientResponse response = client.callProcedure("@AdHoc", String.format(DROP_STREAM_FORMAT, "t_2")); assertEquals(ClientResponse.SUCCESS, response.getStatus()); response = client.callProcedure("@AdHoc", NULLABLE_SCHEMA); assertEquals(ClientResponse.SUCCESS, response.getStatus()); response = client.callProcedure("@AdHoc", "insert into nullable values(null, null, null)" ); assertEquals(ClientResponse.SUCCESS, response.getStatus()); TestExportBaseSocketExport.waitForExportAllRowsDelivered(client, streamNames); assertEquals(3, m_cluster.getLiveNodeCount()); client.callProcedure("@AdHoc", String.format(DROP_STREAM_FORMAT, "nullable")); client.callProcedure("@AdHoc", T2_SCHEMA); streamNames.remove("nullable"); streamNames.add("t_2"); }

Target:
public void testInsertAllNulls_ENG_19237() throws Exception { Client client = getClient(m_cluster); streamNames.add("nullable"); ClientResponse response = client.callProcedure("@AdHoc", NULLABLE_SCHEMA); assertEquals(ClientResponse.SUCCESS, response.getStatus()); response = client.callProcedure("@AdHoc", "insert into nullable values(null, null, null)" ); assertEquals(ClientResponse.SUCCESS, response.getStatus()); TestExportBaseSocketExport.waitForExportAllRowsDelivered(client, streamNames); assertEquals(3, m_cluster.getLiveNodeCount()); }
Source:
static File createBundle(File outputDir, String bundleName, Map<String, String> headers, Map<String, String>... entries) throws IOException { Manifest m = new Manifest(); Attributes attributes = m.getMainAttributes(); attributes.putValue("Manifest-Version", "1.0"); for (Map.Entry<String, String> entry : headers.entrySet()) { attributes.putValue(entry.getKey(), entry.getValue()); } File file = new File(outputDir, "bundle" + bundleName + ".jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(file), m); if (entries != null) { for (Map<String, String> entryMap : entries) { for (Map.Entry<String, String> entry : entryMap.entrySet()) { jos.putNextEntry(new JarEntry(entry.getKey())); if (entry.getValue() != null) { jos.write(entry.getValue().getBytes()); } jos.closeEntry(); } } } jos.flush(); jos.close(); file.deleteOnExit(); return file; }

Target:
static File createBundle(File outputDir, String bundleName, Map<String, String> headers, Map<String, String>... entries) throws IOException { Manifest m = new Manifest(); Attributes attributes = m.getMainAttributes(); attributes.putValue("Manifest-Version", "1.0"); for (Map.Entry<String, String> entry : headers.entrySet()) { attributes.putValue(entry.getKey(), entry.getValue()); } File file = new File(outputDir, "bundle" + bundleName + ".jar"); try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(file), m)) { if (entries != null) { for (Map<String, String> entryMap : entries) { for (Map.Entry<String, String> entry : entryMap.entrySet()) { jos.putNextEntry(new JarEntry(entry.getKey())); if (entry.getValue() != null) { jos.write(entry.getValue().getBytes()); } jos.closeEntry(); } } } jos.flush(); } file.deleteOnExit(); return file; }
Source:
public Parser<String, Object> makeParser() { if (firstRowIsHeader) { return new DelimitedParser( Optional.fromNullable(delimiter), Optional.fromNullable(listDelimiter), firstRowIsHeader ); } else { return new DelimitedParser( Optional.fromNullable(delimiter), Optional.fromNullable(listDelimiter) ); } }

Target:
public Parser<String, Object> makeParser() { return new DelimitedParser( Optional.fromNullable(delimiter), Optional.fromNullable(listDelimiter), columns, hasHeaderRow ); }
Source:
private synchronized void updateReview(TaskTask task) { String summary = task.getSummary(); boolean ourQuery = task.getParentContainers().contains(fCurrentQuery); if (ourQuery && summary != null && !summary.equals("")) { try { TaskData taskData = fConnector.getTaskData(getTaskRepository(), task.getTaskId(), new NullProgressMonitor()); GerritTask gtask = new GerritTask(taskData); if (gtask.getAttribute(GerritTask.DATE_COMPLETION) == null) { fReviewTable.updateReviewItem(gtask); } } catch (CoreException e) { StatusHandler.log(new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, e.getMessage(), e)); } } }

Target:
private synchronized void updateReview(TaskTask task) { boolean ourQuery = task.getParentContainers().contains(fCurrentQuery); if (ourQuery && !Strings.isNullOrEmpty(task.getSummary())) { try { TaskData taskData = fConnector.getTaskData(getTaskRepository(), task.getTaskId(), new NullProgressMonitor()); GerritTask gtask = new GerritTask(taskData); if (gtask.getAttribute(GerritTask.DATE_COMPLETION) == null) { fReviewTable.updateReviewItem(gtask); } } catch (CoreException e) { StatusHandler.log(new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, e.getMessage(), e)); } } }
Source:
public void onFullScreen(boolean isFullScreen) { if (isPrepared) { isManualFullscreen = isFullScreen; if (isFullScreen) { enterFullScreen(); environment.getAnalyticsRegistry().trackVideoOrientation(videoEntry.videoId, player.getCurrentPosition() / AppConstants.MILLISECONDS_PER_SECOND, true, videoEntry.eid, videoEntry.lmsUrl); } else { exitFullScreen(); environment.getAnalyticsRegistry().trackVideoOrientation(videoEntry.videoId, player.getCurrentPosition() / AppConstants.MILLISECONDS_PER_SECOND, false, videoEntry.eid, videoEntry.lmsUrl); } } else { logger.debug("Player not prepared ?? full screen will NOT work!"); } }

Target:
public void onFullScreen(boolean isFullScreen) { if (isPrepared) { isManualFullscreen = isFullScreen; if (isFullScreen) { enterFullScreen(); } else { exitFullScreen(); } environment.getAnalyticsRegistry().trackVideoOrientation(videoEntry.videoId, player.getCurrentPosition() / AppConstants.MILLISECONDS_PER_SECOND, isFullScreen, videoEntry.eid, videoEntry.lmsUrl); } else { logger.debug("Player not prepared ?? full screen will NOT work!"); } }
Source:
public KafkaSimpleConsumer(String topic, int partitionId, String clientId, List<String> brokers, boolean earliest) { List<KafkaBroker> brokerList = new ArrayList<KafkaBroker>(); for (String broker : brokers) { String[] tokens = broker.split(":"); if (tokens.length != 2) { log.warn("wrong broker name [%s], its format should be host:port", broker); continue; } try { brokerList.add(new KafkaBroker(tokens[0], Integer.parseInt(tokens[1]))); } catch (NumberFormatException e) { log.warn("wrong broker name [%s], its format should be host:port", broker); continue; } } this.allBrokers = Collections.unmodifiableList(brokerList); this.topic = topic; this.partitionId = partitionId; this.clientId = String.format("%s_%d_%s", topic, partitionId, clientId); this.leaderLookupClientId = clientId + "leaderLookup"; this.replicaBrokers = new ArrayList<>(); this.replicaBrokers.addAll(this.allBrokers); this.earliest = earliest; log.info( "KafkaSimpleConsumer initialized with clientId [%s] for message consumption and clientId [%s] for leader lookup", this.clientId, this.leaderLookupClientId ); }

Target:
public KafkaSimpleConsumer(String topic, int partitionId, String clientId, List<String> brokers, boolean earliest) { List<HostAndPort> brokerList = new ArrayList<>(); for (String broker : brokers) { HostAndPort brokerHostAndPort = HostAndPort.fromString(broker); Preconditions.checkArgument( brokerHostAndPort.getHostText() != null && !brokerHostAndPort.getHostText().isEmpty() && brokerHostAndPort.hasPort(), "kafka broker [%s] is not valid, must be <host>:<port>", broker ); brokerList.add(brokerHostAndPort); } this.allBrokers = Collections.unmodifiableList(brokerList); this.topic = topic; this.partitionId = partitionId; this.clientId = String.format("%s_%d_%s", topic, partitionId, clientId); this.leaderLookupClientId = clientId + "leaderLookup"; this.replicaBrokers = new ArrayList<>(); this.replicaBrokers.addAll(this.allBrokers); this.earliest = earliest; log.info( "KafkaSimpleConsumer initialized with clientId [%s] for message consumption and clientId [%s] for leader lookup", this.clientId, this.leaderLookupClientId ); }
Source:
public void removeGroup(GroupInfo group) { Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { ((IJobProgressManagerListener)element).removeGroup(group); } }

Target:
public void removeGroup(GroupInfo group) { for (Object element : listeners.getListeners()) { ((IJobProgressManagerListener)element).removeGroup(group); } }
Source:
public void handleCommand(Command command) { Thing thing = thingProvider.apply(link.getLinkedUID().getThingUID()); if (thing != null) { final ThingHandler handler = thing.getHandler(); if (handler != null) { if (ThingHandlerHelper.isHandlerInitialized(thing)) { logger.debug("Delegating command '{}' for item '{}' to handler for channel '{}'", command, link.getItemName(), link.getLinkedUID()); safeCaller.create(handler).withTimeout(CommunicationManager.THINGHANDLER_EVENT_TIMEOUT) .onTimeout(() -> { logger.warn("Handler for thing '{}' takes more than {}ms for handling a command", handler.getThing().getUID(), SafeCaller.DEFAULT_TIMEOUT); }).build().handleCommand(link.getLinkedUID(), command); } else { logger.debug("Not delegating command '{}' for item '{}' to handler for channel '{}', " + "because handler is not initialized (thing must be in status UNKNOWN, ONLINE or OFFLINE but was {}).", command, link.getItemName(), link.getLinkedUID(), thing.getStatus()); } } else { logger.warn("Cannot delegate command '{}' for item '{}' to handler for channel '{}', " + "because no handler is assigned. Maybe the binding is not installed or not " + "propertly initialized.", command, link.getItemName(), link.getLinkedUID()); } } else { logger.warn( "Cannot delegate command '{}' for item '{}' to handler for channel '{}', " + "because no thing with the UID '{}' could be found.", command, link.getItemName(), link.getLinkedUID(), link.getLinkedUID().getThingUID()); } }

Target:
public void handleCommand(Command command) { Thing thing = thingProvider.apply(link.getLinkedUID().getThingUID()); if (thing != null) { final ThingHandler handler = thing.getHandler(); if (handler != null) { if (ThingHandlerHelper.isHandlerInitialized(thing)) { logger.debug("Delegating command '{}' for item '{}' to handler for channel '{}'", command, link.getItemName(), link.getLinkedUID()); safeCaller.create(handler).withTimeout(CommunicationManager.THINGHANDLER_EVENT_TIMEOUT) .onTimeout(() -> { logger.warn("Handler for thing '{}' takes more than {}ms for handling a command", handler.getThing().getUID(), CommunicationManager.THINGHANDLER_EVENT_TIMEOUT); }).build().handleCommand(link.getLinkedUID(), command); } else { logger.debug("Not delegating command '{}' for item '{}' to handler for channel '{}', " + "because handler is not initialized (thing must be in status UNKNOWN, ONLINE or OFFLINE but was {}).", command, link.getItemName(), link.getLinkedUID(), thing.getStatus()); } } else { logger.warn("Cannot delegate command '{}' for item '{}' to handler for channel '{}', " + "because no handler is assigned. Maybe the binding is not installed or not " + "propertly initialized.", command, link.getItemName(), link.getLinkedUID()); } } else { logger.warn( "Cannot delegate command '{}' for item '{}' to handler for channel '{}', " + "because no thing with the UID '{}' could be found.", command, link.getItemName(), link.getLinkedUID(), link.getLinkedUID().getThingUID()); } }
Source:
public static void sendErrorResponse(ChannelHandlerContext ctx, FullHttpRequest request, List<ErrorResponse.ErrorData> validationErrors, HttpResponseStatus status) { try { String responseBody = new ObjectMapper().writeValueAsString(new ErrorResponse(validationErrors)); sendResponse(ctx, request, responseBody, status); } catch (IOException e) { log.warn("Error preparing response", e); sendErrorResponse(ctx, request, "Error preparing response", HttpResponseStatus.INTERNAL_SERVER_ERROR); } }

Target:
public static void sendErrorResponse(ChannelHandlerContext ctx, FullHttpRequest request, List<ErrorResponse.ErrorData> validationErrors, HttpResponseStatus status) { try { String responseBody = new ObjectMapper().writeValueAsString(new ErrorResponse(validationErrors)); sendResponse(ctx, request, responseBody, status); } catch (IOException e) { log.error("Error preparing response", e); sendErrorResponse(ctx, request, "Error preparing response", HttpResponseStatus.INTERNAL_SERVER_ERROR); } }
Source:
public void testMajorVersionNot3() throws Exception { SslContext nettyContext = makeSslContext(provider, false); try { DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext).build(); SniHandler handler = new SniHandler(mapping); EmbeddedChannel ch = new EmbeddedChannel(handler); byte[] message = {22, 2, 0, 0, 0}; try { ch.writeInbound(Unpooled.wrappedBuffer(message)); } catch (Exception e) { } ch.close(); ByteBuf buf = ch.readOutbound(); if (buf != null) { assertFalse(buf.isReadable()); buf.release(); } assertThat(ch.finish(), is(false)); assertThat(handler.hostname(), nullValue()); assertThat(handler.sslContext(), is(nettyContext)); } finally { releaseAll(nettyContext); } }

Target:
public void testMajorVersionNot3() throws Exception { SslContext nettyContext = makeSslContext(provider, false); try { DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext).build(); SniHandler handler = new SniHandler(mapping); EmbeddedChannel ch = new EmbeddedChannel(handler); byte[] message = {22, 2, 0, 0, 0}; try { ch.writeInbound(Unpooled.wrappedBuffer(message)); fail(); } catch (Exception e) { } ch.close(); ByteBuf buf = ch.readOutbound(); if (buf != null) { assertFalse(buf.isReadable()); buf.release(); } assertThat(ch.finish(), is(false)); assertThat(handler.hostname(), nullValue()); assertThat(handler.sslContext(), is(nettyContext)); } finally { releaseAll(nettyContext); } }
Source:
private void addToBlacklist(InetSocketAddress badHost) { blacklistedHosts.put(badHost, System.currentTimeMillis()); log.info("Blacklisted host '{}'", SafeArg.of("badHost", badHost)); }

Target:
private void addToBlacklist(InetSocketAddress badHost) { blacklistedHosts.put(badHost, System.currentTimeMillis()); log.warn("Blacklisted host '{}'", SafeArg.of("badHost", badHost)); }
Source:
public String description() { return "number of problems in Problems view is " + problems.size() + ".\n" + "Expected number of problems is: " + problems.size(); }

Target:
public String description() { return "number of problems in Problems view is " + problems.size() + ".\n" + "Expected number of problems is: " + expectedProblemsCount; }
Source:
public void run() { try { List<BatchOperation<K, V>> batches = createMonomorphicBatches(operations()); for (BatchOperation<K, V> batch : batches) { try { batch.performBatchOperation(cacheLoaderWriter); } catch (Exception e) { LOGGER.warn("Exception while bulk processing in write behind queue", e); } } } finally { try { for (SingleOperation<K, V> op : operations()) { latest.remove(op.getKey(), op); } } finally { LOGGER.debug("Batch processing completed"); expireTask.cancel(false); } } }

Target:
public void run() { try { List<BatchOperation<K, V>> batches = createMonomorphicBatches(operations()); for (BatchOperation<K, V> batch : batches) { try { batch.performBatchOperation(cacheLoaderWriter); } catch (Exception e) { LOGGER.warn("Exception while bulk processing in write behind queue", e); } } } finally { try { for (SingleOperation<K, V> op : operations()) { latest.remove(op.getKey(), op); } } finally { LOGGER.debug("Cancelling batch expiry task"); expireTask.cancel(false); } } }
Source:
private void updateNetworkDisplay() { String networkName = null; VmInitNetwork obj = null; if (getNetworkList().getSelectedItem() != null) { networkName = getNetworkList().getSelectedItem(); obj = networkMap.get(networkName); } final NetworkBootProtocol bootProtocol = ((obj == null || obj.getBootProtocol() == null) ? NetworkBootProtocol.NONE : obj.getBootProtocol()); getNetworkBootProtocolList().setSelectedItem(Linq.firstOrDefault(getNetworkBootProtocolList().getItems(), new IPredicate<Map.Entry<String, NetworkBootProtocol>>() { @Override public boolean match(Map.Entry<String, NetworkBootProtocol> item) { return item.getValue() == bootProtocol; } })); getNetworkIpAddress().setEntity(obj == null ? null : obj.getIp()); getNetworkNetmask().setEntity(obj == null ? null : obj.getNetmask()); getNetworkGateway().setEntity(obj == null ? null : obj.getGateway()); getNetworkStartOnBoot().setEntity(networkName == null ? null : networkStartOnBoot.contains(networkName)); }

Target:
private void updateNetworkDisplay() { String networkName = null; VmInitNetwork obj = null; if (getNetworkList().getSelectedItem() != null) { networkName = getNetworkList().getSelectedItem(); obj = networkMap.get(networkName); } if (obj == null || obj.getBootProtocol() == null) { getNetworkBootProtocolList().setSelectedItem(NetworkBootProtocol.NONE); } else { getNetworkBootProtocolList().setSelectedItem(obj.getBootProtocol()); } getNetworkIpAddress().setEntity(obj == null ? null : obj.getIp()); getNetworkNetmask().setEntity(obj == null ? null : obj.getNetmask()); getNetworkGateway().setEntity(obj == null ? null : obj.getGateway()); getNetworkStartOnBoot().setEntity(networkName == null ? null : networkStartOnBoot.contains(networkName)); }
Source:
public String decrypt(String encryptedValue) throws CrypterException { if (encryptedValue == null || encryptedValue.isEmpty()) { throw new CrypterException("Value to decrypt cannot be null or empty."); } if (associatedData == null) { throw new CrypterException("Associated data cannot be null."); } try { byte[] encryptedBytes = Base64.getDecoder().decode(encryptedValue); return new String(aead.decrypt(encryptedBytes, associatedData)); } catch (GeneralSecurityException | NullPointerException e) { LOGGER.debug("Problem decrypting.", e); throw new CrypterException("Problem decrypting.", e); } }

Target:
public String decrypt(String encryptedValue) throws CrypterException { if (isBlank(encryptedValue)) { throw new CrypterException("Value to decrypt cannot be null or blank."); } if (associatedData == null) { throw new CrypterException("Associated data cannot be null."); } try { byte[] encryptedBytes = Base64.getDecoder().decode(encryptedValue); return new String(aead.decrypt(encryptedBytes, associatedData)); } catch (GeneralSecurityException | NullPointerException e) { LOGGER.debug("Problem decrypting.", e); throw new CrypterException("Problem decrypting.", e); } }
Source:
public static <Key, Value> Cache<Key, Value> createOneSlotCache() { return new CacheGuava<>(1) ; }

Target:
public static <Key, Value> Cache<Key, Value> createOneSlotCache() { return new Cache1<>() ; }
Source:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { buffer = new TupleBatchBuffer(getSchema()); Character delim = ','; Character esc = '\\'; Integer skip = 0; if (delimiter != null) { delim = delimiter; } if (escape != null) { esc = escape; } if (numberOfSkippedLines != null) { skip = numberOfSkippedLines; } try { scanner = new CSVReader(new BufferedReader(new InputStreamReader(source.getInputStream())), delim, '"', esc, skip); } catch (IOException e) { throw new DbException(e); } lineNumber = 0; }

Target:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { buffer = new TupleBatchBuffer(getSchema()); try { scanner = new CSVReader(new BufferedReader(new InputStreamReader(source.getInputStream())), delimiter, quote, escape, numberOfSkippedLines); } catch (IOException e) { throw new DbException(e); } lineNumber = 0; }
Source:
public boolean shouldVendorBeSentToPaymentWorks(PaymentWorksVendor paymentWorksVendor) { Integer vendorNumber = paymentWorksVendor.getVendorHeaderGeneratedIdentifier(); Integer vendorParentChildNumber = paymentWorksVendor.getVendorDetailAssignedIdentifier(); VendorDetail vendorDetail = getVendorService().getVendorDetail(vendorNumber, vendorParentChildNumber); if (ObjectUtils.isNotNull(vendorDetail)) { return shouldVendorBeSentToPaymentWorks(vendorDetail); } else { LOG.error("shouldVendorBeSentToPaymentWorks2, unable to find a vendor by " + vendorNumber + " and " + vendorParentChildNumber); } return false; }

Target:
public boolean shouldVendorBeSentToPaymentWorks(PaymentWorksVendor paymentWorksVendor) { Integer headerId = paymentWorksVendor.getVendorHeaderGeneratedIdentifier(); Integer detailId = paymentWorksVendor.getVendorDetailAssignedIdentifier(); VendorDetail vendorDetail = getVendorService().getVendorDetail(headerId, detailId); if (ObjectUtils.isNotNull(vendorDetail)) { return shouldVendorBeSentToPaymentWorks(vendorDetail); } LOG.error("shouldVendorBeSentToPaymentWorks2, unable to find a vendor by headerId: " + headerId + " and detailId: " + detailId); return false; }
Source:
private Map<Integer, Long> loadOffsetFromPreviousMetaData(Object lastCommit) { Map<Integer, Long> offsetMap = Maps.newHashMap(); if (lastCommit == null) { return offsetMap; } if (lastCommit instanceof Map) { Map<Object, Object> lastCommitMap = (Map) lastCommit; for (Map.Entry<Object, Object> entry : lastCommitMap.entrySet()) { try { int partitionId = Integer.parseInt(entry.getKey().toString()); long offset = Long.parseLong(entry.getValue().toString()); log.debug("Recover last commit information partitionId [%s], offset [%s]", partitionId, offset); offsetMap.put(partitionId, offset); } catch (NumberFormatException e) { log.error(e, "Fail to load offset from previous meta data [%s]", entry); } } log.info("Loaded offset map[%s]", offsetMap); } else { log.error("Unable to cast lastCommit to Map"); } return offsetMap; }

Target:
private Map<Integer, Long> loadOffsetFromPreviousMetaData(Object lastCommit) { Map<Integer, Long> offsetMap = Maps.newHashMap(); if (lastCommit == null) { return offsetMap; } if (lastCommit instanceof Map) { Map<Object, Object> lastCommitMap = (Map) lastCommit; for (Map.Entry<Object, Object> entry : lastCommitMap.entrySet()) { try { int partitionId = Integer.parseInt(entry.getKey().toString()); long offset = Long.parseLong(entry.getValue().toString()); log.debug("Recover last commit information partitionId [%s], offset [%s]", partitionId, offset); offsetMap.put(partitionId, offset); } catch (NumberFormatException e) { log.error(e, "Fail to load offset from previous meta data [%s]", entry); } } log.info("Loaded offset map[%s]", offsetMap); } else { log.makeAlert("Unable to cast lastCommit to Map for feed [%s]", feed); } return offsetMap; }
Source:
public BlockLocator(){ blockLocator = new ArrayList<>(); }

Target:
public BlockLocator() { hashes = ImmutableList.of(); }
Source:
private static String dialogSanitize(String text) { StringBuilder sanitized = new StringBuilder(); boolean firstSegment = true; for (String segment : text.split("<", -1)) { if (firstSegment) { firstSegment = false; sanitized.append(SafeHtmlUtils.htmlEscapeAllowEntities(segment)); continue; } int tagStart = 0; int tagEnd = segment.indexOf('>'); String tag = null; boolean isValidTag = false; if (tagEnd > 0) { if (segment.charAt(0) == '/') { tagStart = 1; } tag = segment.substring(tagStart, tagEnd); if (TAG_WHITELIST.contains(tag)) { isValidTag = true; } } if (isValidTag) { if (tagStart == 0) { sanitized.append('<'); } else { sanitized.append("</"); } sanitized.append(tag).append('>'); sanitized.append(SafeHtmlUtils.htmlEscapeAllowEntities( segment.substring(tagEnd + 1))); } else { sanitized.append("&lt;").append( SafeHtmlUtils.htmlEscapeAllowEntities(segment)); } } return sanitized.toString(); }

Target:
private static String dialogSanitize(String text) { StringBuilder sanitized = new StringBuilder(); boolean firstSegment = true; for (String segment : text.split("<", -1)) { if (firstSegment) { firstSegment = false; sanitized.append(SafeHtmlUtils.htmlEscapeAllowEntities(segment)); continue; } int tagStart = 0; int tagEnd = segment.indexOf('>'); String tag = null; boolean isValidTag = false; if (tagEnd > 0) { if (segment.charAt(0) == '/') { tagStart = 1; } tag = segment.substring(tagStart, tagEnd).toLowerCase(); if (TAG_WHITELIST.contains(tag)) { isValidTag = true; } } if (isValidTag) { if (tagStart == 0) { sanitized.append('<'); } else { sanitized.append("</"); } sanitized.append(tag).append('>'); sanitized.append(SafeHtmlUtils.htmlEscapeAllowEntities( segment.substring(tagEnd + 1))); } else { sanitized.append("&lt;").append( SafeHtmlUtils.htmlEscapeAllowEntities(segment)); } } return sanitized.toString(); }