auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public MatchAnyValidator(List<AttributeValidator> validators) { if (validators == null) { this.validators = null; } else { this.validators = validators .stream() .sorted(Comparator.comparingInt(Object::hashCode)) .collect(Collectors.toList()); } }

Target:
public MatchAnyValidator(List<AttributeValidator> validators) { if (validators == null) { this.validators = Collections.<AttributeValidator>emptyList(); } else { this.validators = validators .stream() .sorted(Comparator.comparingInt(Object::hashCode)) .collect(Collectors.toList()); } }
Source:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClient httpClient; if (getSslContextBinding() != null) { final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setSslContext(getSslContextBinding().getProvider().get()); httpClient = new HttpClient(sslContextFactory); } else { httpClient = new HttpClient(); } httpClient.setIdleTimeout(config.getReadTimeout().getMillis()); httpClient.setMaxConnectionsPerDestination(config.getNumConnections()); final QueuedThreadPool queuedThreadPool = new QueuedThreadPool(config.getNumMaxThreads()); queuedThreadPool.setName(QueuedThreadPool.class.getSimpleName() + "@" + queuedThreadPool.hashCode()); httpClient.setExecutor(queuedThreadPool); final Lifecycle lifecycle = getLifecycleProvider().get(); try { lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { } @Override public void stop() { try { httpClient.stop(); } catch (Exception e) { throw Throwables.propagate(e); } } } ); } catch (Exception e) { throw Throwables.propagate(e); } return httpClient; }

Target:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClient httpClient; if (getSslContextBinding() != null) { final SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setSslContext(getSslContextBinding().getProvider().get()); httpClient = new HttpClient(sslContextFactory); } else { httpClient = new HttpClient(); } httpClient.setIdleTimeout(config.getReadTimeout().getMillis()); httpClient.setMaxConnectionsPerDestination(config.getNumConnections()); final QueuedThreadPool pool = new QueuedThreadPool(config.getNumMaxThreads()); pool.setName(JettyHttpClientModule.class.getSimpleName() + "-threadPool-" + pool.hashCode()); httpClient.setExecutor(pool); final Lifecycle lifecycle = getLifecycleProvider().get(); try { lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { } @Override public void stop() { try { httpClient.stop(); } catch (Exception e) { throw Throwables.propagate(e); } } } ); } catch (Exception e) { throw Throwables.propagate(e); } return httpClient; }
Source:
public static int mode(File f) throws PosixException { try { if (Functions.isWindows()) { return -1; } else if (Util.NATIVE_CHMOD_MODE) { return PosixAPI.jnr().stat(f.getPath()).mode(); } else { return Util.permissionsToMode(Files.getPosixFilePermissions(f.toPath())); } } catch (InvalidPathException | IOException cause) { PosixException e = new PosixException("Unable to get file permissions", null); e.initCause(cause); throw e; } }

Target:
public static int mode(File f) throws PosixException { if(Functions.isWindows()) return -1; try { if (Util.NATIVE_CHMOD_MODE) { return PosixAPI.jnr().stat(f.getPath()).mode(); } else { return Util.permissionsToMode(Files.getPosixFilePermissions(Util.fileToPath(f))); } } catch (IOException cause) { PosixException e = new PosixException("Unable to get file permissions", null); e.initCause(cause); throw e; } }
Source:
private boolean processRebalance(LineTcpMeasurementEvent event) { if (event.rebalanceToThreadId == id) { if (!event.rebalanceReleasedByFromThread) { return false; } return true; } if (event.rebalanceFromThreadId == id) { Parser parser = parserCache.get(event.rebalanceTableName); parserCache.remove(event.rebalanceTableName); parser.close(); event.rebalanceReleasedByFromThread = true; return true; } return true; }

Target:
private boolean processRebalance(LineTcpMeasurementEvent event) { if (event.rebalanceToThreadId == id) { return event.rebalanceReleasedByFromThread; } if (event.rebalanceFromThreadId == id) { Parser parser = parserCache.get(event.rebalanceTableName); parserCache.remove(event.rebalanceTableName); parser.close(); event.rebalanceReleasedByFromThread = true; } return true; }
Source:
public static ConfigErrorFormGroupDisplayer getErrorGroup() { return IOC.getBeanManager().lookupBean( ConfigErrorFormGroupDisplayer.class ).newInstance(); }

Target:
public static ConfigErrorFormGroupDisplayer getErrorGroup() { return configErrorDisplayer.newInstance(); }
Source:
public static String escapeStringLiteral(final String s) { Preconditions.checkNotNull(s); if (s == null) { return "''"; } else { boolean isPlainAscii = true; final StringBuilder builder = new StringBuilder("'"); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); if (Character.isLetterOrDigit(c) || c == ' ') { builder.append(c); if (c > 127) { isPlainAscii = false; } } else { builder.append("\\").append(BaseEncoding.base16().encode(Chars.toByteArray(c))); isPlainAscii = false; } } builder.append("'"); return isPlainAscii ? builder.toString() : "U&" + builder.toString(); } }

Target:
public static String escapeStringLiteral(final String s) { Preconditions.checkNotNull(s); boolean isPlainAscii = true; final StringBuilder builder = new StringBuilder("'"); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); if (Character.isLetterOrDigit(c) || c == ' ') { builder.append(c); if (c > 127) { isPlainAscii = false; } } else { builder.append("\\").append(BaseEncoding.base16().encode(Chars.toByteArray(c))); isPlainAscii = false; } } builder.append("'"); return isPlainAscii ? builder.toString() : "U&" + builder.toString(); }
Source:
static RailDirection fromFaces(final Direction firstDirection, final Direction secondDirection) { checkNotNull(firstDirection, "firstDirection"); checkNotNull(secondDirection, "secondDirection"); Direction cardinalFirstDirection = Direction.getClosest(firstDirection.asOffset(), Direction.Division.CARDINAL); Direction cardinalSecondDirection = Direction.getClosest(secondDirection.asOffset(), Direction.Division.CARDINAL); if (cardinalFirstDirection.equals(cardinalSecondDirection)) { throw new IllegalArgumentException("The directions should be different!"); } for (RailDirection currentRailDirection: Sponge.getRegistry().getAllForMinecraft(RailDirection.class)) { if (currentRailDirection.isFacing(cardinalFirstDirection) && currentRailDirection.isFacing(cardinalSecondDirection)) { return currentRailDirection; } } throw new AssertionError(); }

Target:
static RailDirection fromFaces(final Direction firstDirection, final Direction secondDirection) { checkNotNull(firstDirection, "firstDirection"); checkNotNull(secondDirection, "secondDirection"); if (!firstDirection.isCardinal() || !secondDirection.isCardinal()) { throw new IllegalArgumentException("The given directions isn't cardinal!"); } for (RailDirection currentRailDirection: Sponge.getRegistry().getAllForMinecraft(RailDirection.class)) { if (currentRailDirection.isFacing(firstDirection) && currentRailDirection.isFacing(secondDirection)) { return currentRailDirection; } } throw new IllegalArgumentException(); }
Source:
public static String[] getStringArrayProperty(Map properties, String key) { if (properties == null) return null; Object value = properties.get(key); List<String> r = new ArrayList<String>(); if (value == null) r = Collections.EMPTY_LIST; if (value instanceof String) r = Collections.singletonList((String) value); if (value instanceof String[]) { String[] values = (String[]) value; for (String value2 : values) { if (value2 != null) r.add(value2); } } if (value instanceof Collection) { Collection values = (Collection) value; List result = new ArrayList(values.size()); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { result.add(v); } } } return (r.size() == 0) ? null : r.toArray(new String[r.size()]); }

Target:
public static String[] getStringArrayProperty(Map properties, String key) { if (properties == null) return null; Object value = properties.get(key); List<String> r = new ArrayList<String>(); if (value == null) r = Collections.EMPTY_LIST; if (value instanceof String) r = Collections.singletonList((String) value); if (value instanceof String[]) { String[] values = (String[]) value; for (String v : values) { if (v != null) r.add(v); } } if (value instanceof Collection) { Collection values = (Collection) value; List result = new ArrayList(values.size()); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { result.add(v); } } } return (r.size() == 0) ? null : r.toArray(new String[r.size()]); }
Source:
private String formatWifiNameList(Set<String> ssids) { if (ssids != null) { ssids = new TreeSet<>(ssids); StringBuilder sb = new StringBuilder(); for (String ssid : ssids) { if (sb.length() > 0) { sb.append(", "); } sb.append(ssid.replaceFirst("^\"", "").replaceFirst("\"$", "")); } return sb.toString(); } return null; }

Target:
private String formatWifiNameList(Set<String> ssids) { Set<String> formatted = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (String ssid : ssids) { formatted.add(ssid.replaceFirst("^\"", "").replaceFirst("\"$", "")); } return TextUtils.join(", ", formatted); }
Source:
public ContainerAsyncClient getContainerAsyncClient() { return new ContainerAsyncClient(new AzureBlobStorageBuilder() .url(Utility.stripLastPathSegment(getBlobUrl()).toString()) .pipeline(blobAsyncRawClient.azureBlobStorage.httpPipeline())); }

Target:
public ContainerAsyncClient getContainerAsyncClient() { try { BlobURLParts parts = URLParser.parse(getBlobUrl()); return new ContainerAsyncClient(new AzureBlobStorageBuilder() .url(String.format("%s://%s/%s", parts.scheme(), parts.host(), parts.containerName())) .pipeline(blobAsyncRawClient.azureBlobStorage.httpPipeline())); } catch (UnknownHostException e) { throw new RuntimeException(e); } }
Source:
private void readLoop(long ledgerId, CompletableFuture<LedgerMetadata> promise) { LedgerMetadata current = currentLocalValue.get(); lm.readLedgerMetadata(ledgerId, (rc, read) -> { if (rc != BKException.Code.OK) { promise.completeExceptionally(BKException.create(rc)); } else if (current.getVersion().equals(read.getVersion())) { promise.complete(current); } else if (updateLocalValue.test(current, read)) { promise.complete(read); } else { readLoop(ledgerId, promise); } }); }

Target:
private void readLoop(long ledgerId, CompletableFuture<LedgerMetadata> promise) { LedgerMetadata current = currentLocalValue.get(); lm.readLedgerMetadata(ledgerId, (rc, read) -> { if (rc != BKException.Code.OK) { LOG.error("{} Failed to read metadata from store, rc = {}", logContext, rc); promise.completeExceptionally(BKException.create(rc)); } else if (current.getVersion().compare(read.getVersion()) == Version.Occurred.CONCURRENTLY) { promise.complete(current); } else if (updateLocalValue.updateValue(current, read)) { promise.complete(read); } else { readLoop(ledgerId, promise); } }); }
Source:
public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; this.m_srcBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); this.m_dstBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); this.m_partialLength = ByteBuffer.allocate(4); }

Target:
public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; }
Source:
public TracePackageExportOperation(TracePackageTraceElement[] traceExportElements, boolean useCompression, boolean useTar, String fileName) { super(fileName); fTraceExportElements = Arrays.copyOf(traceExportElements,traceExportElements.length); fUseCompression = useCompression; fUseTar = useTar; fResources = new HashSet<>(); }

Target:
public TracePackageExportOperation(TracePackageTraceElement[] traceExportElements, boolean useCompression, boolean useTar, String fileName) { super(fileName); fTraceExportElements = (traceExportElements == null ? null : Arrays.copyOf(traceExportElements, traceExportElements.length)); fUseCompression = useCompression; fUseTar = useTar; fResources = new HashSet<>(); }
Source:
public boolean useAjaxTabs() { ConfigurationService configurationService = Framework.getService(ConfigurationService.class); if (configurationService.getBoolean(AJAX_TAB_PROPERTY, true)) { return canUseAjaxTabs(); } return false; }

Target:
public boolean useAjaxTabs() { ConfigurationService configurationService = Framework.getService(ConfigurationService.class); if (configurationService.isBooleanTrue(AJAX_TAB_PROPERTY)) { return canUseAjaxTabs(); } return false; }
Source:
public static void savePage(Long listingId, String[] p1q1) { Listing listing = Listing.getByListingId(listingId); validation.required(p1q1).key("p1q1"); validation.isTrue(ValidationUtils.stringArrayValuesAreNotTooLong(p1q1, 30)).key("p1q1").message("Invalid values"); if(validation.hasErrors()) { flash.put("body", params.get("body")); for(Map.Entry<String, List<Error>> entry : validation.errorsMap().entrySet()) { String key = entry.getKey(); String value = entry.getValue().get(0).message(); flash.put(key, value); } redirect(String.format("/page/%d/%d", PAGE_ID, listing.id)); } if (listing.serviceSubmitted) { redirect(listing.summaryPageUrl()); } else { Gson gson = new Gson(); Page page = new Page(listingId, PAGE_ID); page.responses.put("p1q1", gson.toJson(p1q1)); page.insert(); listing.addResponsePage(page, PAGE_ID, supplierDetailsFromCookie.get("supplierEmail")); redirect(listing.nextPageUrl(PAGE_ID, listing.id)); } }

Target:
public static void savePage(Long listingId, String[] p1q1) { Listing listing = Listing.getByListingId(listingId); if (listing.serviceSubmitted) { redirect(listing.summaryPageUrl()); } validation.required(p1q1).key("p1q1"); validation.isTrue(ValidationUtils.stringArrayValuesAreNotTooLong(p1q1, 30)).key("p1q1").message("Invalid values"); if(validation.hasErrors()) { flash.put("body", params.get("body")); for(Map.Entry<String, List<Error>> entry : validation.errorsMap().entrySet()) { String key = entry.getKey(); String value = entry.getValue().get(0).message(); flash.put(key, value); } redirect(String.format("/page/%d/%d", PAGE_ID, listing.id)); } Gson gson = new Gson(); Page page = new Page(listingId, PAGE_ID); page.responses.put("p1q1", gson.toJson(p1q1)); page.insert(); listing.addResponsePage(page, PAGE_ID, supplierDetailsFromCookie.get("supplierEmail")); redirect(listing.nextPageUrl(PAGE_ID, listing.id)); }
Source:
private void updateConsoleAddressPartiallyOverridden(VDSGroup cluster) { AsyncQuery query = new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { @SuppressWarnings("unchecked") boolean toShowWarning = isConsoleAddressPartiallyOverridden((List<VDS>) ((VdcQueryReturnValue) returnValue).getReturnValue()); setConsoleAddressPartiallyOverridden(toShowWarning); } } ); Frontend.RunQuery( VdcQueryType.GetHostsByClusterId, new GetHostsByClusterIdParameters(cluster.getId()), query ); }

Target:
private void updateConsoleAddressPartiallyOverridden(VDSGroup cluster) { AsyncQuery query = new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { boolean toShowWarning = (Boolean) ((VdcQueryReturnValue) returnValue).getReturnValue(); setConsoleAddressPartiallyOverridden(toShowWarning); } } ); Frontend.RunQuery( VdcQueryType.GetHostsInClusterPartiallyOverridden, new GetHostsInClusterPartiallyOverriddenParameters(cluster.getId()), query ); }
Source:
public Email read( ObjectDataInput in ) throws IOException { return null; }

Target:
public Email read( ObjectDataInput in ) throws IOException { return deserialize( in ); }
Source:
protected <K, V> EntryListener<K, V> putAllEntryListenerBuilder(Consumer<EntryEvent<K, V>> f) { return new EntryAdapter<K, V>() { public void entryAdded(EntryEvent<K, V> event) { f.accept(event); } public void entryRemoved(EntryEvent<K, V> event) { System.out.println("entryRemoved " + event); } public void entryEvicted(EntryEvent<K, V> event) { entryRemoved(event); } @Override public void mapEvicted(MapEvent event) { } @Override public void mapCleared(MapEvent event) { System.out.println("mapCleared " + event); } }; }

Target:
protected <K, V> EntryListener<K, V> putAllEntryListenerBuilder(Consumer<EntryEvent<K, V>> f) { return new EntryAdapter<K, V>() { public void entryAdded(EntryEvent<K, V> event) { f.accept(event); } public void entryRemoved(EntryEvent<K, V> event) { } public void entryEvicted(EntryEvent<K, V> event) { entryRemoved(event); } @Override public void mapEvicted(MapEvent event) { } @Override public void mapCleared(MapEvent event) { } }; }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Ean)) { return false; } final Ean other = (Ean) o; if (this.device != null ? !this.device.getDeviceIdentification().equals(other.device.getDeviceIdentification()) : other.device != null) { return false; } if (this.code != null ? !this.code.equals(other.code) : other.code != null) { return false; } if (this.description != null ? !this.description.equals(other.description) : other.description != null) { return false; } return true; }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Ean)) { return false; } final Ean other = (Ean) o; final boolean isDeviceEqual = Objects.equals(this.device, other.device); final boolean isCodeEqual = Objects.equals(this.code, other.code); final boolean isDescriptionEqual = Objects.equals(this.description, other.description); return isDeviceEqual && isCodeEqual && isDescriptionEqual; }
Source:
private void addCrewMember(org.atlasapi.media.entity.CrewMember legacy, CrewMember translated) { translated.withName(legacy.name()); if (Objects.nonNull(legacy.role())) { translated.withRole(CrewMember.Role.fromKey(legacy.role().key())); } }

Target:
private void addCrewMember(org.atlasapi.media.entity.CrewMember legacy, CrewMember translated) { translated.withName(legacy.name()); if (null != legacy.role()) { translated.withRole(CrewMember.Role.fromKey(legacy.role().key())); } }
Source:
static ForkJoinPool getInstance(final ConfigContext config) { Validate.notNull(config, "Configuration context is null"); int processors = Runtime.getRuntime().availableProcessors(); final String parallelismSysProp = System.getProperty(SYSTEM_FORK_JOIN_POOL_PARALLELISM_KEY); if (parallelismSysProp != null) { try { processors = Integer.valueOf(System.getProperty(SYSTEM_FORK_JOIN_POOL_PARALLELISM_KEY)); } catch (NumberFormatException e) { } } final int parallelism = Math.min(config.getMaximumConnections() - 2, processors); return new ForkJoinPool(parallelism); }

Target:
static ForkJoinPool getInstance(final ConfigContext config) { Validate.notNull(config, "Configuration context is null"); final int maximumConnections = Validate.notNull( config.getMaximumConnections(), "Maximum connections setting is null"); Validate.isTrue(maximumConnections > 0, "Maximum connections is not greater than zero"); final int parallelism = calculateParallelism(maximumConnections); return new ForkJoinPool(parallelism); }
Source:
protected OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; }

Target:
OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; }
Source:
public static Single<Integer> processMetadata(String path) throws IOException { Map<MetadataType, Metadata> metadataMap = Metadata.readMetadata(path); Metadata metadata = metadataMap.get(MetadataType.IPTC); byte[] b = new byte[0]; try { b = ((IPTC) metadata).getDataSets().get("SpecialInstructions").get(0).getData(); } catch (NullPointerException e) { return Single.just(ImageUtils.IMAGE_OK); } for (int i = 0; i < b.length; i++) { if (b[i] == 70 && b[i + 1] == 66 && b[i + 2] == 77 && b[i + 3] == 68) { Timber.d("Contains FBMD"); return Single.just(ImageUtils.FILE_FBMD); } } return Single.just(ImageUtils.IMAGE_OK); }

Target:
public Single<Integer> processMetadata(String path) throws IOException { Map<MetadataType, Metadata> metadataMap = Metadata.readMetadata(path); Metadata metadata = metadataMap.get(MetadataType.IPTC); byte[] dataInBytes = new byte[0]; try { dataInBytes = ((IPTC) metadata).getDataSets().get("SpecialInstructions").get(0).getData(); } catch (NullPointerException e) { return Single.just(ImageUtils.IMAGE_OK); } if (dataInBytes[0] == 70 && dataInBytes[1] == 66 && dataInBytes[2] == 77 && dataInBytes[3] == 68) { Timber.d("Contains FBMD"); return Single.just(ImageUtils.FILE_FBMD); } return Single.just(ImageUtils.IMAGE_OK); }
Source:
public void isConnWithSameDetailsExistFileDomains() { StorageServerConnections newNFSConnection = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection1 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection2 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 600, 0); List<StorageServerConnections> connections = Arrays.asList(connection1, connection2); when(storageConnDao.getAllForStorage(newNFSConnection.getConnection())).thenReturn(connections); doReturn(newNFSConnection.getId()).when(command).isConnWithSameDetailsExists(newNFSConnection, null); }

Target:
public void isConnWithSameDetailsExistFileDomains() { StorageServerConnections newNFSConnection = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection1 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection2 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 600, 0); List<StorageServerConnections> connections = Arrays.asList(connection1, connection2); when(storageConnDao.getAllForStorage(newNFSConnection.getConnection())).thenReturn(connections); boolean isExists = !command.isConnWithSameDetailsExists(newNFSConnection, null).isEmpty(); assertTrue(isExists); }
Source:
public void onNext(final ContextStop contextStop) { LOG.log(Level.FINE, "Wait {0} milliseconds at maximum for the PS server to be closed", CLOSE_TIMEOUT_MS); try { parameterServer.close(CLOSE_TIMEOUT_MS); LOG.fine("Succeed to close PS server cleanly"); } catch (InterruptedException | TimeoutException | ExecutionException e) { LOG.log(Level.INFO, "Fail to close PS server cleanly", e); } psNetworkSetup.unregisterConnectionFactory(); }

Target:
public void onNext(final ContextStop contextStop) { LOG.log(Level.FINE, "Wait {0} milliseconds at maximum for the PS server to be closed", CLOSE_TIMEOUT_MS); try { parameterServer.close(CLOSE_TIMEOUT_MS); LOG.fine("Succeed to close PS server cleanly"); } catch (InterruptedException | TimeoutException | ExecutionException e) { LOG.log(Level.WARNING, "Fail to close PS server cleanly", e); } psNetworkSetup.unregisterConnectionFactory(); }
Source:
public synchronized Schema addColumn(String name, TypeDesc typeDesc) { String normalized = name; if(fieldsByQualifiedName.containsKey(normalized)) { throw new TajoRuntimeException(new DuplicateColumnException(normalized)); } Column newCol = new Column(normalized, typeDesc); fields.add(newCol); fieldsByQualifiedName.put(newCol.getQualifiedName(), fields.size() - 1); List inputList = new ArrayList<>(); inputList.add(fields.size() - 1); fieldsByName.put(newCol.getSimpleName(), inputList); return this; }

Target:
public synchronized Schema addColumn(String name, TypeDesc typeDesc) { String normalized = name; if(fieldsByQualifiedName.containsKey(normalized)) { throw new TajoRuntimeException(new DuplicateColumnException(normalized)); } Column newCol = new Column(normalized, typeDesc); fields.add(newCol); fieldsByQualifiedName.put(newCol.getQualifiedName(), fields.size() - 1); List<Integer> inputList = new ArrayList<>(); inputList.add(fields.size() - 1); fieldsByName.put(newCol.getSimpleName(), inputList); return this; }
Source:
private void assertVolumeAvailable(Volume volume) { assertRandom(new Predicate<VolumeRef>() { @Override public boolean apply(VolumeRef volumeRef) { Volume volume = api.volumeApi().getVolume(volumeRef.dataCenterId(), volumeRef.volumeId()); if (volume == null || volume.metadata() == null) return false; return volume.metadata().state() == State.AVAILABLE; } }, VolumeRef.create(volume.dataCenterId(), volume.id())); }

Target:
private void assertVolumeAvailable(Volume volume) { assertPredicate(new Predicate<VolumeRef>() { @Override public boolean apply(VolumeRef volumeRef) { Volume volume = api.volumeApi().getVolume(volumeRef.dataCenterId(), volumeRef.volumeId()); if (volume == null || volume.metadata() == null) return false; return volume.metadata().state() == State.AVAILABLE; } }, VolumeRef.create(volume.dataCenterId(), volume.id())); }
Source:
public List<PersistableBusinessObject> generateDeactivationsToPersist() { List<SubAccount> bosToDeactivate = new ArrayList (); if (!isActive()) { Map<String, Object> fieldValues = new HashMap(); fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, getChartOfAccountsCode()); fieldValues.put(KFSPropertyConstants.ACCOUNT_NUMBER, getAccountNumber()); fieldValues.put(KFSPropertyConstants.ACTIVE, true); Collection<SubAccount> existingSubAccounts = SpringContext.getBean(BusinessObjectService.class) .findMatching(SubAccount.class, fieldValues); bosToDeactivate.addAll(existingSubAccounts); } for (SubAccount subAccount : bosToDeactivate) { subAccount.setActive(false); } return new ArrayList<>(bosToDeactivate); }

Target:
public List<PersistableBusinessObject> generateDeactivationsToPersist() { List<SubAccount> bosToDeactivate = new ArrayList<>(); if (!isActive()) { Map<String, Object> fieldValues = new HashMap<>(); fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, getChartOfAccountsCode()); fieldValues.put(KFSPropertyConstants.ACCOUNT_NUMBER, getAccountNumber()); fieldValues.put(KFSPropertyConstants.ACTIVE, true); Collection<SubAccount> existingSubAccounts = SpringContext.getBean(BusinessObjectService.class) .findMatching(SubAccount.class, fieldValues); bosToDeactivate.addAll(existingSubAccounts); } for (SubAccount subAccount : bosToDeactivate) { subAccount.setActive(false); } return new ArrayList<>(bosToDeactivate); }
Source:
private void addAPI(API api, int tenantId) throws APIManagementException { int apiId = apiMgtDAO.addAPI(api, tenantId); addLocalScopes(api.getId(), tenantId, api.getUriTemplates()); addURITemplates(apiId, api, tenantId); HashSet<String> endpointRegistryEntries = APIUtil.extractEndpointRegistryEntries(api.getEndpointConfig()); if (!endpointRegistryEntries.isEmpty()) { apiMgtDAO.addAPIServiceCatalogEntryMappings(apiId, endpointRegistryEntries, null); } APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_CREATE.name(), tenantId, api.getId().getApiName(), apiId, api.getId().getVersion(), api.getType(), api.getContext(), api.getId().getProviderName(), api.getStatus()); APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name()); }

Target:
private void addAPI(API api, int tenantId) throws APIManagementException { int apiId = apiMgtDAO.addAPI(api, tenantId); addLocalScopes(api.getId(), tenantId, api.getUriTemplates()); addURITemplates(apiId, api, tenantId); HashSet<String> serviceCatalogEntries = APIUtil.extractServiceCatalogEntries(api.getEndpointConfig()); if (!serviceCatalogEntries.isEmpty()) { apiMgtDAO.addAPIServiceCatalogEntryMappings(apiId, serviceCatalogEntries, null); } APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_CREATE.name(), tenantId, api.getId().getApiName(), apiId, api.getId().getVersion(), api.getType(), api.getContext(), api.getId().getProviderName(), api.getStatus()); APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name()); }
Source:
public ChargeEntity markChargeAsEligibleForCapture(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { ChargeStatus targetStatus = charge.isDelayedCapture() ? AWAITING_CAPTURE_REQUEST : CAPTURE_APPROVED; ChargeStatus currentChargeStatus = fromString(charge.getStatus()); try { updateChargeStatus(charge, targetStatus); } catch (InvalidStateTransitionException e) { logger.error("Charge with state " + currentChargeStatus + " cannot proceed to " + targetStatus + " [charge_external_id={}, charge_status={}]", charge.getExternalId(), currentChargeStatus); throw new IllegalStateRuntimeException(charge.getExternalId()); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }

Target:
public ChargeEntity markChargeAsEligibleForCapture(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { ChargeStatus targetStatus = charge.isDelayedCapture() ? AWAITING_CAPTURE_REQUEST : CAPTURE_APPROVED; try { updateChargeStatus(charge, targetStatus); } catch (InvalidStateTransitionException e) { throw new IllegalStateRuntimeException(charge.getExternalId()); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }
Source:
FileRevisionTypedElement getAncestorRevision() { if (ancestor instanceof FileRevisionTypedElement) { return (FileRevisionTypedElement) ancestor; } return null; }

Target:
FileRevisionTypedElement getAncestorRevision() { if (ancestor instanceof FileRevisionTypedElement) return (FileRevisionTypedElement) ancestor; return null; }
Source:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } else { return key; } }

Target:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } return key; }
Source:
private ITmfEvent parseLine(TmfContext context) { @Nullable ITmfLocation location = context.getLocation(); if (location != null) { try { if (!location.getLocationInfo().equals(fFileInput.getFilePointer())) { seekEvent(location); } } catch (IOException e1) { seekEvent(location); } String line; try { line = fFileInput.readLine(); return parseLine(context.getRank(), line); } catch (IOException e) { Activator.logError(e.getMessage(), e); } } return null; }

Target:
private ITmfEvent parseLine(TmfContext context) { ITmfLocation location = context.getLocation(); if (location != null) { try { if (!location.getLocationInfo().equals(fFileInput.getFilePointer())) { seekEvent(location); } } catch (IOException e1) { seekEvent(location); } String line; try { line = fFileInput.readLine(); return parseLine(context.getRank(), line); } catch (IOException e) { Activator.logError(e.getMessage(), e); } } return null; }
Source:
private ServerErrorCode validateRequest(PartitionId partition, RequestOrResponseType requestType) { if (partition == null) { metrics.badRequestError.inc(); return ServerErrorCode.Bad_Request; } if (storageManager.getStore(partition) == null) { boolean partitionPresent = false; for (ReplicaId replica : partition.getReplicaIds()) { if (replica.getDataNodeId().equals(currentNode)) { partitionPresent = true; break; } } if (partitionPresent) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } else { metrics.partitionUnknownError.inc(); return ServerErrorCode.Partition_Unknown; } } List<? extends ReplicaId> replicaIds = partition.getReplicaIds(); for (ReplicaId replica : replicaIds) { if (replica.getDataNodeId().getHostname().equals(currentNode.getHostname()) && replica.getDataNodeId().getPort() == currentNode.getPort()) { if (replica.getDiskId().getState() == HardwareState.UNAVAILABLE) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } } } if (requestType.equals(RequestOrResponseType.PutRequest) && partition.getPartitionState() == PartitionState.READ_ONLY) { metrics.partitionReadOnlyError.inc(); return ServerErrorCode.Partition_ReadOnly; } if (!isRequestEnabled(requestType, partition)) { metrics.temporarilyUnavailableError.inc(); return ServerErrorCode.Temporarily_Unavailable; } return ServerErrorCode.No_Error; }

Target:
private ServerErrorCode validateRequest(PartitionId partition, RequestOrResponseType requestType) { if (partition == null) { metrics.badRequestError.inc(); return ServerErrorCode.Bad_Request; } if (storageManager.getStore(partition) == null) { boolean partitionPresent = false; for (ReplicaId replica : partition.getReplicaIds()) { if (replica.getDataNodeId().equals(currentNode)) { partitionPresent = true; break; } } if (partitionPresent) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } else { metrics.partitionUnknownError.inc(); return ServerErrorCode.Partition_Unknown; } } List<? extends ReplicaId> replicaIds = partition.getReplicaIds(); for (ReplicaId replica : replicaIds) { if (replica.getDataNodeId().getHostname().equals(currentNode.getHostname()) && replica.getDataNodeId().getPort() == currentNode.getPort()) { if (replica.getDiskId().getState() == HardwareState.UNAVAILABLE) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } } } if (requestType.equals(RequestOrResponseType.PutRequest) && partition.getPartitionState() == PartitionState.READ_ONLY) { metrics.partitionReadOnlyError.inc(); return ServerErrorCode.Partition_ReadOnly; } if (!isRequestEnabled(requestType, partition)) { metrics.temporarilyUnavailableError.inc(); return ServerErrorCode.Temporarily_Disabled; } return ServerErrorCode.No_Error; }
Source:
private Optional<String> readFromResources(final String filePath) { final ClassLoader classLoader = TestDataFileReader.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream(filePath)) { return Optional.of(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); } catch (final NullPointerException | IOException e) { return Optional.empty(); } }

Target:
private Optional<String> readFromResources(final String filePath) { final ClassLoader classLoader = TestDataFileReader.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream(filePath)) { return Optional.of(new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)); } catch (final NullPointerException | IOException e) { return Optional.empty(); } }
Source:
public ConnectedChannel checkOutConnection(String host, int port, long timeoutInMs) throws IOException, InterruptedException, ConnectionPoolTimeoutException { final Timer.Context context = connectionCheckOutTime.time(); BlockingChannelInfo blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { synchronized (this) { blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { logger.trace("Creating new blocking channel info for host and port {}", host, port); blockingChannelInfo = new BlockingChannelInfo(config, host, port, registry); connections.put(host + port, blockingChannelInfo); } } } context.stop(); return blockingChannelInfo.getBlockingChannel(timeoutInMs); }

Target:
public ConnectedChannel checkOutConnection(String host, int port, long timeoutInMs) throws IOException, InterruptedException, ConnectionPoolTimeoutException { final Timer.Context context = connectionCheckOutTime.time(); try { BlockingChannelInfo blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { synchronized (this) { blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { logger.trace("Creating new blocking channel info for host and port {}", host, port); blockingChannelInfo = new BlockingChannelInfo(config, host, port, registry); connections.put(host + port, blockingChannelInfo); } } } return blockingChannelInfo.getBlockingChannel(timeoutInMs); } finally { context.stop(); } }
Source:
public void shutdown(IRecordProcessorCheckpointer iRecordProcessorCheckpointer, ShutdownReason shutdownReason) { LOGGER.warn("SHUTDOWN: {}", shutdownReason.toString()); if(shutdownReason == ShutdownReason.TERMINATE) { LOGGER.warn("Going to checkpoint"); try { iRecordProcessorCheckpointer.checkpoint(); LOGGER.warn("Checkpointed successfully"); } catch (InvalidStateException e) { LOGGER.error(e.getMessage()); } catch (ShutdownException e) { LOGGER.error(e.getMessage()); } } }

Target:
public void shutdown(IRecordProcessorCheckpointer iRecordProcessorCheckpointer, ShutdownReason shutdownReason) { LOGGER.warn("SHUTDOWN: {}", shutdownReason.toString()); if(shutdownReason.equals(ShutdownReason.TERMINATE)) { LOGGER.warn("Going to checkpoint"); try { iRecordProcessorCheckpointer.checkpoint(); LOGGER.warn("Checkpointed successfully"); } catch (InvalidStateException e) { LOGGER.error(e.getMessage()); } catch (ShutdownException e) { LOGGER.error(e.getMessage()); } } }
Source:
public void testDeleteCommentAsRelation() { CommentManager anotherCommentManager = new CommentManagerImpl(CommentServiceHelper.getCommentService().getConfig()); DocumentModel commentDocModel = createComment(anotherCommentManager); Comment comment = anotherCommentManager.getComment(session, commentDocModel.getId()); assertNotNull(comment); CommentService commentComponent = (CommentService) Framework.getRuntime().getComponent(CommentService.NAME); RelationManager relationManager = Framework.getService(RelationManager.class); CommentServiceConfig config = commentComponent.getConfig(); if (config != null) { Resource commentRes = relationManager.getResource(config.commentNamespace, commentDocModel, null); assertNotNull(commentRes); Graph graph = relationManager.getGraph(config.graphName, commentDocModel.getCoreSession()); Resource predicateRes = new ResourceImpl(config.predicateNamespace); assertTrue(graph.getObjects(commentRes, predicateRes).stream().findAny().isPresent()); } commentManager.deleteComment(session, commentDocModel.getId()); try { anotherCommentManager.getComment(session, commentDocModel.getId()); fail(); } catch (CommentNotFoundException cfe) { assertNotNull(cfe); assertNotNull(cfe.getMessage()); } }

Target:
public void testDeleteCommentAsRelation() { CommentManager anotherCommentManager = Framework.getService(CommentManager.class); DocumentModel commentDocModel = createComment(anotherCommentManager); Comment comment = anotherCommentManager.getComment(session, commentDocModel.getId()); assertNotNull(comment); CommentService commentComponent = (CommentService) Framework.getRuntime().getComponent(CommentService.NAME); RelationManager relationManager = Framework.getService(RelationManager.class); CommentServiceConfig config = commentComponent.getConfig(); if (config != null) { Resource commentRes = relationManager.getResource(config.commentNamespace, commentDocModel, null); assertNotNull(commentRes); Graph graph = relationManager.getGraph(config.graphName, commentDocModel.getCoreSession()); Resource predicateRes = new ResourceImpl(config.predicateNamespace); assertTrue(graph.getObjects(commentRes, predicateRes).stream().findAny().isPresent()); } commentManager.deleteComment(session, commentDocModel.getId()); try { anotherCommentManager.getComment(session, commentDocModel.getId()); fail(); } catch (CommentNotFoundException cfe) { assertNotNull(cfe); assertNotNull(cfe.getMessage()); } }
Source:
public void testLotsOfWrites() { Cache<String, String> cache = cache(0); int amount = 5_0000; for (int i = 0; i < amount; ++i) { cache.put("key" + i, "value" + i); } assertEquals(amount, cache.size()); }

Target:
public void testLotsOfWrites() { Cache<String, String> cache = cache(0); for (int i = 0; i < 5_000; ++i) { cache.put("key" + i, "value" + i); } }
Source:
public void setUp() throws Exception { File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); System.out.println(tmpDir); conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); conf.setEntryLogSizeLimit(2048); ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); interleavedStorage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager, null, checkpointSource, checkpointer, NullStatsLogger.INSTANCE); for (long entryId = 0; entryId < numWrites; entryId++) { for (long ledgerId = 0; ledgerId < 5; ledgerId++) { if (entryId == 0) { interleavedStorage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes()); interleavedStorage.setFenced(ledgerId); } ByteBuf entry = Unpooled.buffer(128); entry.writeLong(ledgerId); entry.writeLong(entryId * entriesPerWrite); entry.writeBytes(("entry-" + entryId).getBytes()); interleavedStorage.addEntry(entry); } } }

Target:
public void setUp() throws Exception { File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); conf.setEntryLogSizeLimit(2048); ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); interleavedStorage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager, null, checkpointSource, checkpointer, NullStatsLogger.INSTANCE); for (long entryId = 0; entryId < numWrites; entryId++) { for (long ledgerId = 0; ledgerId < 5; ledgerId++) { if (entryId == 0) { interleavedStorage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes()); interleavedStorage.setFenced(ledgerId); } ByteBuf entry = Unpooled.buffer(128); entry.writeLong(ledgerId); entry.writeLong(entryId * entriesPerWrite); entry.writeBytes(("entry-" + entryId).getBytes()); interleavedStorage.addEntry(entry); } } }
Source:
public ItemBucketBCA(Fluid fluid) { super(fluid.getBlock()); this.fluid = new FluidStack(fluid.getID(), FluidContainerRegistry.BUCKET_VOLUME); setContainerItem(Items.bucket); setCreativeTab(BuildcraftAdditions.bcadditions); setUnlocalizedName("bcaBucket." + fluid.getName()); if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) MinecraftForgeClient.registerItemRenderer(this, BucketItemRenderer.INSTANCE); }

Target:
public ItemBucketBCA(Fluid fluid) { super(fluid.getBlock()); this.fluid = new FluidStack(fluid.getID(), FluidContainerRegistry.BUCKET_VOLUME); setContainerItem(Items.bucket); setCreativeTab(BuildcraftAdditions.bcadditions); setUnlocalizedName("bcaBucket." + fluid.getName()); }
Source:
public synchronized void releaseEncodedBuffer() { if (temporaryBuffer != null && temporaryBuffer.release()) { temporaryBuffer = null; } }

Target:
public void releaseEncodedBuffer() { internalReleaseBuffer(1); }
Source:
public void updateSessionAttributes(String id, Map<String, Object> sessionAttributes) { SessionData sessionData = sessionDataMap.get(id); if (sessionData != null && !sessionData.getAllAttributes().equals(sessionAttributes)) { LOGGER.debug( "Storing new attributes for session at context {}", id, _context.getCanonicalContextPath()); synchronized (this) { sessionData.clearAllAttributes(); sessionData.putAllAttributes(sessionAttributes); } } }

Target:
public void updateSessionAttributes(String id, Map<String, Object> sessionAttributes) { synchronized (sessionDataMap) { SessionData sessionData = sessionDataMap.get(id); if (sessionData != null && !sessionData.getAllAttributes().equals(sessionAttributes)) { LOGGER.trace( "Storing new attributes for session at context {}", id, _context.getCanonicalContextPath()); sessionData.clearAllAttributes(); sessionData.putAllAttributes(sessionAttributes); } } }
Source:
protected void say(String text) { try { Voice voice = null; for (Voice currentVoice : tts.getAvailableVoices()) { if (this.locale.getLanguage().equals(currentVoice.getLocale().getLanguage())) { voice = currentVoice; break; } } if (null == voice) { throw new TTSException("Unable to find a voice"); } AudioStream audioStream = tts.synthesize(text, voice, null); try { sink.process(audioStream); } catch (UnsupportedAudioFormatException | UnsupportedAudioStreamException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } } catch (TTSException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } }

Target:
protected void say(String text) { try { Voice voice = null; for (Voice currentVoice : tts.getAvailableVoices()) { if (this.locale.getLanguage().equals(currentVoice.getLocale().getLanguage())) { voice = currentVoice; break; } } if (null == voice) { throw new TTSException("Unable to find a suitable voice"); } AudioStream audioStream = tts.synthesize(text, voice, null); try { sink.process(audioStream); } catch (UnsupportedAudioFormatException | UnsupportedAudioStreamException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } } catch (TTSException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } }
Source:
public synchronized void serviceStop() throws Exception { if (isSession) { sessionStopped.set(true); } if (this.dagSubmissionTimer != null) { this.dagSubmissionTimer.cancel(); } stopServices(); boolean deleteTezScratchData = this.amConf.getBoolean( TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE, TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE_DEFAULT); LOG.info("Checking whether tez scratch data dir should be deleted, deleteTezScratchData=" + deleteTezScratchData); if (deleteTezScratchData && this.taskSchedulerEventHandler != null && this.taskSchedulerEventHandler.hasUnregistered()) { if (this.tezSystemStagingDir != null) { LOG.info("Deleting tez scratch data dir, path=" + this.tezSystemStagingDir); try { FileSystem fs = this.tezSystemStagingDir.getFileSystem(this.amConf); boolean deletedStagingDir = fs.delete(this.tezSystemStagingDir, true); if (!deletedStagingDir) { LOG.warn("Failed to delete tez scratch data dir, path=" + this.tezSystemStagingDir); } else { LOG.info("Completed deletion of tez scratch data dir, path=" + this.tezSystemStagingDir); } } catch (IOException e) { LOG.warn("Failed to tez scratch data dir", e); } } } super.serviceStop(); }

Target:
public synchronized void serviceStop() throws Exception { if (isSession) { sessionStopped.set(true); } if (this.dagSubmissionTimer != null) { this.dagSubmissionTimer.cancel(); } stopServices(); boolean deleteTezScratchData = this.amConf.getBoolean( TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE, TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE_DEFAULT); if (LOG.isDebugEnabled()) { LOG.debug("Checking whether tez scratch data dir should be deleted, deleteTezScratchData=" + deleteTezScratchData); } if (deleteTezScratchData && this.taskSchedulerEventHandler != null && this.taskSchedulerEventHandler.hasUnregistered()) { if (this.tezSystemStagingDir != null) { try { FileSystem fs = this.tezSystemStagingDir.getFileSystem(this.amConf); boolean deletedStagingDir = fs.delete(this.tezSystemStagingDir, true); if (!deletedStagingDir) { LOG.warn("Failed to delete tez scratch data dir, path=" + this.tezSystemStagingDir); } else { LOG.info("Completed deletion of tez scratch data dir, path=" + this.tezSystemStagingDir); } } catch (IOException e) { LOG.warn("Failed to delete tez scratch data dir", e); } } } super.serviceStop(); }