auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void fails_with_ISE_when_default_organization_does_not_exist_in_table_ORGANIZATIONS() throws SQLException { insertDefaultOrganizationUuid("blabla"); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Default organization with uuid 'blabla' does not exist in table ORGANIZATIONS"); underTest.execute(); }

Target:
public void fails_with_ISE_when_default_organization_does_not_exist_in_table_ORGANIZATIONS() throws SQLException { setDefaultOrganizationProperty("blabla"); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Default organization with uuid 'blabla' does not exist in table ORGANIZATIONS"); underTest.execute(); }
Source:
protected static byte[] getSignedContent(String queryString) throws SecurityPolicyException { log.debug("Constructing signed content string from URL query string "+queryString ); String constructed = buildSignedContentString(queryString); if (DatatypeHelper.isEmpty(constructed)) { throw new SecurityPolicyException( "Could not extract signed content string from query string"); } log.debug("Constructed signed content string for HTTP-Redirect DEFLATE "+ constructed); try { return constructed.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug("Encoding not supported.", e); } return new byte[0]; } }

Target:
protected static byte[] getSignedContent(String queryString) throws SecurityPolicyException { if (log.isDebugEnabled()) { log.debug("Constructing signed content string from URL query string " + queryString); } String constructed = buildSignedContentString(queryString); if (DatatypeHelper.isEmpty(constructed)) { throw new SecurityPolicyException( "Could not extract signed content string from query string"); } if (log.isDebugEnabled()) { log.debug("Constructed signed content string for HTTP-Redirect DEFLATE " + constructed); } try { return constructed.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { if (log.isDebugEnabled()) { log.debug("Encoding not supported.", e); } return new byte[0]; } }
Source:
int invalidMethodReturningPrimitive() { assertTrue(false); return 1; }

Target:
int invalidMethodReturningPrimitive() { fail("This method should never have been called."); return 1; }
Source:
public ArrayList<DiskErrorPolicy> getDiskErrorPolicyList() { ArrayList<DiskErrorPolicy> diskErrorPolicy = new ArrayList<>( Arrays.asList(new DiskErrorPolicy[] { DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE })); return diskErrorPolicy; }

Target:
public List<DiskErrorPolicy> getDiskErrorPolicyList() { return Arrays.asList( DiskErrorPolicy.REPORT, DiskErrorPolicy.ENOSPC, DiskErrorPolicy.STOP, DiskErrorPolicy.IGNORE ); }
Source:
public void testResourceMetadataXML() throws Exception { XMLUnit.setXpathNamespaceContext(NS_XML); Document doc = getAsDOM("/rest/resource/mydir/myres?operation=metadata&format=xml"); XMLAssert.assertXpathEvaluatesTo("myres", "/ResourceMetadata/name", doc); XMLAssert.assertXpathEvaluatesTo("/mydir", "/ResourceMetadata/parent/path", doc); XMLAssert.assertXpathEvaluatesTo("http://localhost:8080/geoserver/rest/resources/mydir?format=xml", "/ResourceMetadata/parent/atom:link/@href", doc); XMLAssert.assertXpathEvaluatesTo(FORMAT.format(myRes.lastmodified()), "/ResourceMetadata/lastModified", doc); }

Target:
public void testResourceMetadataXML() throws Exception { XMLUnit.setXpathNamespaceContext(NS_XML); Document doc = getAsDOM("/rest/resource/mydir/myres?operation=mEtAdATa&format=xml"); XMLAssert.assertXpathEvaluatesTo("myres", "/ResourceMetadata/name", doc); XMLAssert.assertXpathEvaluatesTo("/mydir", "/ResourceMetadata/parent/path", doc); XMLAssert.assertXpathEvaluatesTo("http://localhost:8080/geoserver/rest/resources/mydir?format=xml", "/ResourceMetadata/parent/atom:link/@href", doc); XMLAssert.assertXpathEvaluatesTo(FORMAT.format(myRes.lastmodified()), "/ResourceMetadata/lastModified", doc); }
Source:
public void refresh() { AccountDiffPreference diffPrefs; if (patchTable == null) { diffPrefs = (new ListenableAccountDiffPreference()).get(); } else { diffPrefs = patchTable.getPreferences().get(); } Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs, new GerritCallback<PatchSetDetail>() { @Override public void onSuccess(PatchSetDetail result) { if (patchSet.getId().equals(diffBaseId)) { patchTable.setVisible(false); actionsPanel.setVisible(false); } else { if (patchTable != null) { patchTable.removeFromParent(); } patchTable = new PatchTable(); patchTable.setPatchSetIdToCompareWith(diffBaseId); patchTable.display(result); body.add(patchTable); for (ClickHandler clickHandler : registeredClickHandler) { patchTable.addClickHandler(clickHandler); } } } }); }

Target:
public void refresh() { AccountDiffPreference diffPrefs; if (patchTable == null) { diffPrefs = new ListenableAccountDiffPreference().get(); } else { diffPrefs = patchTable.getPreferences().get(); } Util.DETAIL_SVC.patchSetDetail(patchSet.getId(), diffBaseId, diffPrefs, new GerritCallback<PatchSetDetail>() { @Override public void onSuccess(PatchSetDetail result) { if (patchSet.getId().equals(diffBaseId)) { patchTable.setVisible(false); actionsPanel.setVisible(false); } else { if (patchTable != null) { patchTable.removeFromParent(); } patchTable = new PatchTable(); patchTable.setPatchSetIdToCompareWith(diffBaseId); patchTable.display(result); body.add(patchTable); for (ClickHandler clickHandler : registeredClickHandler) { patchTable.addClickHandler(clickHandler); } } } }); }
Source:
public void iterableRemoves(Iterable<?> iterable, Object value) { if (iterable == null) return; if (iterable instanceof Collection) { ((Collection<?>) iterable).removeIf(o -> comparator.compare(o, value) == 0); } Iterator<?> iterator = iterable.iterator(); while (iterator.hasNext()) { if (comparator.compare(iterator.next(), value) == 0) { iterator.remove(); } } }

Target:
public void iterableRemoves(Iterable<?> iterable, Object value) { if (iterable == null) return; if (iterable instanceof Collection) { ((Collection<?>) iterable).removeIf(o -> comparator.compare(o, value) == 0); } else { Iterator<?> iterator = iterable.iterator(); while (iterator.hasNext()) { if (comparator.compare(iterator.next(), value) == 0) { iterator.remove(); } } } }
Source:
private void marshallAttributes(XMLExtendedStreamWriter writer, ModelNode model, Collection<AttributeDefinition> attributes, String group) throws XMLStreamException { boolean started = false; boolean possibleElements = attributes.stream().filter(attributeDefinition -> attributeDefinition.getParser().isParseAsElement()).count() > 0; for (AttributeDefinition ad : attributes.stream().sorted((o1, o2) -> o1.getParser().isParseAsElement() ? 1 : -1).collect(Collectors.toList())) { AttributeMarshaller marshaller = attributeMarshallers.getOrDefault(ad.getName(), ad.getAttributeMarshaller()); if (marshaller.isMarshallable(ad, model, true)) { if (!started && group != null) { if (possibleElements) { writer.writeStartElement(group); } else { writer.writeEmptyElement(group); } started = true; } marshaller.marshall(ad, model, marshallDefaultValues, writer); } } if (possibleElements && started) { writer.writeEndElement(); } }

Target:
private void marshallAttributes(XMLExtendedStreamWriter writer, ModelNode model, Collection<AttributeDefinition> attributes, String group) throws XMLStreamException { boolean started = false; boolean possibleElements = attributes.stream().filter(attributeDefinition -> attributeDefinition.getParser().isParseAsElement()).count() > 0; for (AttributeDefinition ad : attributes.stream().sorted((o1, o2) -> o1.getParser().isParseAsElement() ? 1 : -1).collect(Collectors.toList())) { AttributeMarshaller marshaller = attributeMarshallers.getOrDefault(ad.getName(), ad.getAttributeMarshaller()); if (marshaller.isMarshallable(ad, model, marshallDefaultValues)) { if (!started && group != null) { if (possibleElements) { writer.writeStartElement(group); } else { writer.writeEmptyElement(group); } started = true; } marshaller.marshall(ad, model, marshallDefaultValues, writer); } } if (possibleElements && started) { writer.writeEndElement(); } }
Source:
public CoordinatorBasicAuthenticatorCacheNotifier( AuthenticatorMapper authenticatorMapper, DruidNodeDiscoveryProvider discoveryProvider, @EscalatedClient HttpClient httpClient ) { userCacheNotifier = new CommonCacheNotifier( initAuthenticatorConfigMap(authenticatorMapper), discoveryProvider, httpClient, "/druid-ext/basic-security/authentication/listen/%s", "CoordinatorBasicAuthenticatorCacheNotifier" ); configCacheNotifier = new CommonCacheNotifier( initAuthenticatorConfigMap(authenticatorMapper), discoveryProvider, httpClient, "/druid-ext/basic-security/authentication/listen/config/%s", "CoordinatorBasicAuthenticatorCacheNotifier" ); }

Target:
public CoordinatorBasicAuthenticatorCacheNotifier( AuthenticatorMapper authenticatorMapper, DruidNodeDiscoveryProvider discoveryProvider, @EscalatedClient HttpClient httpClient ) { userCacheNotifier = new CommonCacheNotifier( initAuthenticatorConfigMap(authenticatorMapper), discoveryProvider, httpClient, "/druid-ext/basic-security/authentication/listen/%s", "CoordinatorBasicAuthenticatorCacheNotifier" ); }
Source:
public static Slice emptyApproxSet(@SqlType(StandardTypes.DOUBLE) double maxStandardError) { return HyperLogLog.newInstance(ApproximateCountDistinctAggregation.standardErrorToBuckets(maxStandardError)).serialize(); }

Target:
public static Slice emptyApproxSet(@SqlType(StandardTypes.DOUBLE) double maxStandardError) { return HyperLogLog.newInstance(standardErrorToBuckets(maxStandardError)).serialize(); }
Source:
protected boolean isOkToCreateFile(File sourceFile) { String fname = sourceFile.getName(); if (fname.equals(TEMPLATE_ACTIVATOR_FILENAME)) return mustGenerateActivator; if (fname.equals(TEMPLATE_LIFECYCLE_FILENAME)) return getBooleanOption(KEY_CREATE_LIFE_CYCLE); if (fname.endsWith(E4_MODEL_FILE)) { boolean createSampleContent = getBooleanOption(KEY_CREATE_SAMPLE_CONTENT); if (sourceFile.getAbsolutePath().contains(BIN_FOLDER)) { return !createSampleContent; } return createSampleContent; } return super.isOkToCreateFile(sourceFile); }

Target:
protected boolean isOkToCreateFile(File sourceFile) { String fname = sourceFile.getName(); if (fname.equals(TEMPLATE_ACTIVATOR_FILENAME)) return mustGenerateActivator; if (fname.equals(TEMPLATE_LIFECYCLE_FILENAME)) return getBooleanOption(KEY_CREATE_LIFE_CYCLE); if (fname.endsWith(E4_MODEL_FILE)) { if (sourceFile.getAbsolutePath().endsWith(EMPTY_E4_MODEL_FILE)) return !getBooleanOption(KEY_CREATE_SAMPLE_CONTENT); return getBooleanOption(KEY_CREATE_SAMPLE_CONTENT); } return super.isOkToCreateFile(sourceFile); }
Source:
public void flush() { network.setDataCenterId(getSelectedDc().getId()); network.setName(getName().getEntity()); network.setStp(getIsStpEnabled().getEntity()); network.setDescription(getDescription().getEntity()); network.setComment(getComment().getEntity()); network.setVmNetwork(getIsVmNetwork().getEntity()); String label = getNetworkLabel().getSelectedItem(); network.setLabel(label == null || !label.isEmpty() ? label : null); network.setMtu(0); if (getMtu().getIsChangable() && isCustomMtu()) { network.setMtu(Integer.parseInt(getMtu().getEntity().toString())); } network.setVlanId(null); if (getHasVLanTag().getEntity()) { network.setVlanId(Integer.parseInt(getVLanTag().getEntity().toString())); } for (VnicProfileModel profileModel : getProfiles().getItems()) { profileModel.flush(); } if (getQos().getIsChangable()) { NetworkQoS qos = getQos().getSelectedItem(); network.setQosId(qos == NetworkQoSModel.EMPTY_QOS ? null : qos.getId()); } }

Target:
public void flush() { network.setDataCenterId(getSelectedDc().getId()); network.setName(getName().getEntity()); network.setStp(getIsStpEnabled().getEntity()); network.setDescription(getDescription().getEntity()); network.setComment(getComment().getEntity()); network.setVmNetwork(getIsVmNetwork().getEntity()); String label = getNetworkLabel().getSelectedItem(); network.setLabel(label == null || !label.isEmpty() ? label : null); network.setMtu(0); if (getMtu().getIsChangable()) { network.setMtu(Integer.parseInt(getMtu().getEntity().toString())); } network.setVlanId(null); if (getHasVLanTag().getEntity()) { network.setVlanId(Integer.parseInt(getVLanTag().getEntity().toString())); } for (VnicProfileModel profileModel : getProfiles().getItems()) { profileModel.flush(); } if (getQos().getIsChangable()) { NetworkQoS qos = getQos().getSelectedItem(); network.setQosId(qos == NetworkQoSModel.EMPTY_QOS ? null : qos.getId()); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LoggingEventKey that = (LoggingEventKey) o; return level == that.level && Objects.equals(message, that.message) && Arrays.equals(params, that.params) && Objects.equals(marker, that.marker); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LoggingEventKey that = (LoggingEventKey) o; return level == that.level && Objects.equals(message, that.message) && Objects.equals(marker, that.marker) && Arrays.equals(params, that.params); }
Source:
public void testLogManager() throws Exception { System.setProperty("test.log.file", "test-hc-jbl.log"); if (isIbmJdk()) { try (InputStream in = getClass().getResourceAsStream("/jbl-logging.properties")) { Assert.assertNotNull("Failed to find the logging.properties file", in); LogManager.getLogManager().readConfiguration(in); } } System.setProperty("logging.configuration", getClass().getResource("/jbl-logging.properties").toExternalForm()); System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); testHostController(Configuration.LoggerHint.JBOSS_LOG_MANAGER, "test-standalone-jbl.log", "[jboss-logmanager]"); }

Target:
public void testLogManager() throws Exception { System.setProperty("test.log.file", "test-hc-jbl.log"); if (isIbmJdk()) { try (InputStream in = getClass().getResourceAsStream("/jbl-logging.properties")) { Assert.assertNotNull("Failed to find the logging.properties file", in); LogManager.getLogManager().readConfiguration(in); } } System.setProperty("logging.configuration", getClass().getResource("/jbl-logging.properties").toExternalForm()); System.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); testHostController(Configuration.LoggerHint.JBOSS_LOG_MANAGER, "test-hc-jbl.log", "[jboss-logmanager]"); }
Source:
public static List<String> extractBaseImages(File dockerFile, FixedStringSearchInterpolator interpolator) throws IOException { List<String[]> fromLines = extractLines(dockerFile, "FROM", interpolator); LinkedList<String> result = new LinkedList<>(); Map<String, String> fromAlias = new HashMap<>(); for (String[] fromLine : fromLines) { if (fromLine.length > 1) { if (fromLine.length == 2) { result.add(fromLine[1]); } else if (fromLine.length == 4) { if (!fromAlias.containsKey(fromLine[1])) { result.add(fromLine[1]); } fromAlias.put(fromLine[3], fromLine[1]); } } } return result; }

Target:
public static List<String> extractBaseImages(File dockerFile, FixedStringSearchInterpolator interpolator) throws IOException { List<String[]> fromLines = extractLines(dockerFile, "FROM", interpolator); Set<String> result = new LinkedHashSet<>(); Set<String> fromAlias = new HashSet<>(); for (String[] fromLine : fromLines) { if (fromLine.length > 1) { if (fromLine.length == 2) { result.add(fromLine[1]); } else if (fromLine.length == 4) { if (!fromAlias.contains(fromLine[1])) { result.add(fromLine[1]); } fromAlias.add(fromLine[3]); } } } return result.stream().collect(Collectors.toList()); }
Source:
public int hashCode() { return element.hashCode(); }

Target:
public int hashCode() { if (element == null) { return super.hashCode(); } return element.hashCode(); }
Source:
public void testRequirements() { IKernelTrace trace = fTrace; assertNotNull(trace); IKernelAnalysisEventLayout layout = trace.getKernelEventLayout(); Set<String> expected = ImmutableSet.of(layout.eventSchedSwitch()); Iterable<TmfAnalysisRequirement> requirements = fModule.getAnalysisRequirements(); Set<String> actual = new HashSet<>(); for (TmfAnalysisRequirement req : requirements) { actual.addAll(req.getValues()); } assertEquals(expected, actual); }

Target:
public void testRequirements() { IKernelTrace trace = fTrace; assertNotNull(trace); IKernelAnalysisEventLayout layout = trace.getKernelEventLayout(); Set<String> expected = ImmutableSet.of(layout.eventSchedSwitch()); Set<String> actual = StreamSupport.stream(fModule.getAnalysisRequirements().spliterator(), false) .flatMap(req -> req.getValues().stream()) .collect(Collectors.toSet()); assertEquals(expected, actual); }
Source:
public void verifyPagination(){ waitForElementByElement(paginationContainer); for (WebElement elem:paginationPages){ } }

Target:
public void verifyPagination() { waitForElementByElement(paginationContainer); int i=1; for (WebElement elem:paginationPages) { Assertion.assertEquals(Integer.toString(i), elem.getText()); i++; } }
Source:
private void handleMetadata(BufferedInputStream parser, ITmfTrace trace, String dir) throws IOException { List<String> processes = new ArrayList<>(); String processString = JsonTrace.readNextEventString(() -> (char) parser.read()); while (processString != null) { processes.add(processString); processString = JsonTrace.readNextEventString(() -> (char) parser.read()); if (processString == null) { break; } } if (!processes.isEmpty()) { String filePath = trace.getPath().replaceAll(".json", "Processes.json"); File processFile = new File(dir + File.separator + new File(filePath).getName()); processFile.createNewFile(); try (PrintWriter tempWriter = new PrintWriter(processFile)) { tempWriter.println('['); for (int j = 0; j < processes.size() - 1; j++) { tempWriter.println(processes.get(j) + ','); } tempWriter.println(processes.get(processes.size() - 1) + "\n]"); } } }

Target:
protected abstract void handleMetadata(BufferedInputStream parser, ITmfTrace trace, String dir) throws IOException; private static @Nullable Pair readNextEvent(BufferedInputStream parser, String key, int i) throws IOException { String event = JsonTrace.readNextEventString(() -> (char) parser.read()); return event == null ? null : new Pair(key, event, i); }
Source:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { return isModified(null, false, null); }

Target:
public boolean isModified(DirCacheEntry entry, boolean forceContentCheck) { return isModified(entry, false, null); }
Source:
protected DocumentModel createPrincipal(Map<String, Serializable> attributes) { DocumentModel userModel = getUserManager().getBareUserModel(); userModel.getDataModel(getUserManager().getUserSchemaName()).setMap((Map) attributes); return getUserManager().createUser(userModel); }

Target:
protected DocumentModel createPrincipal(Map<String, Serializable> attributes) { UserManager userManager = getUserManager(); DocumentModel userModel = userManager.getBareUserModel(); userModel.getDataModel(userManager.getUserSchemaName()).setMap((Map) attributes); return userManager.createUser(userModel); }
Source:
protected Traverser.Admin<E> processNextStart() { while (true) { if (this.iterator.hasNext()) { return this.head.split(this.iterator.next(), this); } else { this.head = this.starts.next(); closeIterator(); this.iterator = this.flatMap(this.head); } } }

Target:
protected Traverser.Admin<E> processNextStart() { while (true) { if (this.iterator.hasNext()) { return this.head.split(this.iterator.next(), this); } else { closeIterator(); this.head = this.starts.next(); this.iterator = this.flatMap(this.head); } } }
Source:
protected void setNoCache(final HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); }

Target:
protected void setNoCache(final HttpServletResponse response) { response.setHeader("Cache-Control", "max-age=0, must-revalidate, no-cache, no-store"); }
Source:
public ArrayList<WebLocation> getBookmarks() { return bookmarksData; }

Target:
public List<Bookmark> getBookmarks() { return bookmarks; }
Source:
private final void closeStatements() { final int size = openStatements.size(); if (size > 0) { for (int i = 0; i < size; i++) { try { final Statement statement = openStatements.get(i); if (statement != null) { statement.close(); } } catch (SQLException e) { checkException(e); if (delegate == ClosedConnection.CLOSED_CONNECTION) { break; } } } openStatements.clear(); } }

Target:
private final void closeStatements() { final int size = openStatements.size(); if (size > 0) { for (int i = 0; i < size && delegate != ClosedConnection.CLOSED_CONNECTION; i++) { try { final Statement statement = openStatements.get(i); if (statement != null) { statement.close(); } } catch (SQLException e) { checkException(e); } } openStatements.clear(); } }
Source:
private Collection<ModuleDeploymentStatus> processResults(CuratorFramework client, ResultCollector collector) throws InterruptedException { Collection<ModuleDeploymentStatus> statuses = collector.getResults(); for (ModuleDeploymentStatus deploymentStatus : statuses) { if (deploymentStatus.getState() != ModuleDeploymentStatus.State.deployed) { logger.trace("Unsuccessful deployment: {}", deploymentStatus); String path = new ModuleDeploymentsPath() .setContainer(deploymentStatus.getContainer()) .setStreamName(deploymentStatus.getKey().getGroup()) .setModuleType(deploymentStatus.getKey().getType().toString()) .setModuleLabel(deploymentStatus.getKey().getLabel()).build(); try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (InterruptedException e) { throw e; } catch (KeeperException.NoNodeException e) { } catch (Exception e) { logger.warn("Error while cleaning up failed deployment " + path, e); } } } return statuses; }

Target:
private Collection<ModuleDeploymentStatus> processResults(CuratorFramework client, ResultCollector collector) throws InterruptedException { Collection<ModuleDeploymentStatus> statuses = collector.getResults(); for (ModuleDeploymentStatus deploymentStatus : statuses) { if (deploymentStatus.getState() != ModuleDeploymentStatus.State.deployed) { String path = new ModuleDeploymentsPath() .setContainer(deploymentStatus.getContainer()) .setStreamName(deploymentStatus.getKey().getGroup()) .setModuleType(deploymentStatus.getKey().getType().toString()) .setModuleLabel(deploymentStatus.getKey().getLabel()).build(); logger.debug("Unsuccessful deployment: {}; removing path {}", deploymentStatus, path); try { client.delete().deletingChildrenIfNeeded().forPath(path); } catch (InterruptedException e) { throw e; } catch (KeeperException.NoNodeException e) { } catch (Exception e) { logger.warn("Error while cleaning up failed deployment " + path, e); } } } return statuses; }
Source:
private void privateAssertLine(final String tag, final int status, final int missedBranches, final int coveredBranches) { final int nr = source.getLineNumber(tag); final ILine line = sourceCoverage.getLine(nr); final String lineMsg = String.format("line %s: %s", Integer.valueOf(nr), source.getLine(nr)); final int insnStatus = line.getInstructionCounter().getStatus(); assertEquals("Status in " + lineMsg, STATUS_NAME[status], STATUS_NAME[insnStatus]); assertEquals("Branches in " + lineMsg, CounterImpl.getInstance(missedBranches, coveredBranches), line.getBranchCounter()); }

Target:
private void privateAssertLine(final String tag, final int status, final int missedBranches, final int coveredBranches) { final int nr = source.getLineNumber(tag); final ILine line = sourceCoverage.getLine(nr); final String lineMsg = String.format("line %s: %s", Integer.valueOf(nr), source.getLine(nr)); final int insnStatus = line.getInstructionCounter().getStatus(); assertEquals("Instructions in " + lineMsg, STATUS_NAME[status], STATUS_NAME[insnStatus]); assertEquals("Branches in " + lineMsg, CounterImpl.getInstance(missedBranches, coveredBranches), line.getBranchCounter()); }
Source:
public void gotoClass(String packagePath, int line) { lastWentLine = line; final Project project = appContext.getRootProject(); String testSrcPath = project.getPath() + "/src/test/java/"; appContext.getWorkspaceRoot().getFile(testSrcPath + packagePath).then(new Operation<Optional<File>>() { @Override public void apply(Optional<File> file) throws OperationException { if (file.isPresent()) { eventBus.fireEvent(FileEvent.createOpenFileEvent(file.get())); Timer t = new Timer() { @Override public void run() { EditorPartPresenter editorPart = editorAgent.getActiveEditor(); Document doc = ((TextEditor) editorPart).getDocument(); doc.setCursorPosition(new TextPosition(lastWentLine - 1, 0)); } }; t.schedule(500); } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { Log.info(TestResultViewImpl.class, error); } }); }

Target:
public void gotoClass(String packagePath, int line) { lastWentLine = line; final Project project = appContext.getRootProject(); String testSrcPath = Paths.get(project.getPath(), MavenAttributes.DEFAULT_TEST_SOURCE_FOLDER).toString(); appContext.getWorkspaceRoot().getFile(testSrcPath + packagePath).then(new Operation<Optional<File>>() { @Override public void apply(Optional<File> file) throws OperationException { if (file.isPresent()) { eventBus.fireEvent(FileEvent.createOpenFileEvent(file.get())); Timer t = new Timer() { @Override public void run() { EditorPartPresenter editorPart = editorAgent.getActiveEditor(); Document doc = ((TextEditor) editorPart).getDocument(); doc.setCursorPosition(new TextPosition(lastWentLine - 1, 0)); } }; t.schedule(500); } } }).catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { Log.info(TestResultViewImpl.class, error); } }); }
Source:
public ApiQuotaInfo updateApiQuotaInfoInGui(ApiQuotaInfo apiQuotaInfo) { uiManager.updateApiQuotaInfo(apiQuotaInfo); return apiQuotaInfo; }

Target:
public void updateApiQuotaInfoInGui(ApiQuotaInfo apiQuotaInfo) { uiManager.updateApiQuotaInfo(apiQuotaInfo); }
Source:
private void updateNonPutOverheadMetrics(long microsWritingToTargetedSweepQueue, long microsForWrites, long microsForCommitStage) { long nonPutOverhead = microsForCommitStage - microsForWrites - microsWritingToTargetedSweepQueue; getTimer("nonPutOverhead").update(nonPutOverhead, TimeUnit.MILLISECONDS); getHistogram("nonPutOverheadMillionths").update( Math.round((1_000_000. * nonPutOverhead) / microsForCommitStage)); }

Target:
private void updateNonPutOverheadMetrics(long microsWritingToTargetedSweepQueue, long microsForWrites, long microsForCommitStage) { long nonPutOverhead = microsForCommitStage - microsForWrites - microsWritingToTargetedSweepQueue; getTimer("nonPutOverhead").update(nonPutOverhead, TimeUnit.MICROSECONDS); getHistogram("nonPutOverheadMillionths").update( Math.round((1_000_000. * nonPutOverhead) / microsForCommitStage)); }
Source:
public synchronized UsersSshPairImpl get(String owner, String service, String name) throws NotFoundException { final Optional<UsersSshPairImpl> any = find(owner, service, name); if (any.isPresent()) { return any.get(); } throw new NotFoundException(format("Ssh pair with service '%s' and name '%s' was not found.", name, service)); }

Target:
public SshPairImpl get(String owner, String service, String name) throws NotFoundException { lock.readLock().lock(); try { final Optional<SshPairImpl> any = find(owner, service, name); if (any.isPresent()) { return any.get(); } throw new NotFoundException(format("Ssh pair with service '%s' and name '%s' was not found.", service, name)); } finally { lock.readLock().unlock(); } }
Source:
private void reportFormExit() { TimedStatsTracker.registerExitForm(getCurrentFormTitle()); }

Target:
private void reportFormExit() { TimedStatsTracker.registerExitForm(getCurrentFormID()); }
Source:
protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap bmp = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); bmp = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return bmp; }

Target:
protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap bmp = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); bmp = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e(DownloadImageTask.class.getName(), "Error fetching bitmap", e); e.printStackTrace(); } return bmp; }
Source:
private void selectedKeyChanged() { String key = (String) getSelectedKey().getEntity(); List<GlusterVolumeOptionInfo> options = (List<GlusterVolumeOptionInfo>) getKeyList().getItems(); GlusterVolumeOptionInfo selectedOption = null; for (GlusterVolumeOptionInfo option : options) { if (option.getKey().equals(key.trim())) { selectedOption = option; break; } } if (selectedOption != null) { if (selectedOption.getDescription().equals("(null)")) { getDescription().setEntity(null); } else { getDescription().setEntity(selectedOption.getDescription()); } if (getIsNew()) { if (selectedOption.getDefaultValue().equals("(null)")) { getValue().setEntity(null); } else { getValue().setEntity(selectedOption.getDefaultValue()); } } } else if (getIsNew()) { getDescription().setEntity(null); getValue().setEntity(null); } }

Target:
private void selectedKeyChanged() { String key = (String) getSelectedKey().getEntity(); List<GlusterVolumeOptionInfo> options = (List<GlusterVolumeOptionInfo>) getKeyList().getItems(); GlusterVolumeOptionInfo selectedOption = null; for (GlusterVolumeOptionInfo option : options) { if (option.getKey().equals(key.trim())) { selectedOption = option; break; } } if (selectedOption != null) { if (selectedOption.getDescription() == null || selectedOption.getDescription().equals(NULL_CONST)) { getDescription().setEntity(null); } else { getDescription().setEntity(selectedOption.getDescription()); } if (getIsNew()) { if (selectedOption.getDefaultValue() == null || selectedOption.getDefaultValue().equals(NULL_CONST)) { getValue().setEntity(null); } else { getValue().setEntity(selectedOption.getDefaultValue()); } } } else if (getIsNew()) { getDescription().setEntity(null); getValue().setEntity(null); } }
Source:
public void unloadCube(int cubeX, int cubeY, int cubeZ) { if (cubeIsNearSpawn(cubeX, cubeY, cubeZ)) { return; } if (dependencyManager.isRequired(cubeX, cubeY, cubeZ)) { return; } this.cubesToUnload.add(AddressTools.getAddress(cubeX, cubeY, cubeZ)); }

Target:
public void unloadCube(int cubeX, int cubeY, int cubeZ) { if (cubeIsNearSpawn(cubeX, cubeY, cubeZ)) { return; } if (dependencyManager.isRequired(new CubeCoords(cubeX, cubeY, cubeZ))) { return; } this.cubesToUnload.add(AddressTools.getAddress(cubeX, cubeY, cubeZ)); }
Source:
public Void visitFilter(FilterNode node, Void context) { String expression = isExpression(node.getPredicate()) ? node.getPredicate().toString() : formatter.formatRowExpression(node.getPredicate()); printNode(node, "Filter", expression, NODE_COLORS.get(NodeType.FILTER)); return node.getSource().accept(this, context); }

Target:
public Void visitFilter(FilterNode node, Void context) { String expression = formatter.formatRowExpression(node.getPredicate()); printNode(node, "Filter", expression, NODE_COLORS.get(NodeType.FILTER)); return node.getSource().accept(this, context); }
Source:
protected synchronized ExitStatus run(OptionSet options) throws Exception { String text = StringUtils .collectionToDelimitedString(options.nonOptionArguments(), " "); System.out.println(URLEncoder.encode(text, "UTF-8")); return ExitStatus.OK; }

Target:
protected synchronized ExitStatus run(OptionSet options) throws Exception { String charset = "UTF-8"; if(options.has(charsetOption)){ charset = options.valueOf(charsetOption); } String text = StringUtils .collectionToDelimitedString(options.nonOptionArguments(), " "); try { Charset.forName(charset); String outText = URLEncoder.encode(text, charset); System.out.println(outText); return ExitStatus.OK; } catch (UnsupportedCharsetException e){ System.out.println("Unsupported Character Set"); return ExitStatus.ERROR; } }
Source:
public static AutomaticHardwareIdSpec parseId(String hardwareId) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); String hardwareSpec = hardwareId.substring(10); Map<String, String> specValues = Splitter.on(';') .trimResults() .omitEmptyStrings() .withKeyValueSeparator('=') .split(hardwareSpec); if (!specValues.containsKey("ram") || !specValues.containsKey("cores")) { throw new IllegalArgumentException(String.format("Omitted keys on hardwareId: %s", hardwareId)); } spec.ram = Integer.parseInt(specValues.get("ram")); spec.cores = Double.parseDouble(specValues.get("cores")); return spec; }

Target:
public static AutomaticHardwareIdSpec parseId(String hardwareId) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); String hardwareSpec = hardwareId.substring(10); Map<String, String> specValues = Splitter.on(';') .trimResults() .omitEmptyStrings() .withKeyValueSeparator('=') .split(hardwareSpec); if (!specValues.containsKey("ram") || !specValues.containsKey("cores")) { throw new IllegalArgumentException(String.format("Omitted keys on hardwareId: %s. Please set number " + "of cores and ram amount.", hardwareId)); } spec.ram = Integer.parseInt(specValues.get("ram")); spec.cores = Double.parseDouble(specValues.get("cores")); return spec; }
Source:
private static double[] calculateTargetFactors(final ReadCountCollection readCounts) { final double[] result = new double[readCounts.targets().size()]; final RealMatrix counts = readCounts.counts(); final Median medianCalculator = new Median(); for (int i = 0; i < result.length; i++) { result[i] = medianCalculator.evaluate(counts.getRow(i)); } return result; }

Target:
private static double[] calculateTargetFactors(final ReadCountCollection readCounts) { return MatrixSummaryUtils.getRowMedians(readCounts.counts()); }
Source:
public void MercuryCuratedNavigationTest_005_redirectToExistingArticle() { ArticleContent content = new ArticleContent(); String redirect = WikiTextContent.REDIRECT + WikiTextContent.LINK_PREFIX + MercurySubpages.CC_REDIRECT_DESTINATION + WikiTextContent.LINK_POSTFIX; content.push(redirect, MercurySubpages.CC_REDIRECT_SOURCE_1); ArticlePageObject article = new ArticlePageObject(driver); article.openCuratedMainPage(wikiURL, MercurySubpages.CC_REDIRECT_SOURCE_1); Assertion.assertEqualsIgnoreCase(article.getArticleTitle(), MercurySubpages.CC_REDIRECT_DESTINATION); }

Target:
public void MercuryCuratedNavigationTest_005_redirectToExistingArticle() { ArticlePageObject article = new ArticlePageObject(driver); String redirect = WikiTextContent.REDIRECT + WikiTextContent.INTERNAL_LINK_OPENING + MercurySubpages.CC_REDIRECT_DESTINATION + WikiTextContent.INTERNAL_LINK_CLOSING; new ArticleContent().push(redirect, MercurySubpages.CC_REDIRECT_SOURCE_1); article.openCuratedMainPage(wikiURL, MercurySubpages.CC_REDIRECT_SOURCE_1); Assertion.assertEqualsIgnoreCase(article.getArticleTitle(), MercurySubpages.CC_REDIRECT_DESTINATION); }
Source:
static Duration largestOf(Duration... durations) { Duration largest = Duration.ZERO; for (Duration duration : durations) { if (duration.compareTo(largest) > 0) { largest = duration; } } return largest; }

Target:
static Duration largestOf(Duration... durations) { return Arrays.stream(durations).max(Duration::compareTo).orElse(Duration.ZERO); }
Source:
public void cleanup() { networkProviderWidget.cleanup(); fenceAgentsEditor.cleanup(); proxySourceEditor.cleanup(); driver.cleanup(); }

Target:
public void cleanup() { driver.cleanup(); }
Source:
public AllSSTableOpStatus performCleanup(final ColumnFamilyStore cfStore, int jobs) throws InterruptedException, ExecutionException { assert !cfStore.isIndex(); Keyspace keyspace = cfStore.keyspace; if (!StorageService.instance.isJoined()) { logger.info("Cleanup cannot run before a node has joined the ring"); return AllSSTableOpStatus.ABORTED; } final Collection<Range<Token>> ranges = StorageService.instance.getLocalReplicas(keyspace.getName()).asRangeSet(); final boolean hasIndexes = cfStore.indexManager.hasIndexes(); return parallelAllSSTableOperation(cfStore, new OneSSTableOperation() { @Override public Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction) { List<SSTableReader> sortedSSTables = Lists.newArrayList(transaction.originals()); Collections.sort(sortedSSTables, SSTableReader.sizeComparator); return sortedSSTables; } @Override public void execute(LifecycleTransaction txn) throws IOException { CleanupStrategy cleanupStrategy = CleanupStrategy.get(cfStore, ranges, FBUtilities.nowInSeconds()); doCleanupOne(cfStore, txn, cleanupStrategy, ranges, hasIndexes); } }, jobs, OperationType.CLEANUP); }

Target:
public AllSSTableOpStatus performCleanup(final ColumnFamilyStore cfStore, int jobs) throws InterruptedException, ExecutionException { assert !cfStore.isIndex(); Keyspace keyspace = cfStore.keyspace; if (!StorageService.instance.isJoined()) { logger.info("Cleanup cannot run before a node has joined the ring"); return AllSSTableOpStatus.ABORTED; } final Collection<Range<Token>> ranges = StorageService.instance.getLocalReplicas(keyspace.getName()).asUnmodifiableRangeCollection(); final boolean hasIndexes = cfStore.indexManager.hasIndexes(); return parallelAllSSTableOperation(cfStore, new OneSSTableOperation() { @Override public Iterable<SSTableReader> filterSSTables(LifecycleTransaction transaction) { List<SSTableReader> sortedSSTables = Lists.newArrayList(transaction.originals()); Collections.sort(sortedSSTables, SSTableReader.sizeComparator); return sortedSSTables; } @Override public void execute(LifecycleTransaction txn) throws IOException { CleanupStrategy cleanupStrategy = CleanupStrategy.get(cfStore, ranges, FBUtilities.nowInSeconds()); doCleanupOne(cfStore, txn, cleanupStrategy, ranges, hasIndexes); } }, jobs, OperationType.CLEANUP); }
Source:
public void testListing() throws DDFException { List<String> buckets = manager.listBuckets(); LOG.info("========== buckets =========="); assert(buckets.contains("jing-bucket")); LOG.info("========== jing-bucket/testFolder/ =========="); List<String> keys = manager.listFiles("jing-bucket/testFolder/"); assert (keys.size() > 1); assert (keys.contains("testFolder/(-_*')!.@&:,$=+?;#.csv")); LOG.info("========== jing-bucket/testFolder/a.json =========="); keys = manager.listFiles("jing-bucket", "testFolder/a.json"); assert (keys.size()==1); keys = manager.listFiles("adatao-sample-data/test/extra/format/mixed-csv-tsv"); assert keys.size() > 1; keys = manager.listFiles("jing-bucket", "testFolder/(-_*')!.@&:,$=+?;#.csv"); assert (keys.size() == 1); keys = manager.listFiles("jing-bucket", "non-exist"); assert keys.size() == 0; }

Target:
public void testListing() throws DDFException { List<String> buckets = manager.listBuckets(); LOG.info("========== buckets =========="); assert(buckets.contains("jing-bucket")); LOG.info("========== jing-bucket/testFolder/ =========="); List<String> keys = manager.listFiles("jing-bucket/testFolder/"); assert (keys.size() > 1); assert (keys.contains("testFolder/(-_*')!.@&:,$=+?;#.csv")); LOG.info("========== jing-bucket/testFolder/a.json =========="); keys = manager.listFiles("jing-bucket", "testFolder/a.json"); assert (keys.size()==1); keys = manager.listFiles("adatao-sample-data/test/extra/format/mixed-csv-tsv"); assert keys.size() > 1; keys = manager.listFiles("jing-bucket", "testFolder/(-_*')!.@&:,$=+?;#.csv"); assert (keys.size() == 1); try { keys = manager.listFiles("jing-bucket", "non-exist"); assert (false); } catch (DDFException e) { assert (e.getMessage().equals("java.io.FileNotFoundException: File does not exist")); } }
Source:
public String toString() { return String.format("%s(%s) = %s", extractionFn, dimension, value); }

Target:
public String toString() { if (extractionFn != null) { return String.format("%s(%s) = %s", extractionFn, dimension, value); } else { return String.format("%s = %s", dimension, value); } }
Source:
public void sendNowSync(Log eventLog) { sendNowSync(eventLog); }

Target:
public void sendNowSync(Log eventLog) { sendNow(eventLog); }
Source:
public void containsTest() throws Exception { final boolean CASE_SENSITIVE = true; final boolean CASE_INSENSITIVE = false; iface.go(testPage); final WebDriverElement writingDiv = iface.getWebDriverElement(Strategy.ID, "writingDiv"); Assert.assertTrue(writingDiv.contains("Click button", CASE_SENSITIVE)); Assert.assertTrue(writingDiv.contains("cLiCk BuTtOn", CASE_INSENSITIVE)); Assert.assertTrue(writingDiv.contains("Click button", CASE_INSENSITIVE)); Assert.assertFalse(writingDiv.contains("cLiCk BuTtOn", CASE_SENSITIVE)); Assert.assertFalse(writingDiv.contains("Doesn't contain this", CASE_SENSITIVE)); Assert.assertFalse(writingDiv.contains("Doesn't contain this", CASE_SENSITIVE)); }

Target:
public void containsTest() throws Exception { final boolean CASE_SENSITIVE = true; final boolean CASE_INSENSITIVE = false; iface.go(testPage); final WebDriverElement writingDiv = $("#clickToHideDiv"); Assert.assertTrue(writingDiv.contains("Click button", CASE_SENSITIVE)); Assert.assertTrue(writingDiv.contains("cLiCk BuTtOn", CASE_INSENSITIVE)); Assert.assertTrue(writingDiv.contains("Click button", CASE_INSENSITIVE)); Assert.assertFalse(writingDiv.contains("cLiCk BuTtOn", CASE_SENSITIVE)); Assert.assertFalse(writingDiv.contains("Doesn't contain this", CASE_SENSITIVE)); Assert.assertFalse(writingDiv.contains("Doesn't contain this", CASE_INSENSITIVE)); }
Source:
private void buildFixtureMethods() { MethodInfo cleanupMethod = createMethod(Identifiers.CLEANUP_METHOD, MethodKind.CLEANUP); if (cleanupMethod != null) spec.addCleanupMethod(cleanupMethod); MethodInfo cleanupSpecMethod = createMethod(Identifiers.CLEANUP_SPEC_METHOD, MethodKind.CLEANUP_SPEC); if (cleanupSpecMethod != null) spec.addCleanupSpecMethod(cleanupSpecMethod); if (isJunit4SupportAvailable()) { for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(JUnit4LegacyUtil.BEFORE_ANNOTATION)) { spec.addSetupMethod(createJUnitFixtureMethod(method, MethodKind.SETUP, JUnit4LegacyUtil.BEFORE_ANNOTATION)); } if (method.isAnnotationPresent(JUnit4LegacyUtil.AFTER_ANNOTATION)) { spec.addCleanupMethod(createJUnitFixtureMethod(method, MethodKind.CLEANUP, JUnit4LegacyUtil.AFTER_ANNOTATION)); } if (method.isAnnotationPresent(JUnit4LegacyUtil.BEFORE_CLASS_ANNOTATION)) { spec.addSetupSpecMethod(createJUnitFixtureMethod(method, MethodKind.SETUP_SPEC, JUnit4LegacyUtil.BEFORE_CLASS_ANNOTATION)); } if (method.isAnnotationPresent(JUnit4LegacyUtil.AFTER_CLASS_ANNOTATION)) { spec.addCleanupSpecMethod(createJUnitFixtureMethod(method, MethodKind.CLEANUP_SPEC, JUnit4LegacyUtil.AFTER_CLASS_ANNOTATION)); } } } MethodInfo setupMethod = createMethod(Identifiers.SETUP_METHOD, MethodKind.SETUP); if (setupMethod != null) spec.addSetupMethod(setupMethod); MethodInfo setupSpecMethod = createMethod(Identifiers.SETUP_SPEC_METHOD, MethodKind.SETUP_SPEC); if (setupSpecMethod != null) spec.addSetupSpecMethod(setupSpecMethod); }

Target:
private void buildFixtureMethods() { MethodInfo cleanupMethod = createMethod(Identifiers.CLEANUP_METHOD, MethodKind.CLEANUP); if (cleanupMethod != null) spec.addCleanupMethod(cleanupMethod); MethodInfo cleanupSpecMethod = createMethod(Identifiers.CLEANUP_SPEC_METHOD, MethodKind.CLEANUP_SPEC); if (cleanupSpecMethod != null) spec.addCleanupSpecMethod(cleanupSpecMethod); MethodInfo setupMethod = createMethod(Identifiers.SETUP_METHOD, MethodKind.SETUP); if (setupMethod != null) spec.addSetupMethod(setupMethod); MethodInfo setupSpecMethod = createMethod(Identifiers.SETUP_SPEC_METHOD, MethodKind.SETUP_SPEC); if (setupSpecMethod != null) spec.addSetupSpecMethod(setupSpecMethod); }
Source:
public static String getImageUuid(String image, StorageService storageService) { validateImageUuid(image); DockerImage dockerImage = DockerImage.parse(image); if (dockerImage == null) { throw new ValidationErrorException(ValidationErrorCodes.INVALID_REFERENCE, InstanceConstants.FIELD_IMAGE_UUID); } String fullImageName = dockerImage.getFullName(); String registry = dockerImage.getServer(); if (!fullImageName.startsWith(registry)) { String defaultRegistry = DEFAULT_REGISTRY.get(); if (image.contains(registry)) { fullImageName = registry + "/" + fullImageName; } else if (!StringUtils.isBlank(defaultRegistry) && !StringUtils.isEmpty(defaultRegistry)) { fullImageName = defaultRegistry + "/" + fullImageName; } } if (image.startsWith(DockerImage.KIND_PREFIX)) { fullImageName = DockerImage.KIND_PREFIX + fullImageName; } if (image.startsWith("sim:") && !fullImageName.startsWith("sim:")) { fullImageName = "sim:" + fullImageName; } if (!storageService.isValidUUID(fullImageName.toString())) { throw new ValidationErrorException(ValidationErrorCodes.INVALID_REFERENCE, InstanceConstants.FIELD_IMAGE_UUID); } return fullImageName; }

Target:
public static String getImageUuid(String image, StorageService storageService) { validateImageUuid(image); DockerImage dockerImage = DockerImage.parse(image); if (dockerImage == null) { throw new ValidationErrorException(ValidationErrorCodes.INVALID_REFERENCE, InstanceConstants.FIELD_IMAGE_UUID); } String fullImageName = dockerImage.getFullName(); String registry = dockerImage.getServer(); if (!fullImageName.startsWith(registry)) { String defaultRegistry = DEFAULT_REGISTRY.get(); if (image.contains(registry)) { fullImageName = registry + "/" + fullImageName; } else if (!StringUtils.isBlank(defaultRegistry) && !StringUtils.isEmpty(defaultRegistry)) { fullImageName = defaultRegistry + "/" + fullImageName; } } if (image.startsWith(DockerImage.KIND_PREFIX)) { fullImageName = DockerImage.KIND_PREFIX + fullImageName; } if (image.startsWith(DockerImage.SIM_PREFIX) && !fullImageName.startsWith(DockerImage.SIM_PREFIX)) { fullImageName = DockerImage.SIM_PREFIX + fullImageName; } if (!storageService.isValidUUID(fullImageName.toString())) { throw new ValidationErrorException(ValidationErrorCodes.INVALID_REFERENCE, InstanceConstants.FIELD_IMAGE_UUID); } return fullImageName; }
Source:
private void initAuthInfo() { if (isBackdoor()) { authType = AuthType.ALL_ACCESS; userInfo = new UserInfo(getRequestParamValue(Const.ParamsNames.USER_ID)); userInfo.isAdmin = true; userInfo.isStudent = true; userInfo.isInstructor = true; return; } userInfo = gateKeeper.getCurrentUser(); authType = userInfo == null ? AuthType.PUBLIC : AuthType.LOGGED_IN; String userParam = getRequestParamValue(Const.ParamsNames.USER_ID); if (userInfo != null && userParam != null) { if (userInfo.isAdmin) { userInfo = gateKeeper.getMasqueradeUser(userParam); authType = AuthType.MASQUERADE; } else if (!userInfo.id.equals(userParam)) { throw new UnauthorizedAccessException("User " + userInfo.id + " is trying to masquerade as " + userParam + " without admin permission."); } } }

Target:
private void initAuthInfo() { if (Config.BACKDOOR_KEY.equals(req.getHeader("Backdoor-Key"))) { authType = AuthType.ALL_ACCESS; userInfo = new UserInfo(getRequestParamValue(Const.ParamsNames.USER_ID)); userInfo.isAdmin = true; userInfo.isStudent = true; userInfo.isInstructor = true; return; } userInfo = gateKeeper.getCurrentUser(); authType = userInfo == null ? AuthType.PUBLIC : AuthType.LOGGED_IN; String userParam = getRequestParamValue(Const.ParamsNames.USER_ID); if (userInfo != null && userParam != null) { if (userInfo.isAdmin) { userInfo = gateKeeper.getMasqueradeUser(userParam); authType = AuthType.MASQUERADE; } else if (!userInfo.id.equals(userParam)) { throw new UnauthorizedAccessException("User " + userInfo.id + " is trying to masquerade as " + userParam + " without admin permission."); } } }
Source:
private Function<SearchContext, WebElement> getSearchingFunction(By by) { return input -> { try { return input.findElement(by); } catch (NoSuchElementException e) { return null; } }; }

Target:
private Function<SearchContext, Optional<WebElement>> getSearchingFunction(By by) { return input -> { try { return Optional.of(input.findElement(by)); } catch (NoSuchElementException e) { return Optional.empty(); } }; }