auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void aRetrieveConfigurationRequestForOBISCodeIsReceivedAsPartOfABundledRequest(final int obisCodeA, final int obisCodeB, final int obisCodeC, final int obisCodeD, final int obisCodeE, final int obisCodeF) throws Throwable { this.setDeviceAndOrganisationProperties(); PROPERTIES_MAP.put("ObisCodeA", Integer.toString(obisCodeA)); PROPERTIES_MAP.put("ObisCodeB", Integer.toString(obisCodeB)); PROPERTIES_MAP.put("ObisCodeC", Integer.toString(obisCodeC)); PROPERTIES_MAP.put("ObisCodeD", Integer.toString(obisCodeD)); PROPERTIES_MAP.put("ObisCodeE", Integer.toString(obisCodeE)); PROPERTIES_MAP.put("ObisCodeF", Integer.toString(obisCodeF)); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, "501 Retrieve specific configuration object bundle", TEST_SUITE_XML); }

Target:
public void aRetrieveConfigurationRequestForOBISCodeIsReceivedAsPartOfABundledRequest(final int obisCodeA, final int obisCodeB, final int obisCodeC, final int obisCodeD, final int obisCodeE, final int obisCodeF) throws Throwable { this.setDeviceAndOrganisationProperties(); PROPERTIES_MAP.put("ObisCodeA", Integer.toString(obisCodeA)); PROPERTIES_MAP.put("ObisCodeB", Integer.toString(obisCodeB)); PROPERTIES_MAP.put("ObisCodeC", Integer.toString(obisCodeC)); PROPERTIES_MAP.put("ObisCodeD", Integer.toString(obisCodeD)); PROPERTIES_MAP.put("ObisCodeE", Integer.toString(obisCodeE)); PROPERTIES_MAP.put("ObisCodeF", Integer.toString(obisCodeF)); this.RequestRunner(PROPERTIES_MAP, TEST_CASE_NAME_REQUEST, TEST_CASE_XML_501, TEST_SUITE_XML); }
Source:
public String toString() { try { return "TypedString[" + new String(getBytes(), "UTF-8") + "]"; } catch (UnsupportedEncodingException e) { throw new AssertionError("Must be able to decode UTF-8"); } }

Target:
@Override public String toString() { try { return "TypedString[" + new String(getBytes(), "UTF-8") + "]"; } catch (UnsupportedEncodingException e) { throw new AssertionError("Must be able to decode UTF-8"); } }
Source:
protected BulkCommand readEntity(JsonNode jn) throws IOException { Function<String, String> getter = fieldName -> jn.get(fieldName).asText(); Map<String, Serializable> params = emptyMap(); if (jn.has(COMMAND_PARAMS)) { params = BulkParameters.paramsToMap(new ObjectMapper().writeValueAsString(jn.get(COMMAND_PARAMS))); } return new BulkCommand().withUsername(getter.apply(COMMAND_USERNAME)) .withRepository(getter.apply(COMMAND_REPOSITORY)) .withQuery(getter.apply(COMMAND_QUERY)) .withAction(getter.apply(COMMAND_ACTION)) .withParams(params); }

Target:
protected BulkCommand readEntity(JsonNode jn) { Function<String, String> getter = fieldName -> jn.get(fieldName).asText(); Map<String, Serializable> params = emptyMap(); if (jn.has(COMMAND_PARAMS)) { params = BulkParameters.paramsToMap(jn.get(COMMAND_PARAMS)); } return new BulkCommand().withUsername(getter.apply(COMMAND_USERNAME)) .withRepository(getter.apply(COMMAND_REPOSITORY)) .withQuery(getter.apply(COMMAND_QUERY)) .withAction(getter.apply(COMMAND_ACTION)) .withParams(params); }
Source:
public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { if (event.getSource() != getActivePartSource()) { return; } if (event.getSource().equals(navigator.getCommonViewer())) { IWorkbenchPage page = EclipseUIUtil.getActivePage(); IEditorPart activeEditor = page.getActiveEditor(); if (activeEditor instanceof DialectEditor) { DialectEditor dialectEditor = (DialectEditor) activeEditor; page.bringToTop(dialectEditor); selectRepresentationElements(selection, dialectEditor); } } else { Set<EObject> targets = getTargetsFromSelection((IStructuredSelection) selection); if (!targets.isEmpty()) { Set<Object> currentSelection = getCurrentNavigatorSelection(); if (!targets.equals(currentSelection)) { navigator.selectReveal(new StructuredSelection(targets.toArray())); } } } } }

Target:
public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { if (event.getSource() != getActivePartSource()) { return; } if (event.getSource().equals(navigator.getCommonViewer())) { IWorkbenchPage page = EclipseUIUtil.getActivePage(); IEditorPart activeEditor = page.getActiveEditor(); if (activeEditor instanceof DialectEditor) { DialectEditor dialectEditor = (DialectEditor) activeEditor; page.bringToTop(dialectEditor); selectRepresentationElements(selection, dialectEditor); } } else { Set<EObject> targets = getTargetsFromSelection((IStructuredSelection) selection); if (!targets.isEmpty()) { navigator.selectReveal(new StructuredSelection(targets.toArray())); } } } }
Source:
private void updateStatusAndpeerProbeOtherIface(Network glusterNetwork, VDS host, GlusterServerInfo fetchedServerInfo) { if (glusterNetwork == null || host.getStatus() != VDSStatus.Up) { return; } GlusterServer glusterServer = getGlusterServerDao().get(host.getId()); if (glusterServer == null) { return; } if (glusterServer.getPeerStatus() == PeerStatus.DISCONNECTED && fetchedServerInfo.getStatus() == PeerStatus.CONNECTED) { getGlusterServerDao().updatePeerStatus(host.getId(), PeerStatus.DISCONNECTED); } List<VdsNetworkInterface> interfaces = getInterfaceDao().getAllInterfacesForVds(host.getId()); for (VdsNetworkInterface iface : interfaces) { if (glusterNetwork.getName().equals(iface.getNetworkName()) && StringUtils.isNotBlank(iface.getIpv4Address()) && !glusterServer.getKnownAddresses().contains(iface.getIpv4Address())) { VDS upServer = getAlternateUpServerInCluster(host.getClusterId(), host.getId()); if (upServer != null) { boolean peerProbed = glusterPeerProbeAdditionalInterface(upServer.getId(), iface.getIpv4Address()); if (peerProbed) { getGlusterServerDao().addKnownAddress(host.getId(), iface.getIpv4Address()); } } else { log.warn("probe could not be done for server '{}' as no alternate UP server found", host.getHostName()); } } } }

Target:
private void updateStatusAndpeerProbeOtherIface(Network glusterNetwork, VDS host, GlusterServerInfo fetchedServerInfo) { if (glusterNetwork == null || host.getStatus() != VDSStatus.Up) { return; } GlusterServer glusterServer = getGlusterServerDao().get(host.getId()); if (glusterServer == null) { return; } if (glusterServer.getPeerStatus() == PeerStatus.DISCONNECTED && fetchedServerInfo.getStatus() == PeerStatus.CONNECTED) { getGlusterServerDao().updatePeerStatus(host.getId(), PeerStatus.CONNECTED); } List<VdsNetworkInterface> interfaces = getInterfaceDao().getAllInterfacesForVds(host.getId()); for (VdsNetworkInterface iface : interfaces) { if (glusterNetwork.getName().equals(iface.getNetworkName()) && StringUtils.isNotBlank(iface.getIpv4Address()) && !glusterServer.getKnownAddresses().contains(iface.getIpv4Address())) { VDS upServer = getAlternateUpServerInCluster(host.getClusterId(), host.getId()); if (upServer != null) { boolean peerProbed = glusterPeerProbeAdditionalInterface(upServer.getId(), iface.getIpv4Address()); if (peerProbed) { getGlusterServerDao().addKnownAddress(host.getId(), iface.getIpv4Address()); } } else { log.warn("probe could not be done for server '{}' as no alternate UP server found", host.getHostName()); } } } }
Source:
public boolean sendLogs(String payload) { if(logCollectionPort == null){ logger.severe("Datadog Log Collection Port is not set properly"); throw new RuntimeException("Datadog Log Collection Port not set properly"); } if(this.ddLogger == null) { boolean status = reinitializeLogger(true); if(!status) { return false; } } try { this.ddLogger.info(payload); if(this.ddLogger.getHandlers().length == 0){ this.ddLogger = null; return false; } Handler handler = this.ddLogger.getHandlers()[0]; DatadogErrorManager errorManager = (DatadogErrorManager)handler.getErrorManager(); if(errorManager.hadReportedIssue()){ reinitializeLogger(true); this.ddLogger.info(previousPayload); previousPayload = payload; return false; } previousPayload = payload; }catch(Exception e){ DatadogUtilities.severe(logger, e, null); reinitialize(true); previousPayload = payload; return false; } return true; }

Target:
public boolean sendLogs(String payload) { if(logCollectionPort == null){ logger.severe("Datadog Log Collection Port is not set properly"); return false; } if(this.ddLogger == null) { boolean status = reinitializeLogger(true); if(!status) { return false; } } if(this.ddLogger.getHandlers().length == 0){ this.ddLogger = null; return false; } try { this.ddLogger.info(payload); Handler handler = this.ddLogger.getHandlers()[0]; DatadogErrorManager errorManager = (DatadogErrorManager)handler.getErrorManager(); if(errorManager.hadReportedIssue()){ reinitializeLogger(true); this.ddLogger.info(previousPayload); previousPayload = payload; return false; } previousPayload = payload; }catch(Exception e){ DatadogUtilities.severe(logger, e, null); reinitialize(true); previousPayload = payload; return false; } return true; }
Source:
public Hosts list() { ApplicationMode appMode = getCurrent().get(ApplicationMode.class); if (isFiltered()) { if (appMode == ApplicationMode.GlusterOnly) { return mapGlusterOnlyCollection(getBackendCollection(VdcQueryType.GetAllHosts, new VdcQueryParametersBase())); } else { return mapCollection(getBackendCollection(VdcQueryType.GetAllHosts, new VdcQueryParametersBase())); } } else { if (appMode == ApplicationMode.GlusterOnly) { return mapGlusterOnlyCollection(getBackendCollection(SearchType.VDS)); } else { return mapCollection(getBackendCollection(SearchType.VDS)); } } }

Target:
public Hosts list() { ApplicationMode appMode = getCurrent().get(ApplicationMode.class); if (appMode == ApplicationMode.GlusterOnly) { return listGlusterOnly(); } else { return listAll(); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Avatar avatar = (Avatar) o; return url.equals(avatar.url) && timestamp.equals(avatar.timestamp); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Avatar avatar = (Avatar) o; return url.equals(avatar.url) && timestamp.isEqual(avatar.timestamp); }
Source:
public ASTNode transform(Collection collection) { throw new UnsupportedOperationException(); }

Target:
public ASTNode transform(Collection collection) { throw new UnsupportedOperationException("This method should never be called"); }
Source:
private HashSet<String> getAllJarModuleNames(IJavaProject javaProject2) { HashSet<String> autoModules = new HashSet<>(); try { for (IPackageFragmentRoot root : javaProject2.getAllPackageFragmentRoots()) { if (root instanceof JarPackageFragmentRoot) { IModuleDescription desc = ((JarPackageFragmentRoot) root).getAutomaticModuleDescription(); String name = desc != null ? desc.getElementName() : null; if (name != null && name.length() > 0) autoModules.add(name); } } } catch (JavaModelException e) { e.printStackTrace(); } return autoModules; }

Target:
private HashSet<String> getAllJarModuleNames(IJavaProject javaProject2) { HashSet<String> modules = new HashSet<>(); try { for (IPackageFragmentRoot root : javaProject2.getAllPackageFragmentRoots()) { if (root instanceof JarPackageFragmentRoot) { IModuleDescription desc = root.getModuleDescription(); desc = desc == null ? ((JarPackageFragmentRoot) root).getAutomaticModuleDescription() : desc; String name = desc != null ? desc.getElementName() : null; if (name != null && name.length() > 0) modules.add(name); } } } catch (JavaModelException e) { } return modules; }
Source:
public void setUp() throws Exception { now = System.currentTimeMillis(); response = new HttpToolResponse(responseCode, ImmutableMap.of(headerName, ImmutableList.of("myvalue")), body.getBytes(), now-fullLatency, fullLatency/2, fullLatency); }

Target:
public void setUp() throws Exception { now = System.currentTimeMillis(); response = new HttpToolResponse(responseCode, ImmutableMap.of(headerName, ImmutableList.of(headerVal)), body.getBytes(), now-fullLatency, fullLatency / 2, fullLatency); }
Source:
protected SearchResult getFallback() { LOGGER.error("Error during the execution of the command. Falling back to the cache"); return new FallbackViaLDAPServerProblemCommand(cacheKey, getFailedExecutionException()).execute(); }

Target:
protected SearchResult getFallback() { LOGGER.warn("Error during the execution of the command. Falling back to the cache"); return new FallbackViaLDAPServerProblemCommand(cacheKey, getFailedExecutionException()).execute(); }
Source:
protected void execute() { Multimap<String, ItemDefinition> items = HashMultimap.create(); for (NetworkUpsToolsBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String name = provider.getUps(itemName); Class<? extends Item> itemType = provider.getItemType(itemName); String property = provider.getProperty(itemName); items.put(name, new ItemDefinition(itemName, itemType, property)); } } for(String name : items.keySet()) { NutConfig nut = upses.get(name); if (nut == null) { logger.error("No configuration for UPS with name: '{}'", name); } Client client = null; try { client = new Client(nut.host, nut.port, nut.login, nut.pass); Device device = client.getDevice(nut.device); for(ItemDefinition definition : items.get(name)) { Variable variable = device.getVariable(definition.property); String value = variable.getValue(); Class<? extends Item> itemType = definition.itemType; String itemName = definition.itemName; State state = null; if (itemType.isAssignableFrom(StringItem.class)) { state = StringType.valueOf(value); } else if (itemType.isAssignableFrom(NumberItem.class)) { state = DecimalType.valueOf(value); } else if (itemType.isAssignableFrom(SwitchItem.class)) { state = OnOffType.valueOf(value); } if (state != null) { eventPublisher.postUpdate(itemName, state); } else { logger.error( "'{}' couldn't be parsed to a State. Valid State-Types are String, Number and Switch", variable.toString()); } } } catch(Exception ex) { logger.error("Nut processing error", ex); } finally { if (client != null) { client.disconnect(); } } } }

Target:
protected void execute() { Multimap<String, ItemDefinition> items = HashMultimap.create(); for (NetworkUpsToolsBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { String name = provider.getUps(itemName); Class<? extends Item> itemType = provider.getItemType(itemName); String property = provider.getProperty(itemName); items.put(name, new ItemDefinition(itemName, itemType, property)); } } for(String name : items.keySet()) { NutConfig nut = upses.get(name); if (nut == null) { logger.error("No configuration for UPS with name: '{}'", name); continue; } Client client = null; try { client = new Client(nut.host, nut.port, nut.login, nut.pass); Device device = client.getDevice(nut.device); for(ItemDefinition definition : items.get(name)) { Variable variable = device.getVariable(definition.property); String value = variable.getValue(); Class<? extends Item> itemType = definition.itemType; String itemName = definition.itemName; State state = null; if (itemType.isAssignableFrom(StringItem.class)) { state = StringType.valueOf(value); } else if (itemType.isAssignableFrom(NumberItem.class)) { state = DecimalType.valueOf(value); } else if (itemType.isAssignableFrom(SwitchItem.class)) { state = OnOffType.valueOf(value); } if (state != null) { eventPublisher.postUpdate(itemName, state); } else { logger.error( "'{}' couldn't be parsed to a State. Valid State-Types are String, Number and Switch", variable.toString()); } } } catch(Exception ex) { logger.error("Nut processing error", ex); } finally { if (client != null) { client.disconnect(); } } } }
Source:
private void handleClickWebpackLiveReload(ClickEvent event) { addPageReloadingSpan(); String css = "\nconsole.log('Hello world');"; writeToFrontendJSFile(VaadinService.getCurrent(), css); }

Target:
private void handleClickWebpackLiveReload(ClickEvent event) { addPageReloadingSpan(); String js = String.format("%nconsole.log('Hello world');"); writeToFrontendJSFile(VaadinService.getCurrent(), js); }
Source:
private void parseConfiguration(String config) throws IllegalArgumentException { String[] mappings = config.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); if (params.length < 2) { throw new IllegalArgumentException("Configuration " + mapping + " is in-correctly formed. " + "Format should be <fieldname>:<decompressor-type>"); } String field = params[0]; String type = params[1].toUpperCase(); DecompressorType cType = DecompressorType.NONE; switch(type) { case "SNAPPY": cType = DecompressorType.SNAPPY; break; case "GZIP": cType = DecompressorType.GZIP; break; case "ZIP": cType = DecompressorType.ZIP; break; case "NONE": cType = DecompressorType.NONE; break; default: throw new IllegalArgumentException("Unknown decompressor type " + type + " found in mapping " + mapping); } if (deCompMap.containsKey(field)) { throw new IllegalArgumentException("Field " + field + " already has decompressor set. Check the mapping."); } else { deCompMap.put(field, cType); } } }

Target:
private void parseConfiguration(String config) throws IllegalArgumentException { String[] mappings = config.split(","); for (String mapping : mappings) { String[] params = mapping.split(":"); if (params.length < 2) { throw new IllegalArgumentException("Configuration " + mapping + " is in-correctly formed. " + "Format should be <fieldname>:<decompressor-type>"); } String field = params[0]; String type = params[1].toUpperCase(); DecompressorType cType = DecompressorType.valueOf(type); if (deCompMap.containsKey(field)) { throw new IllegalArgumentException("Field " + field + " already has decompressor set. Check the mapping."); } else { deCompMap.put(field, cType); } } }
Source:
private String getDirFromTopic(String dir, String topic, int maxIndexParts) { dir = dir.replace("${topic}", topic); if (topixRegexCaptureGroup != null) { Matcher matcher = topixRegexCaptureGroup.matcher(topic); if (!matcher.matches()) { throw new ConfigException( String.format( "Topic %s does not fully match the specified regex %s in %s", topic, topixRegexCaptureGroup.pattern(), TOPIC_REGEX_CAPTURE_GROUP_CONFIG ) ); } if (maxIndexParts > 0 && maxIndexParts > matcher.groupCount()) { throw new ConfigException( String.format( "Topic %s must have at least %d capture groups using regex pattern %s, " + "but actually had %d capture groups.", topic, maxIndexParts, topixRegexCaptureGroup.pattern(), matcher.groupCount() ) ); } for (int index = 1; index < matcher.groupCount() + 1; index++) { dir = dir.replace("${" + index + "}", matcher.group(index)); } } return dir; }

Target:
private String getDirFromTopic(String dir, String topic, int maxIndexParts) { dir = dir.replace("${topic}", topic); if (topicRegexCaptureGroup != null) { Matcher matcher = topicRegexCaptureGroup.matcher(topic); if (!matcher.matches()) { throw new ConfigException( TOPIC_CAPTURE_GROUPS_REGEX_CONFIG, topicRegexCaptureGroup.pattern(), String.format("Topic %s does not fully match the specified regex.", topic) ); } if (maxIndexParts > matcher.groupCount()) { throw new ConfigException( String.format( "Topic %s must have at least %d capture groups using regex pattern %s, " + "but actually had %d capture groups.", topic, maxIndexParts, topicRegexCaptureGroup.pattern(), matcher.groupCount() ) ); } for (int index = 0; index < matcher.groupCount() + 1; index++) { dir = dir.replace("${" + index + "}", matcher.group(index)); } } return dir; }
Source:
public void patchRequireCertificateMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .build(); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/certificate", null); ops.add(replaceOperation); String patchBody = getPatchContent(ops); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); }

Target:
public void patchRequireCertificateMissingValue() throws Exception { context.turnOffAuthorisationSystem(); EPerson ePerson = EPersonBuilder.createEPerson(context) .withNameInMetadata("John", "Doe") .withEmail("Johndoe@fake-email.com") .build(); String token = getAuthToken(admin.getEmail(), password); List<Operation> ops = new ArrayList<Operation>(); ReplaceOperation replaceOperation = new ReplaceOperation("/certificate", true); ops.add(replaceOperation); String patchBody = getPatchContent(ops); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.requireCertificate", Matchers.is(true)));; List<Operation> ops2 = new ArrayList<Operation>(); ReplaceOperation replaceOperation2 = new ReplaceOperation("/certificate",null); ops2.add(replaceOperation2); patchBody = getPatchContent(ops2); getClient(token).perform(patch("/api/eperson/epersons/" + ePerson.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isBadRequest()); getClient(token).perform(get("/api/eperson/epersons/" + ePerson.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.requireCertificate", Matchers.is(true))) .andExpect(jsonPath("$.email", Matchers.is("johndoe@fake-email.com"))) .andExpect(jsonPath("$.canLogIn", Matchers.is(false))); }
Source:
public void updateTimeRangeSelectionPieChart() { if (getTimeRangePC() == null) { fTimeRangePC = new PieChart(this, SWT.NONE); getTimeRangePC().getTitle().setText(fTimeRangePCname); getTimeRangePC().getAxisSet().getXAxis(0).getTitle().setText(""); getTimeRangePC().getLegend().setPosition(SWT.BOTTOM); getTimeRangePC().getLegend().setVisible(true); getTimeRangePC().addListener(SWT.MouseMove, fMouseListener); } else if (getTimeRangePC().isDisposed()) { return; } updatePieChartWithData(fTimeRangePC, fTimeRangeSelectionEventTypes, MIN_PRECENTAGE_TO_SHOW_SLICE, fOthersSliceName); }

Target:
void updateTimeRangeSelectionPieChart() { if (getTimeRangePC() == null) { fTimeRangePC = new PieChart(this, SWT.NONE); getTimeRangePC().getTitle().setText(fTimeRangePCname); getTimeRangePC().getAxisSet().getXAxis(0).getTitle().setText(""); getTimeRangePC().getLegend().setPosition(SWT.BOTTOM); getTimeRangePC().getLegend().setVisible(true); getTimeRangePC().addListener(SWT.MouseMove, fMouseListener); } else if (getTimeRangePC().isDisposed()) { return; } Map<String, Long> totalEventCountForChart = getTotalEventCountForChart(false); if(totalEventCountForChart == null){ return; } updatePieChartWithData(fTimeRangePC, totalEventCountForChart, MIN_PRECENTAGE_TO_SHOW_SLICE, fOthersSliceName); }
Source:
LedgerEntryRequest(ArrayList<BookieSocketAddress> ensemble, long lId, long eId) { this.entryImpl = LedgerEntryImpl.create(lId, eId); this.ensemble = ensemble; if (lh.bk.isReorderReadSequence()) { DistributionSchedule.WriteSet unorderedWriteSet = lh.getDistributionSchedule().getWriteSet(entryId); BookKeeperServerHealthInfo bookKeeperServerHealthInfo = generateHealthInfoForWriteSet( unorderedWriteSet, ensemble, lh ); writeSet = lh.bk.getPlacementPolicy() .reorderReadSequence( ensemble, bookKeeperServerHealthInfo, lh.distributionSchedule.getWriteSet(eid)); } else { writeSet = lh.distributionSchedule.getWriteSet(eId); } }

Target:
LedgerEntryRequest(ArrayList<BookieSocketAddress> ensemble, long lId, long eId) { this.entryImpl = LedgerEntryImpl.create(lId, eId); this.ensemble = ensemble; this.eId = eId; if (lh.bk.isReorderReadSequence()) { writeSet = lh.bk.getPlacementPolicy() .reorderReadSequence( ensemble, lh.getBookiesHealthInfo(), lh.distributionSchedule.getWriteSet(eId)); } else { writeSet = lh.distributionSchedule.getWriteSet(eId); } }
Source:
public GeoEntry queryById(String id) throws GeoEntryQueryException { SolrQuery solrQuery = new SolrQuery(String.format("id_txt:\"%s\"", ClientUtils.escapeQueryChars(id))); solrQuery.setRows(1); QueryResponse response = null; try { response = client.query(solrQuery, METHOD.POST); } catch (SolrServerException | IOException e) { throw new GeoEntryQueryException("Error while querying", e); } return response .getResults() .stream() .map(this::transformMetacardToGeoEntry) .findFirst() .orElseThrow(() -> new GeoEntryQueryException("Could not find id")); }

Target:
public GeoEntry queryById(String id) throws GeoEntryQueryException { SolrQuery solrQuery = new SolrQuery(String.format("%s:\"%s\"", ID, ClientUtils.escapeQueryChars(id))); solrQuery.setRows(1); QueryResponse response = null; try { response = client.query(solrQuery, METHOD.POST); } catch (SolrServerException | IOException e) { throw new GeoEntryQueryException("Error while querying by ID", e); } return response .getResults() .stream() .map(this::transformMetacardToGeoEntry) .findFirst() .orElseThrow(() -> new GeoEntryQueryException("Could not find id")); }
Source:
protected void setTupleToStringConverter(Converter<Tuple, String> tupleToStringConverter) { this.tupleToStringConverter = tupleToStringConverter; }

Target:
protected void setTupleToStringConverter(Converter<Tuple, String> tupleToStringConverter) { Assert.notNull(tupleToStringConverter,"tupleToStringConverter cannot be null"); this.tupleToStringConverter = tupleToStringConverter; }
Source:
public URI getFeatureURI(String id, String version) { SiteFeature[] entries = site.getFeatures(); for (SiteFeature entrie : entries) { if (id.equals(entrie.getFeatureIdentifier()) && version.equals(entrie.getFeatureVersion())) { return getSiteFeatureURI(entrie); } } URI base = getBaseURI(); URI url = getArchiveURI(base, FEATURE_DIR + id + VERSION_SEPARATOR + version + JAR_EXTENSION); if (url != null) return url; return URIUtil.append(base, FEATURE_DIR + id + VERSION_SEPARATOR + version + JAR_EXTENSION); }

Target:
public URI getFeatureURI(String id, String version) { SiteFeature[] entries = site.getFeatures(); for (SiteFeature entry : entries) { if (id.equals(entry.getFeatureIdentifier()) && version.equals(entry.getFeatureVersion())) { return getSiteFeatureURI(entry); } } URI base = getBaseURI(); URI url = getArchiveURI(base, FEATURE_DIR + id + VERSION_SEPARATOR + version + JAR_EXTENSION); if (url != null) return url; return URIUtil.append(base, FEATURE_DIR + id + VERSION_SEPARATOR + version + JAR_EXTENSION); }
Source:
public Relationship byTypeValue(final String typeValue){ if(typeValue==null) { return null; } Relationship rel = null; List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); try { final DotConnect dc = new DotConnect(); dc.setSQL(sql.FIND_BY_TYPE_VALUE); dc.addParam(typeValue.toLowerCase()); results = dc.loadObjectResults(); if (results.size() == 0) { return rel; } rel = new DbRelationshipTransformer(results).from(); if(rel!= null && InodeUtils.isSet(rel.getInode())){ cache.putRelationshipByInode(rel); } } catch (DotDataException e) { Logger.error(this,"Error getting relationships with typeValue: " + typeValue.toLowerCase(),e); } return rel; }

Target:
public Relationship byTypeValue(final String typeValue){ if(typeValue==null) { return null; } Relationship relationship = null; List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); try { final DotConnect dc = new DotConnect(); dc.setSQL(sql.FIND_BY_TYPE_VALUE); dc.addParam(typeValue.toLowerCase()); results = dc.loadObjectResults(); if (results.size() == 0) { return relationship; } relationship = new DbRelationshipTransformer(results).from(); if(relationship!= null && InodeUtils.isSet(relationship.getInode())){ cache.putRelationshipByInode(relationship); } } catch (DotDataException e) { Logger.error(this,"Error getting relationships with typeValue: " + typeValue.toLowerCase(),e); } return relationship; }
Source:
void close() throws StoreException { long startTimeInMs = time.milliseconds(); try { persistor.write(); if (persistorTask != null) { persistorTask.cancel(false); } if (hardDeleter != null) { try { hardDeleter.shutdown(); } catch (Exception e) { logger.error("Index : " + dataDir + " error while persisting cleanup token ", e); } } try { cleanShutdownFile.createNewFile(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while creating clean shutdown file ", e); } } finally { metrics.indexShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } }

Target:
void close() throws StoreException { long startTimeInMs = time.milliseconds(); try { if (persistorTask != null) { persistorTask.cancel(false); } persistor.write(); if (hardDeleter != null) { try { hardDeleter.shutdown(); } catch (Exception e) { logger.error("Index : " + dataDir + " error while persisting cleanup token ", e); } } try { cleanShutdownFile.createNewFile(); } catch (IOException e) { logger.error("Index : " + dataDir + " error while creating clean shutdown file ", e); } } finally { metrics.indexShutdownTimeInMs.update(time.milliseconds() - startTimeInMs); } }
Source:
private void readWitness() { witnesses = new ArrayList<TransactionWitness>(inputs.size()); for(int i = 0 ; i < inputs.size(); i++) { long pushCount = readVarInt(); TransactionWitness witness = new TransactionWitness((int)pushCount); witnesses.add(witness); optimalEncodingMessageSize += VarInt.sizeOf(pushCount); for(int y = 0; y < pushCount; y++) { long pushSize = readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(pushSize) + pushSize; byte[] push = readBytes((int)pushSize); witness.setPush(y, push); } } }

Target:
private void readWitness() { witnesses = new ArrayList<TransactionWitness>(inputs.size()); for (int i = 0; i < inputs.size(); i++) { long pushCount = readVarInt(); TransactionWitness witness = new TransactionWitness((int) pushCount); setWitness(i, witness); optimalEncodingMessageSize += VarInt.sizeOf(pushCount); for (int y = 0; y < pushCount; y++) { long pushSize = readVarInt(); optimalEncodingMessageSize += VarInt.sizeOf(pushSize) + pushSize; byte[] push = readBytes((int) pushSize); witness.setPush(y, push); } } }
Source:
private int readAllNulls(int[] positions, int positionCount) throws IOException { presentStream.skip(positions[positionCount - 1]); if (nonDeterministicFilter) { outputPositionCount = 0; for (int i = 0; i < positionCount; i++) { if (filter.testNull()) { outputPositionCount++; } } } else if (nullsAllowed) { outputPositionCount = positionCount; allNulls = true; } else { outputPositionCount = 0; } return positions[positionCount - 1] + 1; }

Target:
private int readAllNulls(int[] positions, int positionCount) throws IOException { presentStream.skip(positions[positionCount - 1]); if (nonDeterministicFilter) { outputPositionCount = 0; for (int i = 0; i < positionCount; i++) { if (filter.testNull()) { outputPositionCount++; } else { outputPositionCount -= filter.getPrecedingPositionsToFail(); i += filter.getSucceedingPositionsToFail(); } } } else if (nullsAllowed) { outputPositionCount = positionCount; } else { outputPositionCount = 0; } allNulls = true; return positions[positionCount - 1] + 1; }
Source:
boolean isListForRepeatedAnnotation(AnnotationMirror a) { if (!isListForRepeatedAnnotationCache.containsKey(a)) { isListForRepeatedAnnotationCache.put(a, isListForRepeatedAnnotationImplementation(a)); } return isListForRepeatedAnnotationCache.get(a); }

Target:
private boolean isListForRepeatedAnnotation(AnnotationMirror a) { DeclaredType annotationType = a.getAnnotationType(); Boolean resultObject = isListForRepeatedAnnotationCache.get(annotationType); if (resultObject != null) { return resultObject; } boolean result = isListForRepeatedAnnotationImplementation(annotationType); isListForRepeatedAnnotationCache.put(annotationType, result); return result; }
Source:
private Processor getProcessor(Workspace workspace) { Properties beanProperties = new BeanProperties(); beanProperties.put("project", project); beanProperties.put("settings", session.getSettings()); Properties mavenProperties = new Properties(beanProperties); mavenProperties.putAll(project.getProperties()); return processor = new Processor(workspace, mavenProperties, false); }

Target:
private Processor getProcessor(Workspace workspace) { Properties beanProperties = new BeanProperties(); beanProperties.put("project", project); beanProperties.put("settings", session.getSettings()); Properties mavenProperties = new Properties(beanProperties); mavenProperties.putAll(project.getProperties()); return new Processor(workspace, mavenProperties, false); }
Source:
private SingleResultCallback<List<RawBsonDocument>> convertResultsCallback(final SingleResultCallback<List<T>> callback) { return errorHandlingCallback(new SingleResultCallback<List<RawBsonDocument>>() { @Override public void onResult(final List<RawBsonDocument> rawDocuments, final Throwable t) { if (t != null) { callback.onResult(null, t); } else if (rawDocuments != null) { List<T> results = new ArrayList<T>(); for (RawBsonDocument rawDocument : rawDocuments) { if (!rawDocument.containsKey("_id")) { callback.onResult( null, new MongoChangeStreamException( "Cannot provide resume functionality when the resume token is missing." ) ); return; } results.add(rawDocument.decode(changeStreamOperation.getDecoder())); } try { resumeToken = rawDocuments.get(rawDocuments.size() - 1).getDocument("_id"); callback.onResult(results, null); } catch (Exception e) { callback.onResult(null, e); } } else { callback.onResult(null, null); } } }, LOGGER); }

Target:
private SingleResultCallback<List<RawBsonDocument>> convertResultsCallback(final SingleResultCallback<List<T>> callback) { return errorHandlingCallback(new SingleResultCallback<List<RawBsonDocument>>() { @Override public void onResult(final List<RawBsonDocument> rawDocuments, final Throwable t) { if (t != null) { callback.onResult(null, t); } else if (rawDocuments != null) { List<T> results = new ArrayList<T>(); try { for (RawBsonDocument rawDocument : rawDocuments) { if (!rawDocument.containsKey("_id")) { callback.onResult( null, new MongoChangeStreamException( "Cannot provide resume functionality when the resume token is missing." ) ); return; } results.add(rawDocument.decode(changeStreamOperation.getDecoder())); } resumeToken = rawDocuments.get(rawDocuments.size() - 1).getDocument("_id"); callback.onResult(results, null); } catch (Exception e) { callback.onResult(null, e); } } else { callback.onResult(null, null); } } }, LOGGER); }
Source:
public boolean isHighPriority() { if (getFirstHeader(highPriorityTag)!=null && getFirstHeader(highPriorityTag).equals(xPriorityContent)) { return true; } return false; }

Target:
public boolean isHighPriority() { return X_PRIORITY_CONTENT.equals(getFirstHeader(MimeHeader.HEADER_HIGH_PRIORITY)); }
Source:
public int getCount() { return known ? count : Integer.MAX_VALUE; }

Target:
public int getCount() { if (known) { return count; } else { throw new IllegalStateException( "Can't get superstep count when it's unknown"); } }
Source:
private void refreshGeoRepDataInCluster(VDSGroup cluster) { if (!supportsGlusterGeoRepFeature(cluster)) { return; } List<GlusterGeoRepSession> sessions = getSessionsForCluster(cluster); for (GlusterGeoRepSession session: sessions) { session.setMasterVolumeId(getVolumeId(cluster, session.getMasterVolumeName())); updateGeoRepStatus(session); if (getGeoRepDao().getById(session.getId()) == null) { getGeoRepDao().save(session); } else { getGeoRepDao().updateSession(session); } getGeoRepDao().saveOrUpdateDetailsInBatch(session.getSessionDetails()); } }

Target:
private void refreshGeoRepDataInCluster(VDSGroup cluster) { if (!supportsGlusterGeoRepFeature(cluster)) { return; } List<GlusterGeoRepSession> sessions = getSessionsForCluster(cluster); if (sessions == null) { log.debugFormat("No sessions returned for cluster {0} from CLI, nothing to do", cluster.getName()); return; } for (GlusterGeoRepSession session: sessions) { session.setMasterVolumeId(getVolumeId(cluster, session.getMasterVolumeName())); updateGeoRepStatus(session); if (getGeoRepDao().getById(session.getId()) == null) { getGeoRepDao().save(session); } else { getGeoRepDao().updateSession(session); } getGeoRepDao().saveOrUpdateDetailsInBatch(session.getSessionDetails()); } }
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_RESOURCE_ATTR_DEF); attr.setFriendlyName("projectsBasePath"); attr.setDisplayName("projectsBasePath"); attr.setType(String.class.getName()); attr.setDescription("Path to base directory of projects."); return attr; }

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_RESOURCE_ATTR_DEF); attr.setFriendlyName("projectsBasePath"); attr.setDisplayName("Projects base path"); attr.setType(String.class.getName()); attr.setDescription("Path to base directory of projects."); return attr; }
Source:
private Duration(long amount, TimeUnit timeUnit, boolean forever) { if (!forever) { if (amount <= 0) { throw new IllegalArgumentException("amount must be greater than zero: " + amount); } if (timeUnit == null) { throw new NullPointerException("TimeUnit must not be null"); } switch (timeUnit) { case MICROSECONDS: case NANOSECONDS: { throw new IllegalArgumentException("TimeUnit must be equal or lower granularity than " + TimeUnit.MILLISECONDS.name() + ". Specified value was " + timeUnit.name()); } default: { break; } } } this.amount = amount; this.timeUnit = timeUnit; }

Target:
private Duration(long amount, TimeUnit timeUnit, boolean forever) { if (!forever) { if (amount < 0) { throw new IllegalArgumentException("amount must be greater than or equal to zero: " + amount); } if (timeUnit == null) { throw new NullPointerException("TimeUnit must not be null"); } } this.amount = amount; this.timeUnit = timeUnit; }
Source:
private void showContent() { contentRootLayoutHiding.setVisibility(View.VISIBLE); showDescriptionOnLoad = PreferenceManager.getDefaultSharedPreferences(activity) .getBoolean(getString(R.string.always_expand_description_key), false); if (showDescriptionOnLoad) { toggleTitleAndDescription(); } }

Target:
private void showContent() { contentRootLayoutHiding.setVisibility(View.VISIBLE); final boolean showDescriptionOnLoad = PreferenceManager.getDefaultSharedPreferences(activity) .getBoolean(getString(R.string.always_expand_description_key), false); if (showDescriptionOnLoad) { toggleTitleAndDescription(); } }
Source:
public Position getPosition(IDocument document) { JsonLocation location = getStart() != null ? getStart() : getLocation(); if (location != null) { int startLine = location.getLineNr() - 1; int offset = 0; try { offset = document.getLineOffset(startLine) + location.getColumnNr() + Strings.nullToEmpty(getProperty()).length(); } catch (BadLocationException e) { return new Position(0); } return new Position(Math.max(0, offset), 0); } return new Position(0); }

Target:
public Position getPosition(IDocument document) { JsonLocation location = getStart() != null ? getStart() : getLocation(); if (location != null) { int startLine = location.getLineNr() - 1; int offset = 0; int length = 0; try { offset = document.getLineOffset(startLine); length = document.getLineOffset(startLine + 1) - offset; } catch (BadLocationException e) { return new Position(0); } return new Position(Math.max(0, offset), length); } return new Position(0); }
Source:
public static <K extends Comparable<? super K>, V> TreeMap<K, V> of(K key, V value) { return of((Comparator<? super K> & Serializable) K::compareTo, Tuple.of(key, value)); }

Target:
public static <K extends Comparable<? super K>, V> TreeMap<K, V> of(K key, V value) { return of((Comparator<? super K> & Serializable) K::compareTo, key, value); }
Source:
void disconnect() { if (subscriberStreamObserver != null) { subscriberStreamObserver.onCompleted(); } commandExecutor.shutdown(); try { if (!commandExecutor.awaitTermination(5, TimeUnit.SECONDS)) { logger.warn("Awaited Command Bus termination for 5 seconds. Wait period extended by 30 seconds."); } if (!commandExecutor.awaitTermination(20, TimeUnit.SECONDS)) { logger.warn("Awaited Command Bus termination for 35 seconds. Will shutdown forcefully."); commandExecutor.shutdownNow(); } } catch (InterruptedException e) { logger.warn("Awaiting termination of Command Bus got interrupted. Will shutdown immediately", e); commandExecutor.shutdownNow(); Thread.currentThread().interrupt(); } running = false; }

Target:
void disconnect() { if (subscriberStreamObserver != null) { subscriberStreamObserver.onCompleted(); } commandExecutor.shutdown(); try { if (!commandExecutor.awaitTermination(5, TimeUnit.SECONDS)) { logger.warn("Awaited Command Bus termination for 5 seconds. Wait period extended by 30 seconds."); } if (!commandExecutor.awaitTermination(30, TimeUnit.SECONDS)) { logger.warn("Awaited Command Bus termination for 35 seconds. Will shutdown forcefully."); commandExecutor.shutdownNow(); } } catch (InterruptedException e) { logger.warn("Awaiting termination of Command Bus got interrupted. Will shutdown immediately", e); commandExecutor.shutdownNow(); Thread.currentThread().interrupt(); } running = false; }
Source:
public static Timeline createTimeline( final String eventType, final int order, final Storage storage, final String topic, final Date createdAt) { final Timeline timeline = new Timeline(eventType, order, storage, topic, createdAt); timeline.setId(UUID.randomUUID()); return timeline; }

Target:
public static Timeline createTimeline( final String eventType, final int order, final Storage storage, final String topic, final Date createdAt) { final Timeline timeline = new Timeline(eventType, order, storage, topic, createdAt); timeline.setId(new UUIDGenerator().randomUUID()); return timeline; }
Source:
private String getRelatedContentESQuery(Contentlet contentlet, Relationship rel) { boolean isSameStructRelationship = FactoryLocator.getRelationshipFactory().sameParentAndChild(rel); String q = ""; if(isSameStructRelationship) { q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + contentlet.getIdentifier() + " " + rel.getRelationTypeValue() + "-child:" + contentlet.getIdentifier() + ") "; if(!InodeUtils.isSet(contentlet.getIdentifier())){ q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + "0 " + rel.getRelationTypeValue() + "-child:" + "0 ) "; } } else { q = "+type:content +" + rel.getRelationTypeValue() + ":" + contentlet.getIdentifier(); if(!InodeUtils.isSet(contentlet.getIdentifier())){ q = "+type:content +" + rel.getRelationTypeValue() + ":" + "0"; } } return q; }

Target:
private String getRelatedContentESQuery(Contentlet contentlet, Relationship rel) { final boolean isSameStructRelationship = FactoryLocator.getRelationshipFactory() .sameParentAndChild(rel); String q; if(isSameStructRelationship) { q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + contentlet.getIdentifier() + " " + rel.getRelationTypeValue() + "-child:" + contentlet.getIdentifier() + ") "; if(!InodeUtils.isSet(contentlet.getIdentifier())){ q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + "0 " + rel.getRelationTypeValue() + "-child:" + "0 ) "; } } else { q = "+type:content +" + rel.getRelationTypeValue() + ":" + contentlet.getIdentifier(); if(!InodeUtils.isSet(contentlet.getIdentifier())){ q = "+type:content +" + rel.getRelationTypeValue() + ":" + "0"; } } return q; }
Source:
private void init() { RStudioGinjector.INSTANCE.injectMembers(this); docDisplay_.addSaveCompletedHandler((SaveFileEvent event) -> { discoverPackageDependencies(); }); }

Target:
private void init() { RStudioGinjector.INSTANCE.injectMembers(this); docDisplay_.addSaveCompletedHandler((SaveFileEvent event) -> { if (!event.isAutosave()) discoverPackageDependencies(); }); events_.addHandler(AvailablePackagesReadyEvent.TYPE, (AvailablePackagesReadyEvent event) -> { discoverPackageDependencies(); }); }
Source:
private void markDelivered(InboxMessage message) { changeStatus(message, InboxMessageStatus.DELIVERED); deliveredMessages.recordDelivered(message); }

Target:
private void markDelivered(InboxMessage message) { changeStatus(message, DELIVERED); deliveredMessages.recordDelivered(message); }
Source:
private void setProperties(URL url, Properties properties) { putPropertyIfAbsent(url, properties, NAMESPACE); putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME); String endpoint = url.getParameter(ENDPOINT); if (StringUtils.isNotEmpty(endpoint)) { if (endpoint.contains(":")) { int index = endpoint.lastIndexOf(":"); properties.put(ENDPOINT, endpoint.substring(0, index)); properties.put(ENDPOINT_PORT, endpoint.substring(index + 1)); }else{ putPropertyIfAbsent(url, properties, ENDPOINT); } } putPropertyIfAbsent(url, properties, ACCESS_KEY); putPropertyIfAbsent(url, properties, SECRET_KEY); putPropertyIfAbsent(url, properties, CLUSTER_NAME); }

Target:
private void setProperties(URL url, Properties properties) { putPropertyIfAbsent(url, properties, NAMESPACE); putPropertyIfAbsent(url, properties, NACOS_NAMING_LOG_NAME); String endpoint = url.getParameter(ENDPOINT); String[] hostAndPort = NetUtils.getHostAndPort(endpoint); if (hostAndPort[1] == null) { properties.put(ENDPOINT, hostAndPort[0]); }else{ properties.put(ENDPOINT, hostAndPort[0]); properties.put(ENDPOINT_PORT, hostAndPort[1]); } putPropertyIfAbsent(url, properties, ACCESS_KEY); putPropertyIfAbsent(url, properties, SECRET_KEY); putPropertyIfAbsent(url, properties, CLUSTER_NAME); }
Source:
public PartitionedQueryQueue pickQueue() { while (true) { try { final int pick = random.nextInt(queues.size()); final PartitionedQueryQueue queue = queues.get(pick); return queue; } catch (final IllegalArgumentException e) { } } }

Target:
public PartitionedQueryQueue pickQueue() { while (true) { try { final int pick = random.nextInt(queues.size()); final PartitionedQueryQueue queue = queues.get(pick); return queue; } catch (final IllegalArgumentException e) { return null; } } }
Source:
public Map<String, AbstractDefinition> getTableDefinitionMap() { return tableDefinitionMap; }

Target:
public Map<String, TableDefinition> getTableDefinitionMap() { return tableDefinitionMap.entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> (TableDefinition) e.getValue())); }
Source:
public void testAuditLoggerWithCreateFlag() throws IOException { final Configuration conf = new HdfsConfiguration(); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); LogCapturer auditlog = LogCapturer.captureLogs(FSNamesystem.auditLog); try { cluster.waitClusterUp(); auditlog.clearOutput(); final FileSystem fs = cluster.getFileSystem(); final Path p = new Path("/debug.log"); FSDataOutputStream stm = fs.create(p); assertTrue(auditlog.getOutput().contains("create(options")); auditlog.clearOutput(); stm.close(); stm = fs.append(p); assertTrue(auditlog.getOutput().contains("append(options")); stm.close(); auditlog.clearOutput(); } finally { cluster.shutdown(); } }

Target:
public void testAuditLoggerWithCreateFlag() throws IOException { final Configuration conf = new HdfsConfiguration(); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); LogCapturer auditlog = LogCapturer.captureLogs(FSNamesystem.auditLog); try { cluster.waitClusterUp(); auditlog.clearOutput(); final FileSystem fs = cluster.getFileSystem(); final Path p = new Path("/debug.log"); FSDataOutputStream stm = fs.create(p, false); assertTrue(auditlog.getOutput().contains(STR_AUDIT_CREATE_NOOVERRITE)); auditlog.clearOutput(); stm.close(); stm = fs.create(p, true); assertTrue(auditlog.getOutput().contains(STR_AUDIT_CREATE_OVERRITE)); auditlog.clearOutput(); stm.close(); stm = fs.create(p); assertTrue(auditlog.getOutput().contains(STR_AUDIT_CREATE_OVERRITE)); auditlog.clearOutput(); stm.close(); stm = fs.append(p); assertTrue(auditlog.getOutput().contains(STR_AUDIT_APPEND)); stm.close(); auditlog.clearOutput(); } finally { cluster.shutdown(); } }
Source:
private void lockDown() throws Exception { GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy(); j.jenkins.setAuthorizationStrategy(auth); j.jenkins.setCrumbIssuer(null); HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false); j.jenkins.setSecurityRealm(realm); User user = realm.createAccount("John Smith", "password"); user.save(); auth.add(Jenkins.ADMINISTER, user.getId()); }

Target:
private void lockDown() throws Exception { SecurityRealm securityRealm = j.createDummySecurityRealm(); j.getInstance().setSecurityRealm(securityRealm); GlobalMatrixAuthorizationStrategy authorizationStrategy = new GlobalMatrixAuthorizationStrategy(); authorizationStrategy.add(Hudson.READ, "authenticated"); j.getInstance().setAuthorizationStrategy(authorizationStrategy); }