auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String taskArgsAsCmd() { StringBuilder result = new StringBuilder(); if (!F.isEmpty(taskArg.getCaches())) { for (String cache : taskArg.getCaches()) { result.append(cache); result.append(" "); } } if (taskArg.getCacheFilterEnum() != null) { result.append(CACHE_FILTER); result.append(" "); result.append(taskArg.getCacheFilterEnum().toString()); result.append(" "); } if (!F.isEmpty(taskArg.getExcludeCaches())) { result.append(EXCLUDE_CACHES + " "); for (String excluded : taskArg.getExcludeCaches()) { result.append(excluded); result.append(" "); } } return result.toString(); }

Target:
private String taskArgsAsCmd() { StringBuilder result = new StringBuilder(); if (!F.isEmpty(taskArg.getCaches())) { for (String cache : taskArg.getCaches()) { result.append(cache); result.append(" "); } } if (taskArg.getCacheFilterEnum() != null) { result.append(CACHE_FILTER); result.append(" "); result.append(taskArg.getCacheFilterEnum()); result.append(" "); } if (!F.isEmpty(taskArg.getExcludeCaches())) { result.append(EXCLUDE_CACHES + " "); for (String excluded : taskArg.getExcludeCaches()) { result.append(excluded); result.append(" "); } } return result.toString(); }
Source:
public RouterConfig(VerifiableProperties verifiableProperties) { routerScalingUnitCount = verifiableProperties.getIntInRange("router.scaling.unit.count", 1, 0, 200); routerHostname = verifiableProperties.getString("router.hostname"); routerDatacenterName = verifiableProperties.getString("router.datacenter.name"); routerScalingUnitMaxConnectionsPerPortPlainText = verifiableProperties.getIntInRange("router.scaling.unit.max.connections.per.port.plain.text", 5, 1, 20); routerScalingUnitMaxConnectionsPerPortSsl = verifiableProperties.getIntInRange("router.scaling.unit.max.connections.per.port.ssl", 2, 1, 20); routerConnectionCheckoutTimeoutMs = verifiableProperties.getIntInRange("router.connection.checkout.timeout.ms", 1000, 1, 5000); routerRequestTimeoutMs = verifiableProperties.getInt("router.request.timeout.ms", 2000); routerMaxPutChunkSizeBytes = verifiableProperties.getInt("router.max.put.chunk.size.bytes", 4 * 1024 * 1024); routerPutRequestParallelism = verifiableProperties.getInt("router.put.request.parallelism", 3); routerPutSuccessTarget = verifiableProperties.getInt("router.put.success.target", 2); routerMaxSlippedPutAttempts = verifiableProperties.getInt("router.max.slipped.put.attempts", 1); routerDeleteRequestParallelism = verifiableProperties.getInt("router.delete.request.parallelism", 12); routerDeleteSuccessTarget = verifiableProperties.getInt("router.delete.success.target", 2); }

Target:
public RouterConfig(VerifiableProperties verifiableProperties) { routerScalingUnitCount = verifiableProperties.getIntInRange("router.scaling.unit.count", 1, 1, 200); routerHostname = verifiableProperties.getString("router.hostname"); routerDatacenterName = verifiableProperties.getString("router.datacenter.name"); routerScalingUnitMaxConnectionsPerPortPlainText = verifiableProperties.getIntInRange("router.scaling.unit.max.connections.per.port.plain.text", 5, 1, 20); routerScalingUnitMaxConnectionsPerPortSsl = verifiableProperties.getIntInRange("router.scaling.unit.max.connections.per.port.ssl", 2, 1, 20); routerConnectionCheckoutTimeoutMs = verifiableProperties.getIntInRange("router.connection.checkout.timeout.ms", 1000, 1, 5000); routerRequestTimeoutMs = verifiableProperties.getInt("router.request.timeout.ms", 2000); routerMaxPutChunkSizeBytes = verifiableProperties.getInt("router.max.put.chunk.size.bytes", 4 * 1024 * 1024); routerPutRequestParallelism = verifiableProperties.getInt("router.put.request.parallelism", 3); routerPutSuccessTarget = verifiableProperties.getInt("router.put.success.target", 2); routerMaxSlippedPutAttempts = verifiableProperties.getInt("router.max.slipped.put.attempts", 1); routerDeleteRequestParallelism = verifiableProperties.getInt("router.delete.request.parallelism", 12); routerDeleteSuccessTarget = verifiableProperties.getInt("router.delete.success.target", 2); }
Source:
public void testConvertcaptureObjectDto() { final CaptureObject result = this.mapper.map(this.captureObjectDto(), CaptureObject.class); Assert.assertTrue(result != null && result instanceof CaptureObject); }

Target:
public void testConvertcaptureObjectDto() { final CaptureObject result = this.mapper.map(this.captureObjectDto(), CaptureObject.class); assertNotNull("mapping CaptureObjectDto should not return null", result); assertThat("mapping CaptureObjectDto should return correct type", result, instanceOf(CaptureObject.class)); }
Source:
private void doReleaseMessage(Message<?> message) { if (this.messageStore instanceof SimpleMessageStore || ((MessageStore) this.messageStore).removeMessage(message.getHeaders().getId()) != null) { this.messageStore.removeMessageFromGroup(this.messageGroupId, message); this.delayTasks.remove(message.getHeaders().getId()); this.handleMessageInternal(message); } else { if (logger.isDebugEnabled()) { logger.debug("No message in the Message Store to release: " + message + ". Likely another instance has already released it."); } } }

Target:
private void doReleaseMessage(Message<?> message) { if (removeDelayedMessageFromMessageStore(message)) { this.messageStore.removeMessageFromGroup(this.messageGroupId, message); this.handleMessageInternal(message); } else { if (logger.isDebugEnabled()) { logger.debug("No message in the Message Store to release: " + message + ". Likely another instance has already released it."); } } }
Source:
public synchronized void setMessageCompression(boolean enable) { call.setMessageCompression(enable); }

Target:
public void setMessageCompression(boolean enable) { throw new UnsupportedOperationException("setMessageCompression()"); }
Source:
public static void displayValidationWindow(Project project, Collection<ValidationSuite> vss, String title) { List<RuleViolationResult> results = getRuleViolations(project, vss); Set<Element> elements = new LinkedHashSet<>(); for (RuleViolationResult violation : results) { elements.add((Element) violation.getElement()); } Package dummyvs = (Package) project.getElementByID("_17_0_2_407019f_1354124289134_280378_12909"); if (dummyvs == null) { try { ProjectsManager projectsManager = Application.getInstance().getProjectsManager(); File file = new File(Application.environment().getProfilesDirectory() + "SysML Extensions.mdxml"); ProjectDescriptor projectDescriptor = ProjectDescriptorsFactory.createProjectDescriptor(file.toURI()); projectsManager.useModule(project, projectDescriptor); dummyvs = (Package) project.getElementByID("_17_0_2_407019f_1354124289134_280378_12909"); } catch(Exception e){ } } if(dummyvs == null){ Application.getInstance().getGUILog().log("You don't have SysML Extensions mounted! You need it in order for the validations to show."); return; } EnumerationLiteral severitylevel = Annotation.getSeverityLevel(project, Annotation.INFO); ValidationRunData runData = new ValidationRunData(dummyvs, false, elements, severitylevel); String id = "" + System.currentTimeMillis(); Map<Annotation, RuleViolationResult> mapping = new HashMap<>(); ValidationWindowRun vwr = new ValidationWindowRun(id, title, runData, results, mapping); for (RuleViolationResult rvr : results) { for (NMAction action : rvr.getAnnotation().getActions()) { if (action instanceof IRuleViolationAction) { ((IRuleViolationAction) action).setValidationWindowRun(vwr); } } mapping.put(rvr.getAnnotation(), rvr); } ValidationResultsWindowManager.updateValidationResultsWindow(id, title, runData, results); }

Target:
public static void displayValidationWindow(Project project, Collection<ValidationSuite> vss, String title) { List<RuleViolationResult> results = getRuleViolations(project, vss); Set<Element> elements = new LinkedHashSet<>(); for (RuleViolationResult violation : results) { elements.add((Element) violation.getElement()); } Package dummyvs = (Package) project.getElementByID("_17_0_2_407019f_1354124289134_280378_12909"); if (dummyvs == null) { Application.getInstance().getGUILog().log("You don't have SysML Extensions mounted! You need it in order for the validations to show."); return; } EnumerationLiteral severitylevel = Annotation.getSeverityLevel(project, Annotation.INFO); ValidationRunData runData = new ValidationRunData(dummyvs, false, elements, severitylevel); String id = "" + System.currentTimeMillis(); Map<Annotation, RuleViolationResult> mapping = new HashMap<>(); ValidationWindowRun vwr = new ValidationWindowRun(id, title, runData, results, mapping); for (RuleViolationResult rvr : results) { for (NMAction action : rvr.getAnnotation().getActions()) { if (action instanceof IRuleViolationAction) { ((IRuleViolationAction) action).setValidationWindowRun(vwr); } } mapping.put(rvr.getAnnotation(), rvr); } ValidationResultsWindowManager.updateValidationResultsWindow(id, title, runData, results); }
Source:
public ITmfContext seekEvent(ITmfLocation location) { if (fFile == null) { return INVALID_CONTEXT; } final TmfContext context = new TmfContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); if (NULL_LOCATION.equals(location)) { return context; } try { if (location == null) { fFileInput.seek(0); long lineStartOffset = fFileInput.getFilePointer(); @Nullable String line = fFileInput.readLine(); Matcher matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); while (line != null && !matcher.matches()) { lineStartOffset = fFileInput.getFilePointer(); line = fFileInput.readLine(); if (line == null) { break; } matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); } fFileInput.seek(lineStartOffset); } else if (location.getLocationInfo() instanceof Long) { fFileInput.seek((Long) location.getLocationInfo()); } context.setLocation(new TmfLongLocation(fFileInput.getFilePointer())); context.setRank(0); return context; } catch (final FileNotFoundException e) { Activator.getInstance().logError("Error seeking event. File not found: " + getPath(), e); return context; } catch (final IOException e) { Activator.getInstance().logError("Error seeking event. File: " + getPath(), e); return context; } }

Target:
public ITmfContext seekEvent(ITmfLocation location) { if (fFile == null) { return INVALID_CONTEXT; } final TmfContext context = new TmfContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); if (NULL_LOCATION.equals(location)) { return context; } try { if (location == null) { fFileInput.seek(0); long lineStartOffset = fFileInput.getFilePointer(); @Nullable String line = fFileInput.readLine(); if(line == null) { return context; } Matcher matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); while (!matcher.matches()) { lineStartOffset = fFileInput.getFilePointer(); line = fFileInput.readLine(); if (line == null) { break; } matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); } fFileInput.seek(lineStartOffset); } else if (location.getLocationInfo() instanceof Long) { fFileInput.seek((Long) location.getLocationInfo()); } context.setLocation(new TmfLongLocation(fFileInput.getFilePointer())); context.setRank(0); return context; } catch (final FileNotFoundException e) { Activator.getInstance().logError("Error seeking event. File not found: " + getPath(), e); return context; } catch (final IOException e) { Activator.getInstance().logError("Error seeking event. File: " + getPath(), e); return context; } }
Source:
public void setUp() throws Exception { super.setUp(); copyFileToTestProject(Activator.PLUGIN_ID, PATH, ODESIGN_EXT_RESOURCE_NAME); copyFileToTestProject(Activator.PLUGIN_ID, PATH, SEMANTIC_INTERACTIONS_RESOURCE_NAME); copyFileToTestProject(Activator.PLUGIN_ID, PATH, AIRD_RESOURCE_NAME); changeDiagramUIPreference(SiriusDiagramUiPreferencesKeys.PREF_OLD_UI.name(), true); changeDiagramPreference(SiriusDiagramPreferencesKeys.PREF_DISPLAY_HEADER_SECTION.name(), false); sessionAirdResource = new UIResource(designerProject, "/", AIRD_RESOURCE_NAME); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), "Sequence Diagram on Interaction", "Sequence Diagram on 455443", DDiagram.class); arrangeAll(); maximizeEditor(editor); refreshLayoutScopeAsserter = new RefreshLayoutScopeAsserter(localSession.getOpenedSession().getTransactionalEditingDomain()); }

Target:
public void setUp() throws Exception { super.setUp(); copyFileToTestProject(Activator.PLUGIN_ID, PATH, ODESIGN_EXT_RESOURCE_NAME); copyFileToTestProject(Activator.PLUGIN_ID, PATH, SEMANTIC_INTERACTIONS_RESOURCE_NAME); copyFileToTestProject(Activator.PLUGIN_ID, PATH, AIRD_RESOURCE_NAME); changeDiagramUIPreference(SiriusDiagramUiPreferencesKeys.PREF_OLD_UI.name(), true); changeDiagramPreference(SiriusDiagramPreferencesKeys.PREF_DISPLAY_HEADER_SECTION.name(), false); sessionAirdResource = new UIResource(designerProject, "/", AIRD_RESOURCE_NAME); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), "Sequence Diagram on Interaction", "Sequence Diagram on 455443", DDiagram.class); maximizeEditor(editor); refreshLayoutScopeAsserter = new RefreshLayoutScopeAsserter(localSession.getOpenedSession().getTransactionalEditingDomain()); }
Source:
void runTest(String name) { name = name.replace('/', '.'); System.out.println("Running " + name); Form form = new Form(name); Display display = Display.getDisplay(this); Harness harness = new Harness(name, display); harness.setScreenAndWait(form); Class c = null; try { c = Class.forName(name); } catch (Exception e) { System.err.println(e); harness.fail("Can't load test"); } Object obj = null; try { obj = c.newInstance(); } catch (Exception e) { System.err.println(e); harness.fail("Can't instantiate test"); } Testlet t = (Testlet) obj; try { t.test(harness); } catch (Exception e) { System.err.println(e); harness.fail("Test threw an unexpected exception"); } harness.report(); boolean classPassed = true; if (harness.passed() != t.getExpectedPass()) { classPassed = false; System.err.println(name + ": test expected " + t.getExpectedPass() + " passes, got " + harness.passed()); } if (harness.failed() != t.getExpectedFail()) { classPassed = false; System.err.println(name + ": test expected " + t.getExpectedFail() + " failures, got " + harness.failed()); } if (harness.knownFailed() != t.getExpectedKnownFail()) { classPassed = false; System.err.println(name + ": test expected " + t.getExpectedKnownFail() + " known failures, got " + harness.knownFailed()); } if (classPassed) { classPass++; } else { classFail++; System.err.println(name + ": class fail"); } pass += harness.passed(); fail += harness.failed(); knownFail += harness.knownFailed(); unknownPass += harness.unknownPassed(); System.out.println("Completed " + name); }

Target:
void runTest(String name) { name = name.replace('/', '.'); System.out.println("Running " + name); Form form = new Form(name); Display display = Display.getDisplay(this); Harness harness = new Harness(name, display); harness.setScreenAndWait(form); Class c = null; try { c = Class.forName(name); } catch (Exception e) { System.err.println(e); harness.fail("Can't load test"); } Object obj = null; try { obj = c.newInstance(); } catch (Exception e) { System.err.println(e); harness.fail("Can't instantiate test"); } Testlet t = (Testlet) obj; try { t.test(harness); } catch (Exception e) { System.err.println(e); harness.fail("Test threw an unexpected exception"); } harness.report(); boolean classPassed = true; if (harness.passed() != t.getExpectedPass()) { classPassed = false; System.err.println(name + ": test expected " + t.getExpectedPass() + " passes, got " + harness.passed()); } if (harness.failed() != t.getExpectedFail()) { classPassed = false; System.err.println(name + ": test expected " + t.getExpectedFail() + " failures, got " + harness.failed()); } if (harness.knownFailed() != t.getExpectedKnownFail()) { classPassed = false; System.err.println(name + ": test expected " + t.getExpectedKnownFail() + " known failures, got " + harness.knownFailed()); } if (classPassed) { classPass++; } else { classFail++; System.err.println(name + ": class fail"); } pass += harness.passed(); fail += harness.failed(); knownFail += harness.knownFailed(); unknownPass += harness.unknownPassed(); }
Source:
public D getDiagramByPath(final org.uberfire.backend.vfs.Path file) { if (accepts(file)) { DefinitionSetService services = getServiceByPath(file); if (null != services) { final String defSetId = getDefinitionSetId(services); final String name = parseFileName(file, services); M metadata = obtainMetadata(services, file, defSetId, name); if (null == metadata) { metadata = (M) buildMetadataInstance(file, defSetId, name); } metadata.setPath(file); final InputStream is = loadPath(file); try { final MarshallingResponse<Graph<DefinitionSet, ?>> marshallingResponse = services.getDiagramMarshaller().unmarshallWithValidation(MarshallingRequest.builder() .metadata(metadata) .input(is) .mode(MarshallingRequest.Mode.AUTO) .build()); final Graph<DefinitionSet, ?> graph = marshallingResponse.getResult() .orElseThrow(() -> new RuntimeException(marshallingResponse.getMessages().toString())); final DiagramFactory<M, ?> factory = factoryManager.registry().getDiagramFactory(graph.getContent().getDefinition(), getMetadataType()); D diagram = (D) factory.build(name, metadata, graph); return diagram; } catch (Exception e) { LOG.error("Cannot unmarshall diagram for diagram's path [" + file + "]", e); final String xml = getIoService().readAllString(Paths.convert(file)); throw new DiagramParsingException(metadata, xml); } } } throw new UnsupportedOperationException("Diagram format not supported [" + file + "]"); }

Target:
public D getDiagramByPath(final org.uberfire.backend.vfs.Path file) { if (accepts(file)) { DefinitionSetService services = getServiceByPath(file); if (null != services) { final String defSetId = getDefinitionSetId(services); final String name = parseFileName(file, services); M metadata = obtainMetadata(services, file, defSetId, name); if (null == metadata) { metadata = (M) buildMetadataInstance(file, defSetId, name); } metadata.setPath(file); final InputStream is = loadPath(file); try { final MarshallingResponse<Graph<DefinitionSet, ?>> marshallingResponse = services.getDiagramMarshaller().unmarshallWithValidation(MarshallingRequest.builder() .metadata(metadata) .input(is) .mode(MarshallingRequest.Mode.AUTO) .build()); final Graph<DefinitionSet, ?> graph = Optional.ofNullable(marshallingResponse.getResult()) .orElseThrow(() -> new RuntimeException(marshallingResponse.getMessages().toString())); final DiagramFactory<M, ?> factory = factoryManager.registry().getDiagramFactory(graph.getContent().getDefinition(), getMetadataType()); return (D) factory.build(name, metadata, graph); } catch (Exception e) { LOG.error("Cannot unmarshall diagram for diagram's path [" + file + "]", e); final String xml = getIoService().readAllString(Paths.convert(file)); throw new DiagramParsingException(metadata, xml); } } } throw new UnsupportedOperationException("Diagram format not supported [" + file + "]"); }
Source:
public void build(String target) { Path projectRoot = InProject.findProjectRoot(); if (!Files.exists(projectRoot.resolve("Rakefile"))) { return; } if (target == null || "".equals(target)) { throw new IllegalStateException("No targets specified"); } log.finest("\nBuilding " + target + " ..."); ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.add("bazel", "build", target); ImmutableList<String> command = builder.build(); CommandLine commandLine = new CommandLine(command.toArray(new String[0])); commandLine.setWorkingDirectory(projectRoot.toAbsolutePath().toString()); commandLine.copyOutputTo(System.err); commandLine.execute(); if (!commandLine.isSuccessful()) { throw new WebDriverException("Build failed! " + target + "\n" + commandLine.getStdOut()); } }

Target:
public void build(String target) { Path projectRoot = InProject.findProjectRoot(); if (!Files.exists(projectRoot.resolve("Rakefile"))) { return; } if (target == null || "".equals(target)) { throw new IllegalStateException("No targets specified"); } log.info("\nBuilding " + target + " ..."); ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.add("bazel", "build", target); ImmutableList<String> command = builder.build(); CommandLine commandLine = new CommandLine(command.toArray(new String[0])); commandLine.setWorkingDirectory(projectRoot.toAbsolutePath().toString()); commandLine.copyOutputTo(System.err); commandLine.execute(); if (!commandLine.isSuccessful()) { throw new WebDriverException("Build failed! " + target + "\n" + commandLine.getStdOut()); } }
Source:
public static ConfigurationTransition of( ConfigurationTransition transition1, ConfigurationTransition transition2) { Preconditions.checkNotNull(transition1); Preconditions.checkNotNull(transition2); if (transition1 == NullTransition.INSTANCE || transition1.isHostTransition()) { return transition1; } else if (transition1 == NoTransition.INSTANCE) { return transition2; } if (transition2 == NoTransition.INSTANCE) { return transition1; } else if (transition2 == NullTransition.INSTANCE || transition2.isHostTransition()) { return transition2; } return new ComposingTransition(transition1, transition2); }

Target:
public static ConfigurationTransition of( ConfigurationTransition transition1, ConfigurationTransition transition2) { Preconditions.checkNotNull(transition1); Preconditions.checkNotNull(transition2); if (isFinal(transition1)) { return transition1; } else if (transition1 == NoTransition.INSTANCE) { return transition2; } if (transition2 == NoTransition.INSTANCE) { return transition1; } else if (isFinal(transition2)) { return transition2; } return new ComposingTransition(transition1, transition2); }
Source:
public void testSplit() throws Exception { long bamFileSize = LARGE_BAM_FILE.length(); SBIIndex index = fromBAMFile(LARGE_BAM_FILE, 100); List<Chunk> chunks = index.split(bamFileSize / 10); Assert.assertTrue(chunks.size() > 1); SamReader samReader = SamReaderFactory.makeDefault() .validationStringency(ValidationStringency.SILENT) .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS).open(LARGE_BAM_FILE); List<SAMRecord> allReads = Iterables.slurp(samReader); List<SAMRecord> allReadsFromChunks = new ArrayList<>(); for (Chunk chunk : chunks) { allReadsFromChunks.addAll(getReadsInChunk(LARGE_BAM_FILE, chunk)); } Assert.assertEquals(allReadsFromChunks, allReads); List<Chunk> optimizedChunks = Chunk.optimizeChunkList(chunks, 0); Assert.assertEquals(optimizedChunks.size(), 1); List<SAMRecord> allReadsFromOneChunk = getReadsInChunk(LARGE_BAM_FILE, optimizedChunks.get(0)); Assert.assertEquals(allReadsFromOneChunk, allReads); }

Target:
public void testSplit() throws Exception { final long bamFileSize = LARGE_BAM_FILE.length(); final SBIIndex index = fromBAMFile(LARGE_BAM_FILE, 100); final List<Chunk> chunks = index.split(bamFileSize / 10); Assert.assertTrue(chunks.size() > 1); final List<SAMRecord> allReads = getReads(LARGE_BAM_FILE); final List<SAMRecord> allReadsFromChunks = new ArrayList<>(); for (final Chunk chunk : chunks) { allReadsFromChunks.addAll(getReadsInChunk(LARGE_BAM_FILE, chunk)); } Assert.assertEquals(allReadsFromChunks, allReads); final List<Chunk> optimizedChunks = Chunk.optimizeChunkList(chunks, 0); Assert.assertEquals(optimizedChunks.size(), 1); final List<SAMRecord> allReadsFromOneChunk = getReadsInChunk(LARGE_BAM_FILE, optimizedChunks.get(0)); Assert.assertEquals(allReadsFromOneChunk, allReads); }
Source:
public HostLocation getHostLocation() { String hostname = Parameter.value("minion.localhost"); Pattern adMatcher = Pattern.compile(Parameter.value("adPattern", "(ad[0-9]+)")); Pattern rackMatcher = Pattern.compile(Parameter.value("rackPattern", "(rack[0-9]+)")); Pattern physicalHostMatcher = Pattern.compile(Parameter.value("physicalHostPattern", "(physicalHost[0-9]+)")); String ad = match(hostname, adMatcher); String rack = match(hostname, rackMatcher); String physicalHost = match(hostname, physicalHostMatcher); return new HostLocation(ad, rack, physicalHost); }

Target:
public HostLocation getHostLocation() { String hostname = Parameter.value("minion.localhost"); String dataCenterPattern = Parameter.value("minion.datacenterPattern", ""); String rackPattern = Parameter.value("minion.rackPattern", ""); String physicalHostMatcher = Parameter.value("minion.physicalHostPattern", ""); String ad = match(hostname, dataCenterPattern); String rack = match(hostname, rackPattern); String physicalHost = match(hostname, physicalHostMatcher); return new HostLocation(ad, rack, physicalHost); }
Source:
private static boolean generatesPrivateAccess(ClassTree tree) { if (usesAnnotation(tree, Collections.singletonList("lombok.Value"))) { return true; } return Optional.ofNullable(tree.symbol().metadata().valuesForAnnotation("lombok.experimental.FieldDefaults")) .map(List::stream) .map(s -> s.filter(Objects::nonNull) .anyMatch(av -> "level".equals(av.name()) && "PRIVATE".equals(getAccessLevelValue(av.value()))) ).orElse(false); }

Target:
private static boolean generatesPrivateAccess(ClassTree tree) { if (usesAnnotation(tree, Collections.singletonList(LOMBOK_VALUE))) { return true; } return Optional.ofNullable(tree.symbol().metadata().valuesForAnnotation(LOMBOK_FIELD_DEFAULTS)) .map(List::stream) .map(s -> s.filter(Objects::nonNull) .anyMatch(av -> "level".equals(av.name()) && "PRIVATE".equals(getAccessLevelValue(av.value()))) ).orElse(false); }
Source:
ValidationResult validateRemovedLabels(VdsNetworkInterface unmgmtNic, Set<String> removedLabels) { if (unmgmtNic.getLabels() != null && !Collections.disjoint(unmgmtNic.getLabels(), removedLabels)){ return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_REMOVE_LABEL_FROM_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(NIC, unmgmtNic.getName())); } return ValidationResult.VALID; }

Target:
ValidationResult validateRemovedLabels(VdsNetworkInterface unmgmtNic, Set<String> removedLabels) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_REMOVE_LABEL_FROM_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(NIC, unmgmtNic.getName())). when(unmgmtNic.getLabels() != null && !Collections.disjoint(unmgmtNic.getLabels(), removedLabels)); }
Source:
public void onPlayerJoin(PlayerJoinEvent event) { if (plugin.al.isAdmin(event.getPlayer())) { if (plugin.al.isCommandSpyActive(event.getPlayer())) { FPlayer playerdata = plugin.pl.getPlayer(event.getPlayer()); playerdata.setCommandSpy(playerdata.cmdspyEnabled() == true); } else { FPlayer playerdata = plugin.pl.getPlayer(event.getPlayer()); playerdata.setCommandSpy(playerdata.cmdspyEnabled() == false); } } else { FPlayer playerdata = plugin.pl.getPlayer(event.getPlayer()); playerdata.setCommandSpy(playerdata.cmdspyEnabled() == false); } }

Target:
public void onPlayerJoin(PlayerJoinEvent event) { Admin admin = getAdmin((Player) event.getPlayer()); FPlayer playerdata = plugin.pl.getPlayer(event.getPlayer()); if (plugin.al.isAdmin(event.getPlayer())) { if (admin.hasCommandSpy()) { playerdata.setCommandSpy(playerdata.cmdspyEnabled() == true); } else { playerdata.setCommandSpy(playerdata.cmdspyEnabled() == false); } } else { playerdata.setCommandSpy(playerdata.cmdspyEnabled() == false); } }
Source:
public static VmPool map(org.ovirt.engine.core.common.businessentities.VmPool entity, VmPool template) { VmPool model = template != null ? template : new VmPool(); model.setId(entity.getVmPoolId().toString()); model.setName(entity.getName()); model.setDescription(entity.getVmPoolDescription()); model.setComment(entity.getComment()); model.setSize(entity.getAssignedVmsCount()); model.setPrestartedVms(entity.getPrestartedVms()); if (entity.getVdsGroupId() != null || entity.getVdsGroupName() != null) { model.setCluster(new Cluster()); model.getCluster().setId(entity.getVdsGroupId().toString()); } model.setMaxUserVms(entity.getMaxAssignedVmsPerUser()); if (StringUtils.isNotBlank(entity.getSpiceProxy())) { Display display = new Display(); display.setProxy(entity.getSpiceProxy()); model.setDisplay(display); } model.setType(entity.getVmPoolType().name().toLowerCase()); return model; }

Target:
public static VmPool map(org.ovirt.engine.core.common.businessentities.VmPool entity, VmPool template) { VmPool model = template != null ? template : new VmPool(); model.setId(entity.getVmPoolId().toString()); model.setName(entity.getName()); model.setDescription(entity.getVmPoolDescription()); model.setComment(entity.getComment()); model.setSize(entity.getAssignedVmsCount()); model.setPrestartedVms(entity.getPrestartedVms()); if (entity.getVdsGroupId() != null || entity.getVdsGroupName() != null) { model.setCluster(new Cluster()); model.getCluster().setId(entity.getVdsGroupId().toString()); } model.setMaxUserVms(entity.getMaxAssignedVmsPerUser()); if (StringUtils.isNotBlank(entity.getSpiceProxy())) { Display display = new Display(); display.setProxy(entity.getSpiceProxy()); model.setDisplay(display); } model.setType(map(entity.getVmPoolType(), null)); return model; }
Source:
private Collection<FeedbackResponseComment> getFeedbackResponseCommentEntitiesForSessionInSection( String courseId, String feedbackSessionName, String section) { Map<Long, FeedbackResponseComment> comments = new HashMap<Long, FeedbackResponseComment>(); for (FeedbackResponseComment comment : load() .filter("courseId =", courseId) .filter("feedbackSessionName =", feedbackSessionName) .filter("giverSection =", section) .list()) { comments.put(comment.getFeedbackResponseCommentId(), comment); } for (FeedbackResponseComment comment : load() .filter("courseId =", courseId) .filter("feedbackSessionName =", feedbackSessionName) .filter("receiverSection =", section) .list()) { comments.put(comment.getFeedbackResponseCommentId(), comment); } return comments.values(); }

Target:
private Collection<FeedbackResponseComment> getFeedbackResponseCommentEntitiesForSessionInSection( String courseId, String feedbackSessionName, String section) { Map<Long, FeedbackResponseComment> comments = new HashMap<>(); List<FeedbackResponseComment> firstQueryResponseComments = load() .filter("courseId =", courseId) .filter("feedbackSessionName =", feedbackSessionName) .filter("giverSection =", section) .list(); for (FeedbackResponseComment comment : firstQueryResponseComments) { comments.put(comment.getFeedbackResponseCommentId(), comment); } List<FeedbackResponseComment> secondQueryResponseComments = load() .filter("courseId =", courseId) .filter("feedbackSessionName =", feedbackSessionName) .filter("receiverSection =", section) .list(); for (FeedbackResponseComment comment : secondQueryResponseComments) { comments.put(comment.getFeedbackResponseCommentId(), comment); } return comments.values(); }
Source:
public void setClass(String name, String groups, String engines) { if (name != null) { this.nameField.setValue(name); this.nameField.setDisabled(true); this.enginesPickList.setValues(engines.split(", ")); this.groupsPickList.setValues(groups.split(", ")); this.newClass = false; this.removeButton.setDisabled(false); } else { this.nameField.setValue(""); this.nameField.setDisabled(false); this.enginesPickList.setValues(new String[]{}); this.groupsPickList.setValues(new String[]{}); this.newClass = true; this.removeButton.setDisabled(true); } }

Target:
public void setClass(String name, String groups, String engines) { if (name != null) { this.nameField.setValue(name); this.nameField.setDisabled(true); this.enginesPickList.setValues(engines.split("\\s*,\\s*")); this.groupsPickList.setValues(groups.split("\\s*,\\s*")); this.newClass = false; this.removeButton.setDisabled(false); } else { this.nameField.setValue(""); this.nameField.setDisabled(false); this.enginesPickList.setValues(new String[]{}); this.groupsPickList.setValues(new String[]{}); this.newClass = true; this.removeButton.setDisabled(true); } }
Source:
public int hashCode() { return HashUtil.combineHashCodes(super.hashCode(), onEntryAction.hashCode(), onExitAction.hashCode(), isAsync.hashCode()); }

Target:
public int hashCode() { return HashUtil.combineHashCodes(super.hashCode(), Objects.hashCode(onEntryAction), Objects.hashCode(onExitAction), Objects.hashCode(isAsync)); }
Source:
protected void onRestoreInstanceState(final Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); usernameEdit.setText(savedInstanceState.getString(Save_username)); passwordEdit.setText(savedInstanceState.getString(Save_password)); if(savedInstanceState.getBoolean(Save_progressDailog)){ performLogin(); } String errorMessage=savedInstanceState.getString(Save_errorMessage); if(sessionManager.isUserLoggedIn()){ showMessage(R.string.login_success, R.color.primaryDarkColor); }else{ showMessage(errorMessage, R.color.secondaryDarkColor); } }

Target:
protected void onRestoreInstanceState(final Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); usernameEdit.setText(savedInstanceState.getString(saveUsername)); passwordEdit.setText(savedInstanceState.getString(savePassword)); if(savedInstanceState.getBoolean(saveProgressDailog)) { performLogin(); } String errorMessage=savedInstanceState.getString(saveErrorMessage); if(sessionManager.isUserLoggedIn()) { showMessage(R.string.login_success, R.color.primaryDarkColor); } else { showMessage(errorMessage, R.color.secondaryDarkColor); } }
Source:
public INDArray createFromNpyFile(File file) { byte[] pathBytes = file.getAbsolutePath().getBytes(Charset.forName("UTF-8" )); String otherBytes = new String(pathBytes); System.out.println(otherBytes); ByteBuffer directBuffer = ByteBuffer.allocateDirect(pathBytes.length).order(ByteOrder.nativeOrder()); directBuffer.put(pathBytes); directBuffer.put(pathBytes); directBuffer.rewind(); directBuffer.position(0); Pointer pointer = nativeOps.numpyFromFile(new BytePointer(directBuffer)); return createFromNpyPointer(pointer); }

Target:
public INDArray createFromNpyFile(File file) { byte[] pathBytes = file.getAbsolutePath().getBytes(Charset.forName("UTF-8" )); String otherBytes = new String(pathBytes); System.out.println(otherBytes); ByteBuffer directBuffer = ByteBuffer.allocateDirect(pathBytes.length).order(ByteOrder.nativeOrder()); directBuffer.put(pathBytes); directBuffer.rewind(); directBuffer.position(0); Pointer pointer = nativeOps.numpyFromFile(new BytePointer(directBuffer)); INDArray result = createFromNpyPointer(pointer); nativeOps.releaseNumpy(pointer); return result; }
Source:
public Iterable<? extends String> getAllKeys() throws OseeCoreException { Set<String> userIds = new LinkedHashSet<String>(); List<Artifact> artifacts = ArtifactQuery.getArtifactListFromType(CoreArtifactTypes.User, CoreBranches.COMMON); for (Artifact artifact : artifacts) { User user = (User) artifact; userIds.add(user.getUserId()); } return userIds; }

Target:
public Iterable<? extends String> getAllKeys() throws OseeCoreException { return get(); }
Source:
public void testAudioTrackInfoOp() { if (!Utils.hasTvInputFramework(getContext())) { return; } Bundle bundle = new Bundle(); TvTrackInfo info = new TvTrackInfo.Builder(TvTrackInfo.TYPE_AUDIO, "id") .setAudioChannelCount(2) .setAudioSampleRate(48000) .setLanguage("eng") .setExtra(bundle) .build(); assertEquals(TvTrackInfo.TYPE_AUDIO, info.getType()); assertEquals("id", info.getId()); assertEquals(2, info.getAudioChannelCount()); assertEquals(48000, info.getAudioSampleRate()); assertEquals("eng", info.getLanguage()); assertEquals(bundle, info.getExtra()); assertEquals(0, info.describeContents()); Parcel p = Parcel.obtain(); info.writeToParcel(p, 0); p.setDataPosition(0); TvTrackInfo infoFromParcel = TvTrackInfo.CREATOR.createFromParcel(p); assertEquals(TvTrackInfo.TYPE_AUDIO, infoFromParcel.getType()); assertEquals("id", infoFromParcel.getId()); assertEquals(2, infoFromParcel.getAudioChannelCount()); assertEquals(48000, infoFromParcel.getAudioSampleRate()); assertEquals("eng", infoFromParcel.getLanguage()); assertEquals(bundle, infoFromParcel.getExtra()); assertEquals(0, infoFromParcel.describeContents()); p.recycle(); }

Target:
public void testAudioTrackInfoOp() { if (!Utils.hasTvInputFramework(getContext())) { return; } final Bundle bundle = new Bundle(); final TvTrackInfo info = new TvTrackInfo.Builder(TvTrackInfo.TYPE_AUDIO, "id_audio") .setAudioChannelCount(2) .setAudioSampleRate(48000) .setLanguage("eng") .setExtra(bundle) .build(); assertEquals(TvTrackInfo.TYPE_AUDIO, info.getType()); assertEquals("id_audio", info.getId()); assertEquals(2, info.getAudioChannelCount()); assertEquals(48000, info.getAudioSampleRate()); assertEquals("eng", info.getLanguage()); assertEquals(bundle.get("testTrue"), info.getExtra().get("testTrue")); assertEquals(0, info.describeContents()); Parcel p = Parcel.obtain(); info.writeToParcel(p, 0); p.setDataPosition(0); TvTrackInfo infoFromParcel = TvTrackInfo.CREATOR.createFromParcel(p); assertEquals(TvTrackInfo.TYPE_AUDIO, infoFromParcel.getType()); assertEquals("id_audio", infoFromParcel.getId()); assertEquals(2, infoFromParcel.getAudioChannelCount()); assertEquals(48000, infoFromParcel.getAudioSampleRate()); assertEquals("eng", infoFromParcel.getLanguage()); assertEquals(bundle.get("testTrue"), infoFromParcel.getExtra().get("testTrue")); assertEquals(0, infoFromParcel.describeContents()); p.recycle(); }
Source:
static long nanoToMicro(long nano) { return Math.max(1, (long) Math.ceil(nano / (double) 1000)); }

Target:
static long nanoToMicro(long nano) { return (nano + 1000) / 1000L; }
Source:
public void writeStartPage(Page page) throws IOException { XmlWriter writer = this.writer; writer.openElement("page"); writer.textElement("title", page.Title.toString()); writer.textElement("ns", Integer.toString(page.Ns)); writer.textElement("id", Integer.toString(page.Id)); if (page.Redirect != null) { writer.emptyElement("redirect", new String[][] { {"title", page.Redirect.toString()} }); } if (page.Restrictions != null && page.Restrictions.length() != 0) writer.textElement("restrictions", page.Restrictions); }

Target:
public void writeStartPage(Page page) throws IOException { XmlWriter writer = this.writer; writer.openElement("page"); writer.textElement("title", page.Title.toString()); writer.textElement("ns", Integer.toString(page.Ns)); if (page.Id != 0) { writer.textElement("id", Integer.toString(page.Id)); } if (page.Redirect != null) { writer.emptyElement("redirect", new String[][] { {"title", page.Redirect.toString()} }); } if (page.Restrictions != null && page.Restrictions.length() != 0) writer.textElement("restrictions", page.Restrictions); }
Source:
public UserDto updateUserPhoto(UUID id, Optional<UUID> userPhotoId) { User userEntity = getUserEntityById(id); UserDto originalUser = createUserDtoWithPrivateData(userEntity); userEntity.setUserPhotoId(userPhotoId); User savedUserEntity = userRepository.save(userEntity); UserDto userDto = createUserDtoWithPrivateData(savedUserEntity); logger.info("Updated user photo for user with mobile number '{}' and ID '{}'", userDto.getMobileNumber(), userDto.getId()); buddyService.broadcastUserInfoChangeToBuddies(savedUserEntity, originalUser); return userDto; }

Target:
public UserDto updateUserPhoto(UUID id, Optional<UUID> userPhotoId) { User userEntity = getUserEntityById(id); UserDto originalUser = createUserDtoWithPrivateData(userEntity); userEntity.setUserPhotoId(userPhotoId); User savedUserEntity = userRepository.save(userEntity); UserDto userDto = createUserDtoWithPrivateData(savedUserEntity); if (userPhotoId.isPresent()) { logger.info("Updated user photo for user with mobile number '{}' and ID '{}'", userDto.getMobileNumber(), userDto.getId()); } else { logger.info("Deleted user photo for user with mobile number '{}' and ID '{}'", userDto.getMobileNumber(), userDto.getId()); } buddyService.broadcastUserInfoChangeToBuddies(savedUserEntity, originalUser); return userDto; }
Source:
public void assertCanDelete(Project project) throws CannotDeleteProjectException { final Connection conn = ((JdbcSchema) db).getConnection(); final String projectName = project.getName(); try { if (conn.createStatement().executeQuery("SELECT * FROM submodule_subscriptions WHERE " + "super_project_project_name = '" + projectName + "'").first()) { throw new CannotDeleteProjectException("Project has subscribed submodules."); } if (conn.createStatement().executeQuery("SELECT * FROM submodule_subscriptions WHERE " + "submodule_project_name = '" + projectName + "'").first()) { throw new CannotDeleteProjectException("Project is subscribed by other projects."); } } catch (SQLException e) { throw new CannotDeleteProjectException(e); } }

Target:
public void assertCanDelete(Project project) throws CannotDeleteProjectException, OrmException { final Connection conn = ((JdbcSchema) db).getConnection(); final String projectName = project.getName(); try { if (conn.createStatement().executeQuery("SELECT * FROM submodule_subscriptions WHERE " + "super_project_project_name = '" + projectName + "'").first()) { throw new CannotDeleteProjectException("Project has subscribed submodules."); } if (conn.createStatement().executeQuery("SELECT * FROM submodule_subscriptions WHERE " + "submodule_project_name = '" + projectName + "'").first()) { throw new CannotDeleteProjectException("Project is subscribed by other projects."); } } catch (SQLException e) { throw new OrmException(e); } }
Source:
public Response toResponse(ServiceException exception) { int httpStatus = exception.getErrorType().httpErrorCode(); if (Response.Status.Family.familyOf(httpStatus) .equals(Response.Status.Family.CLIENT_ERROR)) { log.info("Error handling request {}", SafeArg.of("errorId", exception.getErrorId()), exception); } else { log.error("Error handling request {}", SafeArg.of("errorId", exception.getErrorId()), exception); } ResponseBuilder builder = Response.status(httpStatus); try { SerializableError error = SerializableError.forException(exception); builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorId", exception.getErrorId()), e); builder = Response.status(httpStatus); builder.type(MediaType.TEXT_PLAIN); builder.entity(Objects.toString(exception.getMessage())); } return builder.build(); }

Target:
public Response toResponse(ServiceException exception) { int httpStatus = exception.getErrorType().httpErrorCode(); if (Response.Status.Family.familyOf(httpStatus) .equals(Response.Status.Family.CLIENT_ERROR)) { log.info("Error handling request {}", SafeArg.of("errorInstanceId", exception.getErrorInstanceId()), exception); } else { log.error("Error handling request {}", SafeArg.of("errorInstanceId", exception.getErrorInstanceId()), exception); } ResponseBuilder builder = Response.status(httpStatus); try { SerializableError error = SerializableError.builder() .from(SerializableError.forException(exception)) .message("Refer to the server logs with this errorInstanceId: " + exception.getErrorInstanceId()) .build(); builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", SafeArg.of("errorInstanceId", exception.getErrorInstanceId()), e); builder.type(MediaType.TEXT_PLAIN); builder.entity("Unable to translate exception to json. Refer to the server logs with this errorInstanceId: " + exception.getErrorInstanceId()); } return builder.build(); }
Source:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }

Target:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); final List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }
Source:
public void UpdateDynamicData(VdsDynamic dynamicData) { if (dynamicData != null && _vds != null && _vds.getDynamicData() != null && (!dynamicData.equals(_vds.getDynamicData()) || dynamicData.getprevious_status() != dynamicData.getStatus())) { DbFacade.getInstance().getVdsDynamicDao().update(dynamicData); } else { log.debug("Ignoring unneeded update of VDSDynamic"); } }

Target:
public void UpdateDynamicData(VdsDynamic dynamicData) { log.debug("Updated VDS dynamic without checking if update is needed"); DbFacade.getInstance().getVdsDynamicDao().update(dynamicData); }
Source:
void convertWithServiceEventData() { ActorBase actor = ActorCrn.builder().withActorCrn(USER_CRN).build(); EventData eventData = ServiceEventData.builder() .withVersion(SERVICE_EVENT_VERSION) .withEventDetails(SERVICE_EVENT_DETAILS) .build(); AuditEvent source = makeAuditEvent(actor, eventData); underTest = new AuditEventToGrpcAuditEventConverter(createMockUtilizer(ServiceEventData.class)); AuditProto.AuditEvent target = underTest.convert(source); assertGeneric(target); verify(mockEventDataUtilizer, times(1)).modifyAuditEventBuilderWithEventData(any(), any()); }

Target:
void convertWithServiceEventData() { ActorBase actor = ActorCrn.builder().withActorCrn(USER_CRN).build(); EventData eventData = ServiceEventData.builder() .withVersion(SERVICE_EVENT_VERSION) .withEventDetails(SERVICE_EVENT_DETAILS) .build(); AuditEvent source = makeAuditEvent(actor, eventData); underTest = new AuditEventToGrpcAuditEventConverter(createMockUtilizer(ServiceEventData.class), mockBuilderProvider); underTest.convert(source); assertGeneric(); verify(mockAuditEventBuilderUpdater, times(1)).update(any(), any()); }
Source:
public void escapeHTMLCharsInAttributes() throws Exception { String htmlInput = "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"; Document document = this.cleaner.clean(new StringReader(htmlInput)); String textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff", textContent); htmlInput = "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"; document = this.cleaner.clean(new StringReader(htmlInput)); textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff", textContent); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>", "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>", "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"); }

Target:
void escapeHTMLCharsInAttributes() throws Exception { String htmlInput = "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"; Document document = this.cleaner.clean(new StringReader(htmlInput)); String textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa\"bbb&ccc>ddd<eee'fff", textContent); htmlInput = "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"; document = this.cleaner.clean(new StringReader(htmlInput)); textContent = document.getElementsByTagName("div").item(0).getAttributes().getNamedItem("foo").getTextContent(); assertEquals("aaa\"bbb&ccc>ddd<eee'fff", textContent); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee'fff\">content</div>", "<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff\">content</div>"); assertHTML("<div foo=\"aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee'fff\">content</div>", "<div foo='aaa&quot;bbb&amp;ccc&gt;ddd&lt;eee&apos;fff'>content</div>"); }