auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void initialize(Config newConfig) { super.initialize(newConfig); this.config = newConfig; this.connectionString = Context.stateManagerConnectionString(newConfig); this.isSchedulerService = Context.schedulerService(newConfig); this.tunnelProcesses = new ArrayList<>(); NetworkUtils.TunnelConfig tunnelConfig = NetworkUtils.TunnelConfig.build(config, NetworkUtils.HeronSystem.STATE_MANAGER); if (tunnelConfig.isTunnelNeeded()) { Pair<String, List<Process>> tunneledResults = setupZkTunnel(tunnelConfig); String newConnectionString = tunneledResults.first; if (newConnectionString.isEmpty()) { throw new IllegalArgumentException("Cannot connect to tunnelHost: " + tunnelConfig.getTunnelHost() + "\nBad connectionString: " + connectionString); } connectionString = newConnectionString; tunnelProcesses.addAll(tunneledResults.second); } client = getCuratorClient(); LOG.info("Starting client to: " + connectionString); client.start(); try { if (!client.blockUntilConnected(ZkContext.connectionTimeoutMs(newConfig), TimeUnit.MILLISECONDS)) { throw new RuntimeException("Failed to initialize CuratorClient"); } } catch (InterruptedException e) { throw new RuntimeException("Failed to initialize CuratorClient", e); } if (ZkContext.isInitializeTree(newConfig)) { initTree(); } }

Target:
public void initialize(Config newConfig) { super.initialize(newConfig); this.config = newConfig; this.connectionString = Context.stateManagerConnectionString(newConfig); this.isSchedulerService = Context.schedulerService(newConfig); this.tunnelProcesses = new ArrayList<>(); NetworkUtils.TunnelConfig tunnelConfig = NetworkUtils.TunnelConfig.build(config, NetworkUtils.HeronSystem.STATE_MANAGER); if (tunnelConfig.isTunnelNeeded()) { Pair<String, List<Process>> tunneledResults = setupZkTunnel(tunnelConfig); String newConnectionString = tunneledResults.first; if (newConnectionString.isEmpty()) { throw new IllegalArgumentException("Cannot connect to tunnelHost: " + tunnelConfig.getTunnelHost() + " Bad connectionString: " + connectionString); } connectionString = newConnectionString; tunnelProcesses.addAll(tunneledResults.second); } client = getCuratorClient(); LOG.info("Starting client to: " + connectionString); client.start(); try { if (!client.blockUntilConnected(ZkContext.connectionTimeoutMs(newConfig), TimeUnit.MILLISECONDS)) { throw new RuntimeException("Failed to initialize CuratorClient"); } } catch (InterruptedException e) { throw new RuntimeException("Failed to initialize CuratorClient", e); } if (ZkContext.isInitializeTree(newConfig)) { initTree(); } }
Source:
private void writeToFile(URI parentName, String newFileName, String content, Properties metadata) throws Exception { File parent = new File(parentName); if (!parent.exists() && !parent.mkdirs()) { handleException("Unable to create parent directory: " + parentName); } File newFile = new File(parent, newFileName); File newMetadataFile = new File(parent, newFileName + METADATA_FILE_SUFFIX); try (BufferedWriter writer = new BufferedWriter(new FileWriter(newFile)); BufferedWriter metadataWriter = new BufferedWriter(new FileWriter(newMetadataFile))) { writer.write(content); writer.flush(); metadata.store(metadataWriter, null); if (log.isDebugEnabled()) { log.debug("Successfully content written to file : " + parentName + URL_SEPARATOR + newFileName); } } catch (IOException e) { handleException("Couldn't write to registry resource: " + parentName + URL_SEPARATOR + newFileName, e); } }

Target:
private void writeToFile(URI parentName, String newFileName, String content, Properties metadata) { File parent = new File(parentName); if (!parent.exists() && !parent.mkdirs()) { handleException("Unable to create parent directory: " + parentName); } File newFile = new File(parent, newFileName); try (BufferedWriter writer = new BufferedWriter(new FileWriter(newFile))) { writer.write(content); writer.flush(); writeMetadata(parent, newFileName, metadata); if (log.isDebugEnabled()) { log.debug("Successfully content written to file : " + parentName + URL_SEPARATOR + newFileName); } } catch (IOException e) { handleException("Couldn't write to registry resource: " + parentName + URL_SEPARATOR + newFileName, e); } }
Source:
static void setResult(ImageView target, Context context, RequestHandler.Result result, boolean noFade, boolean debugging) { Drawable placeholder = target.getDrawable(); if (placeholder instanceof Animatable) { ((Animatable) placeholder).stop(); } if (result.hasBitmap()) { Picasso.LoadedFrom loadedFrom = result.getLoadedFrom(); Bitmap bitmap = result.getBitmap(); PicassoDrawable drawable = new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging); target.setImageDrawable(drawable); } Drawable drawable = result.getDrawable(); if (drawable != null) { target.setImageDrawable(drawable); if (drawable instanceof Animatable) { ((Animatable) drawable).start(); } } }

Target:
static void setResult(ImageView target, Context context, RequestHandler.Result result, boolean noFade, boolean debugging) { Drawable placeholder = target.getDrawable(); if (placeholder instanceof Animatable) { ((Animatable) placeholder).stop(); } if (result.hasBitmap()) { Picasso.LoadedFrom loadedFrom = result.getLoadedFrom(); Bitmap bitmap = result.getBitmap(); PicassoDrawable drawable = new PicassoDrawable(context, bitmap, placeholder, loadedFrom, noFade, debugging); target.setImageDrawable(drawable); } else if (result.hasDrawable()) { Drawable drawable = result.getDrawable(); target.setImageDrawable(drawable); if (drawable instanceof Animatable) { ((Animatable) drawable).start(); } } }
Source:
public AccumuloClient getConnector(String user, String passwd) throws AccumuloException, AccumuloSecurityException { return impl.getAccumuloClient(user, new PasswordToken(passwd)); }

Target:
public Connector getConnector(String user, String passwd) throws AccumuloException, AccumuloSecurityException { return Connector.from(impl.getAccumuloClient(user, new PasswordToken(passwd))); }
Source:
public void loginFacebook(final String fbAccessToken, final MojioClient.ResponseListener<User> responseListener) { if (_oauthHelper.shouldRefreshAccessToken() || _oauthHelper.isUserToken()) { authenticateApp(new ResponseListener<UserToken>() { @Override public void onSuccess(UserToken result) { loginFacebook(fbAccessToken, responseListener); } @Override public void onFailure(ResponseError error) { responseListener.onFailure(error); } }); return; } String entityPath = String.format("Login/ExternalUser?accessToken=%s", fbAccessToken); this.create(UserToken.class, entityPath, new MojioClient.ResponseListener<UserToken>() { @Override public void onSuccess(UserToken result) { _oauthHelper.setAccessToken(result._id, result.ValidUntil); String userID = result.UserId; getUser(userID, responseListener); } @Override public void onFailure(ResponseError error) { responseListener.onFailure(error); } }); }

Target:
public void loginFacebook(final String fbAccessToken, final MojioClient.ResponseListener<User> responseListener) { if (_oauthHelper.shouldRefreshAccessToken() || _oauthHelper.isUserToken()) { authenticateApp(new ResponseListener<UserToken>() { @Override public void onSuccess(UserToken result) { Log.d(TAG, "App token " + result._id + " set. Proceeding to external user login."); loginFacebook(fbAccessToken, responseListener); } @Override public void onFailure(ResponseError error) { responseListener.onFailure(error); } }); return; } String entityPath = String.format("Login/ExternalUser?accessToken=%s", fbAccessToken); this.create(UserToken.class, entityPath, new MojioClient.ResponseListener<UserToken>() { @Override public void onSuccess(UserToken result) { Log.d(TAG, "Login successful. User token: " + result._id); _oauthHelper.setAccessToken(result._id, result.ValidUntil); String userID = result.UserId; getUser(userID, responseListener); } @Override public void onFailure(ResponseError error) { responseListener.onFailure(error); } }); }
Source:
public DatabaseBackupResponse createDatabaseBackup(DatabaseBackupRequest databaseBackupRequest) throws MambuApiException { if (databaseBackupRequest == null || databaseBackupRequest.getCallback() == null) { throw new IllegalArgumentException("Request object and callback field must not be null!!"); } createDatabaseBackup.setUrlPath(createDatabaseBackup.getEndPoint() + "/" + APIData.BACKUP); return serviceExecutor.executeJson(createDatabaseBackup, databaseBackupRequest); }

Target:
public DatabaseBackupResponse createDatabaseBackup(DatabaseBackupRequest databaseBackupRequest) throws MambuApiException { if (databaseBackupRequest != null && databaseBackupRequest.getCallback() != null) { validateCallbackUrl(databaseBackupRequest.getCallback()); } createDatabaseBackup.setUrlPath(createDatabaseBackup.getEndPoint() + "/" + APIData.BACKUP); return serviceExecutor.executeJson(createDatabaseBackup, databaseBackupRequest); }
Source:
public void run() { try { cloudFile.uploadFromFile(TEMP_FILE.toString()); } catch (StorageException | IOException | URISyntaxException e) { throw new RuntimeException(e); } }

Target:
public void run() { try { cloudFile.uploadFromFile(TEMP_FILE_PATH); } catch (StorageException | IOException | URISyntaxException e) { throw new RuntimeException(e); } }
Source:
public TypeConverter createTypeConverter(String className) throws Exception { Class<?> classInstance = objectFactory.getClassInstance(className); if (TypeConverter.class.isAssignableFrom(classInstance)) { Class<? extends TypeConverter> converterClass = (Class<? extends TypeConverter>) classInstance; return objectFactory.buildConverter(converterClass, null); } else { throw new IllegalArgumentException("Type converter class " + className + " doesn't implement " + TypeConverter.class.getName()); } }

Target:
public TypeConverter createTypeConverter(String className) throws Exception { Class<?> clazz = objectFactory.getClassInstance(className); return createTypeConverter(clazz); }
Source:
public void workerExecutor3(Vertx vertx) { int poolSize = 10; long maxExecuteTime = 120000000000L; WorkerExecutor executor = vertx.createSharedWorkerExecutor("my-worker-pool", poolSize, maxExecuteTime); }

Target:
public void workerExecutor3(Vertx vertx) { int poolSize = 10; long maxExecuteTime = 2; TimeUnit maxExecuteTimeUnit = TimeUnit.SECONDS; WorkerExecutor executor = vertx.createSharedWorkerExecutor("my-worker-pool", poolSize, maxExecuteTime, maxExecuteTimeUnit); }
Source:
public void testSchemaWithLongName() throws Exception { deployContrib("org.nuxeo.ecm.core.storage.sql.test.tests", "OSGI-INF/test-schema-longname.xml"); applyInlineDeployments(); postSetUp(); Session session = repository.getConnection(); session.getRootNode(); }

Target:
public void testSchemaWithLongName() throws Exception { pushInlineDeployments("org.nuxeo.ecm.core.storage.sql.test.tests:OSGI-INF/test-schema-longname.xml"); Session session = repository.getConnection(); session.getRootNode(); }
Source:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(!currentItems.isEmpty()) { JSONObject item = (JSONObject) parent.getAdapter().getItem(position); this.selection = item.has("Text1")?item.getString("Text1"):""; this.selectionDetailText = item.has("Text2")?item.getString("Text2"):""; this.selectionIndex = itemAdapterCopy.getPosition(item)+1; } else { System.out.println("Spannable Adapter/..........."); Spannable item = (Spannable) parent.getAdapter().getItem(position); this.selection = item.toString(); this.selectionIndex = adapterCopy.getPosition(item) + 1; } AfterPicking(); }

Target:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (!dictItems.isEmpty()) { YailDictionary item = (YailDictionary) parent.getAdapter().getItem(position); this.selection = ElementsUtil.toStringEmptyIfNull(item.get("Text1")); this.selectionDetailText = ElementsUtil.toStringEmptyIfNull(item.get("Text2")); this.selectionIndex = itemAdapterCopy.getPosition(item) + 1; } else { Spannable item = (Spannable) parent.getAdapter().getItem(position); this.selection = item.toString(); this.selectionIndex = adapterCopy.getPosition(item) + 1; } AfterPicking(); }
Source:
protected void addParametersForScript( final Map<String, Object> parameters, final Set<Command> resources, final JobRequest jobRequest ) { parameters.put(COMMANDS_BINDING, resources); }

Target:
protected void addParametersForScript( final Map<String, Object> parameters, final Set<Command> resources, final JobRequest jobRequest ) { super.addParametersForScript(parameters, resources, jobRequest); parameters.put(COMMANDS_BINDING, resources); }
Source:
private static DwrfProto.ColumnEncoding toColumnEncoding(ColumnEncoding columnEncodings) { Preconditions.checkArgument( !columnEncodings.getSequenceEncodings().isPresent(), "DWRF writer doesn't support flat map encodings: " + columnEncodings); return DwrfProto.ColumnEncoding.newBuilder() .setKind(toColumnEncoding(columnEncodings.getColumnEncodingKind())) .setDictionarySize(columnEncodings.getDictionarySize()) .build(); }

Target:
private static DwrfProto.ColumnEncoding toColumnEncoding(ColumnEncoding columnEncodings) { checkArgument( !columnEncodings.getAdditionalSequenceEncodings().isPresent(), "DWRF writer doesn't support writing columns with non-zero sequence IDs: " + columnEncodings); return DwrfProto.ColumnEncoding.newBuilder() .setKind(toColumnEncoding(columnEncodings.getColumnEncodingKind())) .setDictionarySize(columnEncodings.getDictionarySize()) .build(); }
Source:
public static boolean isSmallIde(){ return PlatformUtils.isRubyMine() || PlatformUtils.isPyCharm() || PlatformUtils.isPhpStorm() || PlatformUtils.isWebStorm(); }

Target:
public static boolean isSmallIde(){ return PlatformUtils.isRubyMine() || PlatformUtils.isPyCharm() || PlatformUtils.isPhpStorm() || PlatformUtils.isWebStorm() || PlatformUtils.isAppCode() || PlatformUtils.isCLion(); }
Source:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainIdValid(storageDomainId)) { throw new EngineException(EngineError.GetIsoListError); } if (forceRefresh) { if (!refreshRepos(storageDomainId, imageType)) { throw new EngineException(EngineError.IMAGES_NOT_SUPPORTED_ERROR); } } else { refreshReposIfIntervalPassed(storageDomainId, imageType); } return getCachedIsoListByDomainId(storageDomainId, imageType); }

Target:
public List<RepoImage> getUserRequestForStorageDomainRepoFileList(Guid storageDomainId, ImageFileType imageType, boolean forceRefresh) { if (!isStorageDomainIdValid(storageDomainId)) { throw new EngineException(EngineError.GetIsoListError); } refreshReposIfNeeded(storageDomainId, imageType, forceRefresh); return getCachedIsoListByDomainId(storageDomainId, imageType); }
Source:
public boolean eat(GlowPlayer player, ItemStack item) { PlayerItemConsumeEvent event1 = new PlayerItemConsumeEvent(player, item); EventFactory.callEvent(event1); if (event1.isCancelled()) return false; player.setUsageItem(null); player.setUsageTime(0); player.getInventory().getItemInHand().setType(Material.BUCKET); for(PotionEffect potionEffect : player.getActivePotionEffects()) { player.removePotionEffect(potionEffect.getType()); } return true; }

Target:
public boolean eat(GlowPlayer player, ItemStack item) { PlayerItemConsumeEvent event1 = new PlayerItemConsumeEvent(player, item); EventFactory.callEvent(event1); if (event1.isCancelled()) return false; player.setUsageItem(null); player.setUsageTime(0); for (PotionEffect potionEffect : player.getActivePotionEffects()) { player.removePotionEffect(potionEffect.getType()); } player.getInventory().getItemInHand().setType(Material.BUCKET); return true; }
Source:
protected void doStart() throws Exception { for (int i = 0; i < schedulers.length; i++) { schedulers[i] = Executors.newScheduledThreadPool(threadsPerScheduler, Threads.daemonThreadsNamed(threadBaseName + "-%s-lock" + i)); } }

Target:
protected void doStart() throws Exception { for (int i = 0; i < schedulers.length; i++) { schedulers[i] = Executors.newScheduledThreadPool(threadsPerScheduler, Threads.daemonThreadsNamed(threadBaseName + "-timeout-%s" + i)); } }
Source:
public void onGenerateMapButtonClicked() { try { if (!previousMapName.getText().isEmpty()){ mapGeneratorService.generateMap(previousMapName.getText()).thenAccept(mapName -> { Platform.runLater(() -> { createGameController.initMapSelection(); createGameController.mapListView.getItems().stream() .filter(mapBean -> mapBean.getFolderName().equalsIgnoreCase(mapName)) .findAny().ifPresent(mapBean -> { createGameController.mapListView.getSelectionModel().select(mapBean); createGameController.mapListView.scrollTo(mapBean); createGameController.setSelectedMap(mapBean); }); }); }); } else { byte spawnCount = spawnCountSpinner.getValue().byteValue(); byte landDensity = (byte) (127 - getSliderValue(waterSlider, waterRandom)); byte plateauDensity = getSliderValue(plateauSlider, plateauRandom); byte mountainDensity = getSliderValue(mountainSlider, mountainRandom); byte rampDensity = getSliderValue(rampSlider, rampRandom); byte[] optionArray = {spawnCount, landDensity, plateauDensity, mountainDensity, rampDensity}; mapGeneratorService.generateMap(optionArray).thenAccept(mapName -> { Platform.runLater(() -> { createGameController.initMapSelection(); createGameController.mapListView.getItems().stream() .filter(mapBean -> mapBean.getFolderName().equalsIgnoreCase(mapName)) .findAny().ifPresent(mapBean -> { createGameController.mapListView.getSelectionModel().select(mapBean); createGameController.mapListView.scrollTo(mapBean); createGameController.setSelectedMap(mapBean); }); }); }); } } catch (Exception e) { notificationService.addImmediateErrorNotification(e, "mapGenerator.generationFailed"); log.error("Map generation failed", e); } onCloseButtonClickedListener.run(); }

Target:
public void onGenerateMapButtonClicked() { onGenerateMap(); }
Source:
public ExecutionStrategyParameters transform(Consumer<Builder> builderConsumer) { Builder builder = new Builder(this); builderConsumer.accept(builder); return builder.build(); }

Target:
public ExecutionStrategyParameters transform(Consumer<Builder> builderConsumer) { Builder builder = newParameters(this); builderConsumer.accept(builder); return builder.build(); }
Source:
private boolean isMatchingTrigger(DockerEvent dockerEvent, Trigger trigger) { String account = dockerEvent.getContent().getAccount(); String repository = dockerEvent.getContent().getRepository(); String eventTag = dockerEvent.getContent().getTag(); String triggerTagPattern = null; if(trigger.getTag() != null && trigger.getTag().trim().length() > 0) { triggerTagPattern = trigger.getTag().trim(); } return trigger.getType().equals(TRIGGER_TYPE) && trigger.getRepository().equals(repository) && trigger.getAccount().equals(account) && ((triggerTagPattern == null && !eventTag.equals("latest")) || triggerTagPattern != null && matchTags(triggerTagPattern, eventTag)); }

Target:
private boolean isMatchingTrigger(DockerEvent dockerEvent, Trigger trigger) { String account = dockerEvent.getContent().getAccount(); String repository = dockerEvent.getContent().getRepository(); String eventTag = dockerEvent.getContent().getTag(); String triggerTagPattern = null; if (StringUtils.isNotBlank(trigger.getTag())) { triggerTagPattern = trigger.getTag().trim(); } return trigger.getType().equals(TRIGGER_TYPE) && trigger.getRepository().equals(repository) && trigger.getAccount().equals(account) && ((triggerTagPattern == null && !eventTag.equals("latest")) || triggerTagPattern != null && matchTags(triggerTagPattern, eventTag)); }
Source:
public IASTTranslationUnit getAST(ITranslationUnit tu, IProgressMonitor pm) throws CoreException, OperationCanceledException { if (isDisposed()) throw new IllegalStateException("CRefactoringContext is already disposed."); getIndex(); if (pm != null && pm.isCanceled()) throw new OperationCanceledException(); tu= CModelUtil.toWorkingCopy(tu); IASTTranslationUnit ast= fASTCache.get(tu); if (ast == null) { if (fSharedAST != null && tu.equals(fSharedAST.getOriginatingTranslationUnit())) { ast = fSharedAST; } else { ast = ASTProvider.getASTProvider().acquireSharedAST(tu, fIndex, ASTProvider.WAIT_ACTIVE_ONLY, pm); if (ast == null || ast.skippedNodes()) { if (ast != null) { ASTProvider.getASTProvider().releaseSharedAST(ast); } if (pm != null && pm.isCanceled()) throw new OperationCanceledException(); ast= tu.getAST(fIndex, PARSE_MODE); fASTCache.put(tu, ast); } else { if (fSharedAST != null) { ASTProvider.getASTProvider().releaseSharedAST(fSharedAST); } fSharedAST = ast; } } } if (pm != null) { pm.done(); } return ast; }

Target:
public IASTTranslationUnit getAST(ITranslationUnit tu, IProgressMonitor pm) throws CoreException, OperationCanceledException { if (isDisposed()) throw new IllegalStateException("CRefactoringContext is already disposed."); getIndex(); if (pm != null && pm.isCanceled()) throw new OperationCanceledException(); tu= CModelUtil.toWorkingCopy(tu); IASTTranslationUnit ast= fASTCache.get(tu); if (ast == null) { if (fSharedAST != null && tu.equals(fSharedAST.getOriginatingTranslationUnit())) { ast = fSharedAST; } else { ast = ASTProvider.getASTProvider().acquireSharedAST(tu, fIndex, ASTProvider.WAIT_ACTIVE_ONLY, pm); if (ast != null && ast.hasNodesOmitted()) { ASTProvider.getASTProvider().releaseSharedAST(ast); ast = null; } if (ast == null) { if (pm != null && pm.isCanceled()) throw new OperationCanceledException(); ast= tu.getAST(fIndex, PARSE_MODE); fASTCache.put(tu, ast); } else { if (fSharedAST != null) { ASTProvider.getASTProvider().releaseSharedAST(fSharedAST); } fSharedAST = ast; } } } if (pm != null) { pm.done(); } return ast; }
Source:
public CommandCallback getCallback() { if (FeatureSupported.isQemuingCommitSupported(getStoragePool().getCompatibilityVersion())) { return new ConcurrentChildCommandsExecutionCallback(); } if (getVm().isQualifiedForLiveSnapshotMerge() || getParameters().isUseCinderCommandCallback()) { return new ConcurrentChildCommandsExecutionCallback(); } return null; }

Target:
public CommandCallback getCallback() { if (getVm().isQualifiedForLiveSnapshotMerge() || getParameters().isUseCinderCommandCallback() || FeatureSupported.isQemuingCommitSupported(getStoragePool().getCompatibilityVersion())) { return new ConcurrentChildCommandsExecutionCallback(); } return null; }
Source:
private void handleFinishedContext(final String contextId, final Optional<ActiveContext> parentContext) { boolean needToCloseParent = false; if (contextIdToWorkerContexts.containsKey(contextId)) { handleFinishedWorkerContext(contextId); } else if (contextIdToServerContexts.containsKey(contextId)) { handleFinishedServerContext(contextId); } else if (contextIdToRootContexts.remove(contextId) != null) { LOG.log(Level.INFO, "Root context {0} is closed. Its evaluator will be released soon.", contextId); } else if (deletedWorkerContextIds.remove(contextId) || deletedServerContextIds.remove(contextId)) { LOG.log(Level.INFO, "The context {0} is closed by EM's Delete.", contextId); needToCloseParent = true; } else { LOG.log(Level.WARNING, "Untracked context: {0}", contextId); needToCloseParent = true; } if (needToCloseParent) { if (parentContext.isPresent()) { LOG.log(Level.WARNING, "Close a context {0} , which is a parent of the closed context whose id is {1}", new Object[]{parentContext, contextId}); parentContext.get().close(); } } }

Target:
private void handleFinishedContext(final String contextId, final Optional<ActiveContext> parentContext) { boolean needToCloseParent = false; if (contextIdToWorkerContexts.containsKey(contextId)) { handleFinishedWorkerContext(contextId); } else if (contextIdToServerContexts.containsKey(contextId)) { handleFinishedServerContext(contextId); } else if (contextIdToRootContexts.remove(contextId) != null) { LOG.log(Level.INFO, "Root context {0} is closed. Its evaluator will be released soon.", contextId); } else if (deletedWorkerContextIds.remove(contextId) || deletedServerContextIds.remove(contextId)) { LOG.log(Level.INFO, "The context {0} is closed by EM's Delete.", contextId); needToCloseParent = true; } else { LOG.log(Level.WARNING, "Untracked context: {0}", contextId); needToCloseParent = true; } if (needToCloseParent) { if (parentContext.isPresent()) { LOG.log(Level.INFO, "Close a context {0}, which is a parent of the closed context whose id is {1}", new Object[]{parentContext, contextId}); parentContext.get().close(); } } }
Source:
public int position() { return (int)mCompressedStream.getPosition(); }

Target:
public long position() { if (mCompressedStream == null) { throw new SAMException("Null input stream."); } return mCompressedStream.getPosition(); }
Source:
private void newSnapshot() { if (getWindow() != null) { return; } final UIConstants constants = ConstantsManager.getInstance().getConstants(); GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); GlusterVolumeSnapshotModel snapshotModel = new GlusterVolumeSnapshotModel(); snapshotModel.setHelpTag(HelpTag.new_volume_snapshot); snapshotModel.setHashName("new_volume_snapshot"); snapshotModel.setTitle(ConstantsManager.getInstance().getConstants().createSnapshotTitle()); setWindow(snapshotModel); snapshotModel.getClusterName().setEntity(volumeEntity.getVdsGroupName()); snapshotModel.getVolumeName().setEntity(volumeEntity.getName()); UICommand okCommand = new UICommand("onCreateSnapshot", this); okCommand.setTitle(constants.ok()); okCommand.setIsDefault(true); snapshotModel.getCommands().add(okCommand); UICommand cancelCommand = new UICommand("Cancel", this); cancelCommand.setTitle(constants.cancel()); cancelCommand.setIsCancel(true); snapshotModel.getCommands().add(cancelCommand); }

Target:
private void newSnapshot() { if (getWindow() != null) { return; } final UIConstants constants = ConstantsManager.getInstance().getConstants(); GlusterVolumeEntity volumeEntity = getEntity(); GlusterVolumeSnapshotModel snapshotModel = new GlusterVolumeSnapshotModel(); snapshotModel.setHelpTag(HelpTag.new_volume_snapshot); snapshotModel.setHashName("new_volume_snapshot"); snapshotModel.setTitle(ConstantsManager.getInstance().getConstants().createSnapshotTitle()); setWindow(snapshotModel); snapshotModel.getClusterName().setEntity(volumeEntity.getVdsGroupName()); snapshotModel.getVolumeName().setEntity(volumeEntity.getName()); UICommand okCommand = new UICommand("onCreateSnapshot", this); okCommand.setTitle(constants.ok()); okCommand.setIsDefault(true); snapshotModel.getCommands().add(okCommand); UICommand cancelCommand = new UICommand("Cancel", this); cancelCommand.setTitle(constants.cancel()); cancelCommand.setIsCancel(true); snapshotModel.getCommands().add(cancelCommand); }
Source:
private boolean uploadBundle(String moduleSource, String moduleId, File bundleFile, String startBundle, String bundleSymbolicName) throws IOException, InterruptedException { String uri = String.format("http://%s:%d/admin/api/bundles/upload/", HOST, PORT); HttpPost httpPost = new HttpPost(uri); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); Charset chars = Charset.forName("UTF-8"); entity.setCharset(chars); entity.addTextBody("moduleSource", moduleSource, ContentType.MULTIPART_FORM_DATA); if (moduleSource.equals("Repository")) { entity.addTextBody("moduleId", moduleId, ContentType.MULTIPART_FORM_DATA); } else if (moduleSource.equals("File")) { if (bundleFile == null) { fail("Bundle file was null."); } entity.addBinaryBody("bundleFile", bundleFile); } else { fail("Wrong module source."); } entity.addTextBody("startBundle", startBundle, ContentType.MULTIPART_FORM_DATA); httpPost.setEntity(entity.build()); int bundlesCountBeforeUpload = bundleContext.getBundles().length; HttpResponse response = getHttpClient().execute(httpPost); EntityUtils.consume(response.getEntity()); int bundlesCountAfterUpload = bundleContext.getBundles().length; if (response.getStatusLine().getStatusCode() != HttpStatus.ORDINAL_200_OK) { fail("Wrong response code."); } Bundle uploadedBundle = getBundleFromBundlesArray(bundleSymbolicName); if(uploadedBundle == null) { fail("Couldn't find uploaded bundle in current bundles."); } return (bundlesCountAfterUpload == bundlesCountBeforeUpload + 1) && (uploadedBundle.getState() == Bundle.ACTIVE); }

Target:
private void uploadBundle(String moduleSource, String moduleId, File bundleFile, String startBundle, String bundleSymbolicName) throws IOException, InterruptedException { String uri = String.format("http://%s:%d/admin/api/bundles/upload/", HOST, PORT); HttpPost httpPost = new HttpPost(uri); MultipartEntityBuilder entity = MultipartEntityBuilder.create(); Charset chars = Charset.forName("UTF-8"); entity.setCharset(chars); entity.addTextBody("moduleSource", moduleSource, ContentType.MULTIPART_FORM_DATA); if (moduleSource.equals("Repository")) { entity.addTextBody("moduleId", moduleId, ContentType.MULTIPART_FORM_DATA); } else if (moduleSource.equals("File")) { assertNotNull(bundleFile); entity.addBinaryBody("bundleFile", bundleFile); } else { fail("Wrong module source."); } entity.addTextBody("startBundle", startBundle, ContentType.MULTIPART_FORM_DATA); httpPost.setEntity(entity.build()); int bundlesCountBeforeUpload = bundleContext.getBundles().length; HttpResponse response = getHttpClient().execute(httpPost); EntityUtils.consume(response.getEntity()); int bundlesCountAfterUpload = bundleContext.getBundles().length; assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.ORDINAL_200_OK); Bundle uploadedBundle = getBundleFromBundlesArray(bundleSymbolicName); assertNotNull(uploadedBundle); assertEquals(bundlesCountAfterUpload, bundlesCountBeforeUpload + 1); assertEquals(uploadedBundle.getState(), Bundle.ACTIVE); }
Source:
void isUserTakenToDiscussionsAfterClickOnViewAllSzl() { DiscussionsPage discussions = new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickOnViewAllLinkInDiscussions(); Assertion.assertTrue(discussions.isDiscussions()); }

Target:
void isUserTakenToDiscussionsAfterClickOnViewAllSzl() { DiscussionsPage discussions = new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickOnViewAllLinkInDiscussions(); Assertion.assertTrue(discussions.isDiscussionsPresent()); }
Source:
public int openInstallWizard(Collection<IInstallableUnit> initialSelections, InstallOperation operation, RemediationOperation remediationOperation, LoadMetadataRepositoryJob job) { if (operation == null) { InstallWizard wizard = new InstallWizard(this, operation, initialSelections, job); Shell[] shells = Display.getCurrent().getShells(); for (Shell shell : shells) { if (shell.getData() instanceof ProvisioningWizardDialog) { shell.forceActive(); return Window.OK; } } WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.create(); PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); return dialog.open(); } PreselectedIUInstallWizard wizard = new PreselectedIUInstallWizard(this, operation, initialSelections, job); wizard.setRemediationOperation(remediationOperation); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.create(); PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); return dialog.open(); }

Target:
public int openInstallWizard(Collection<IInstallableUnit> initialSelections, InstallOperation operation, RemediationOperation remediationOperation, LoadMetadataRepositoryJob job) { if (operation == null) { InstallWizard wizard = new InstallWizard(this, operation, initialSelections, job); Shell[] shells = Display.getCurrent().getShells(); for (Shell shell : shells) { if (shell.getData() instanceof ProvisioningWizardDialog) { shell.forceActive(); shell.setFocus(); return Window.OK; } } WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.create(); PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); return dialog.open(); } PreselectedIUInstallWizard wizard = new PreselectedIUInstallWizard(this, operation, initialSelections, job); wizard.setRemediationOperation(remediationOperation); WizardDialog dialog = new ProvisioningWizardDialog(ProvUI.getDefaultParentShell(), wizard); dialog.create(); PlatformUI.getWorkbench().getHelpSystem().setHelp(dialog.getShell(), IProvHelpContextIds.INSTALL_WIZARD); return dialog.open(); }
Source:
public static void createServiceActivatorDeployment(File destination, String objectName, Class mbeanClass) throws IOException { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class); archive.addClass(ServiceActivatorDeployment.class); archive.addClass(mbeanClass); archive.addAsServiceProvider(ServiceActivator.class, ServiceActivatorDeployment.class); StringBuilder sb = new StringBuilder(); sb.append(ServiceActivatorDeployment.MBEAN_CLASS_NAME); sb.append('='); sb.append(mbeanClass.getName()); sb.append("\n"); sb.append(ServiceActivatorDeployment.MBEAN_OBJECT_NAME); sb.append('='); sb.append(objectName); sb.append("\n"); archive.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new MBeanPermission("org.wildfly.test.jmx.Dynamic#-[" + objectName + "]", "registerMBean"), new MBeanPermission("org.wildfly.test.jmx.Dynamic#-[" + objectName + "]", "unregisterMBean"), new MBeanTrustPermission("register")), "permissions.xml"); archive.addAsManifestResource(new StringAsset("Dependencies: org.jboss.msc,org.jboss.as.jmx,org.jboss.as.server,org.jboss.as.controller\n"), "MANIFEST.MF"); archive.addAsResource(new StringAsset(sb.toString()), ServiceActivatorDeployment.PROPERTIES_RESOURCE); archive.as(ZipExporter.class).exportTo(destination); }

Target:
public static void createServiceActivatorDeployment(File destination, String objectName, Class mbeanClass) throws IOException { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class); archive.addClass(ServiceActivatorDeployment.class); archive.addClass(mbeanClass); archive.addAsServiceProvider(ServiceActivator.class, ServiceActivatorDeployment.class); StringBuilder sb = new StringBuilder(); sb.append(ServiceActivatorDeployment.MBEAN_CLASS_NAME); sb.append('='); sb.append(mbeanClass.getName()); sb.append("\n"); sb.append(ServiceActivatorDeployment.MBEAN_OBJECT_NAME); sb.append('='); sb.append(objectName); sb.append("\n"); archive.addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new MBeanPermission(mbeanClass + "#-[" + objectName + "]", "registerMBean"), new MBeanPermission(mbeanClass + "#-[" + objectName + "]", "unregisterMBean"), new MBeanTrustPermission("register")), "permissions.xml"); archive.addAsManifestResource(new StringAsset("Dependencies: org.jboss.msc,org.jboss.as.jmx,org.jboss.as.server,org.jboss.as.controller\n"), "MANIFEST.MF"); archive.addAsResource(new StringAsset(sb.toString()), ServiceActivatorDeployment.PROPERTIES_RESOURCE); archive.as(ZipExporter.class).exportTo(destination); }
Source:
public Class<? extends Body> getClassForType(Enum<BodyInternalTypes> modelType) { Class<? extends Body> returnType = null; BodyInternalTypes bodyType = BodyInternalTypes.valueOf(modelType.name()); switch (bodyType) { case SEMANTIC_LINK: returnType = SemanticLinkBody.class; break; case SEMANTIC_TAG: returnType = SemanticTagBody.class; break; case TAG: returnType = PlainTagBody.class; break; case TEXT: returnType = TextBody.class; break; case GEO_TAG: returnType = EdmPlaceBody.class; break; case GRAPH: returnType = RdfGraphBody.class; break; case SPECIFIC_RESOURCE: returnType = SpecificResourceBody.class; break; case FULL_TEXT_RESOURCE: returnType = FullTextResourceBody.class; break; case ENTITY: returnType = AgentBody.class; break; case VCARD_ADDRESS: returnType = VcardAddressBody.class; break; case LINK: throw new AnnotationInstantiationException("Bodies of type LINK must be empty!"); default: throw new AnnotationInstantiationException("unsupported (internal) body type: " + modelType); } return returnType; }

Target:
public Class<? extends Body> getClassForType(Enum<BodyInternalTypes> modelType) { Class<? extends Body> returnType = null; BodyInternalTypes bodyType = BodyInternalTypes.valueOf(modelType.name()); switch (bodyType) { case SEMANTIC_LINK: returnType = SemanticLinkBody.class; break; case SEMANTIC_TAG: returnType = SemanticTagBody.class; break; case TAG: returnType = PlainTagBody.class; break; case TEXT: returnType = TextBody.class; break; case GEO_TAG: returnType = EdmPlaceBody.class; break; case GRAPH: returnType = RdfGraphBody.class; break; case SPECIFIC_RESOURCE: returnType = SpecificResourceBody.class; break; case FULL_TEXT_RESOURCE: returnType = FullTextResourceBody.class; break; case AGENT: returnType = EdmAgentBody.class; break; case VCARD_ADDRESS: returnType = VcardAddressBody.class; break; case LINK: throw new AnnotationInstantiationException("Bodies of type LINK must be empty!"); default: throw new AnnotationInstantiationException("unsupported (internal) body type: " + modelType); } return returnType; }
Source:
public static void generateTrace() { List<String> processes = new ArrayList<String>(); for (String s : sfProcesses) { processes.add(s); } final int cpus = 25; GenerateKernelTrace gt = new GenerateKernelTrace(processes, 2l * Integer.MAX_VALUE - 100, 500000, cpus); gt.writeTrace(PATH); }

Target:
public static void generateTrace() { final int cpus = 25; GenerateKernelTrace gt = new GenerateKernelTrace(2l * Integer.MAX_VALUE - 100, 500000, cpus); gt.writeTrace(PATH); }
Source:
static void internalBeforeClassSetup(Map<String, String> overrides, Class clazz) throws Exception { HiveConf conf = new HiveConf(clazz); conf.set("dfs.client.use.datanode.hostname", "true"); conf.set("hadoop.proxyuser." + Utils.getUGI().getShortUserName() + ".hosts", "*"); MiniDFSCluster miniDFSCluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).format(true).build(); HashMap<String, String> acidEnableConf = new HashMap<String, String>() {{ put("fs.defaultFS", miniDFSCluster.getFileSystem().getUri().toString()); put("hive.support.concurrency", "true"); put("hive.txn.manager", "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager"); put("hive.metastore.client.capability.check", "false"); put("hive.repl.bootstrap.dump.open.txn.timeout", "1s"); put("hive.exec.dynamic.partition.mode", "nonstrict"); put("hive.strict.checks.bucketing", "false"); put("hive.mapred.mode", "nonstrict"); put("mapred.input.dir.recursive", "true"); put("hive.metastore.disallow.incompatible.col.type.changes", "false"); put("hive.in.repl.test", "true"); }}; acidEnableConf.putAll(overrides); primary = new WarehouseInstance(LOG, miniDFSCluster, acidEnableConf); replica = new WarehouseInstance(LOG, miniDFSCluster, acidEnableConf); }

Target:
static void internalBeforeClassSetup(Map<String, String> overrides, Class clazz) throws Exception { HiveConf conf = new HiveConf(clazz); conf.set("dfs.client.use.datanode.hostname", "true"); conf.set("hadoop.proxyuser." + Utils.getUGI().getShortUserName() + ".hosts", "*"); MiniDFSCluster miniDFSCluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).format(true).build(); Map<String, String> acidEnableConf = new HashMap<String, String>() {{ put("fs.defaultFS", miniDFSCluster.getFileSystem().getUri().toString()); put("hive.support.concurrency", "true"); put("hive.txn.manager", "org.apache.hadoop.hive.ql.lockmgr.DbTxnManager"); put("hive.metastore.client.capability.check", "false"); put("hive.repl.bootstrap.dump.open.txn.timeout", "1s"); put("hive.exec.dynamic.partition.mode", "nonstrict"); put("hive.strict.checks.bucketing", "false"); put("hive.mapred.mode", "nonstrict"); put("mapred.input.dir.recursive", "true"); put("hive.metastore.disallow.incompatible.col.type.changes", "false"); put("hive.strict.managed.tables", "true"); put("hive.in.repl.test", "true"); }}; acidEnableConf.putAll(overrides); primary = new WarehouseInstance(LOG, miniDFSCluster, acidEnableConf); replica = new WarehouseInstance(LOG, miniDFSCluster, acidEnableConf); }
Source:
BlockedThreadChecker(long interval, long maxEventLoopExecTime, long maxWorkerExecTime, long warningExceptionTime) { timer = new Timer("vertx-blocked-thread-checker", true); timer.schedule(new TimerTask() { @Override public void run() { long now = System.nanoTime(); for (VertxThread thread: threads.keySet()) { long execStart = thread.startTime(); long dur = now - execStart; if (execStart != 0 && dur > (thread.isWorker() ? maxWorkerExecTime : maxEventLoopExecTime)) { long timeLimit = thread.isWorker() ? maxWorkerExecTime : maxEventLoopExecTime; final String message = "Thread " + thread + " has been blocked for " + (dur / 1000000) + " ms, time limit is " + (timeLimit / 1000000); if (dur <= warningExceptionTime) { log.warn(message); } else { VertxException stackTrace = new VertxException("Thread blocked"); stackTrace.setStackTrace(thread.getStackTrace()); log.warn(message, stackTrace); } } } } }, interval, interval); }

Target:
BlockedThreadChecker(long interval, long maxEventLoopExecTime, long maxWorkerExecTime, long warningExceptionTime) { timer = new Timer("vertx-blocked-thread-checker", true); timer.schedule(new TimerTask() { @Override public void run() { long now = System.nanoTime(); for (VertxThread thread: threads.keySet()) { long execStart = thread.startTime(); long dur = now - execStart; final long timeLimit = thread.isWorker() ? maxWorkerExecTime : maxEventLoopExecTime; if (execStart != 0 && dur > timeLimit) { final String message = "Thread " + thread + " has been blocked for " + (dur / 1000000) + " ms, time limit is " + (timeLimit / 1000000); if (dur <= warningExceptionTime) { log.warn(message); } else { VertxException stackTrace = new VertxException("Thread blocked"); stackTrace.setStackTrace(thread.getStackTrace()); log.warn(message, stackTrace); } } } } }, interval, interval); }
Source:
public void testBadNumberOfArguments() throws URISyntaxException, HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedDataUDF geocodedDataUDF = new GeocodedDataUDF( TestGeocodedDataUDF.class.getResource(defaultDatabaseFile).getFile()); try { geocodedDataUDF.initialize(initArguments); fail("UDFArgumentLengthException was not thrown for invalid number of arguments"); } catch (UDFArgumentLengthException lenEx) { } }

Target:
public void testBadNumberOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedDataUDF geocodedDataUDF = new GeocodedDataUDF(); geocodedDataUDF.initialize(initArguments); }
Source:
public void onUpdate(CounterEvent event) { try { queue.put(event); log.tracef("[%s] add event %s", name, event); } catch (InterruptedException e) { log.errorf(e, "[%s] interrupted while adding event %s", name, event); } }

Target:
public void onUpdate(CounterEvent event) { try { queue.put(event); if (trace) { log.tracef("[%s] add event %s", name, event); } } catch (InterruptedException e) { log.errorf(e, "[%s] interrupted while adding event %s", name, event); } }
Source:
protected static boolean isSerializableAndValueBased(Type type) { JavaType javaType = (JavaType)type; if (javaType.isParameterized()) { ParametrizedTypeJavaType parameterizedType = (ParametrizedTypeJavaType)javaType; return isSubtypeOfCollectionApi(parameterizedType) && parameterizedType.typeParameters().stream() .anyMatch(t -> isSerializableAndValueBased(parameterizedType.substitution(t))); } else { return ValueBasedUtils.isValueBased(javaType); } }

Target:
private static boolean isSerializableAndValueBased(Type type) { JavaType javaType = (JavaType) type; if (javaType.isParameterized()) { ParametrizedTypeJavaType parameterizedType = (ParametrizedTypeJavaType) javaType; return isSubtypeOfCollectionApi(parameterizedType) && parameterizedType.typeParameters().stream() .anyMatch(t -> isSerializableAndValueBased(parameterizedType.substitution(t))); } return ValueBasedUtils.isValueBased(javaType); }
Source:
private CloudVmTypes getCloudVmTypes(CloudCredential cloudCredential, Region region, Map<String, String> filters, Predicate<VmType> enabledInstanceTypeFilter) { CloudRegions regions = regions(cloudCredential, region, filters); Map<String, Set<VmType>> cloudVmResponses = new HashMap<>(); Map<String, VmType> defaultCloudVmResponses = new HashMap<>(); List<AvailabilityZone> availabilityZones = regions.getCloudRegions().get(region); if (availabilityZones != null && !availabilityZones.isEmpty()) { for (AvailabilityZone availabilityZone : availabilityZones) { Set<VmType> types = vmTypes.get(region).stream() .filter(enabledInstanceTypeFilter) .collect(Collectors.toSet()); cloudVmResponses.put(availabilityZone.value(), types); defaultCloudVmResponses.put(availabilityZone.value(), defaultVmTypes.get(region)); } } return new CloudVmTypes(cloudVmResponses, defaultCloudVmResponses); }

Target:
private CloudVmTypes getCloudVmTypes(CloudCredential cloudCredential, Region region, Map<String, String> filters, Predicate<VmType> enabledInstanceTypeFilter) { CloudRegions regions = regions(cloudCredential, region, filters); Map<String, Set<VmType>> cloudVmResponses = new HashMap<>(); Map<String, VmType> defaultCloudVmResponses = new HashMap<>(); List<AvailabilityZone> availabilityZones = regions.getCloudRegions().get(region); if (availabilityZones != null && !availabilityZones.isEmpty()) { for (AvailabilityZone availabilityZone : availabilityZones) { Set<VmType> types = vmTypes.get(region).stream() .filter(enabledInstanceTypeFilter) .collect(Collectors.toSet()); cloudVmResponses.put(availabilityZone.value(), types); defaultCloudVmResponses.put(availabilityZone.value(), defaultVmTypes.get(region)); } } else { LOGGER.info("Availability zones is null or empty in {}", region.getRegionName()); } return new CloudVmTypes(cloudVmResponses, defaultCloudVmResponses); }
Source:
public void close() { listener = null; if (null != curatorFramework && !curatorFramework.isZk34CompatibilityMode()) { curatorFramework.watches().remove(this); } }

Target:
public void close() { if (listener != null && !curatorFramework.isZk34CompatibilityMode()) { try { curatorFramework.watches().remove(this).forPath(key); } catch (final Exception ex) { } } listener = null; }
Source:
private String copyFileToHDFS(FileSystem hdfs, String smbSourceFile, Path dest, NtlmPasswordAuthentication auth) throws IOException { SmbFile smbFile = new SmbFile(smbSourceFile, auth); String name = smbFile.getName(); Path nDest = new Path(dest, name); LOG.debug("Thread is accessing source file {}, dest file {}", Thread.currentThread().getName(), smbFile.getName(), nDest.getName()); if (hdfs.exists(nDest)) { LOG.info("File already exists on HDFS, Skipping", nDest.getName()); return name; } LOG.info("Copying file to {}", smbSourceFile, nDest.toString()); try (InputStream in = smbFile.getInputStream(); BufferedOutputStream out = new BufferedOutputStream(hdfs.create(nDest))) { ByteStreams.copy(in, out); } catch (IOException e) { LOG.info("Exception in getting input stream for file {}", name, e); } return name; }

Target:
private String copyFileToHDFS(FileSystem hdfs, String smbSourceFile, Path dest, NtlmPasswordAuthentication auth) throws IOException { SmbFile smbFile = new SmbFile(smbSourceFile, auth); String name = smbFile.getName(); Path destFile = new Path(dest, name); LOG.debug("Thread is copying source file {}, dest file {}", Thread.currentThread().getName(), smbFile.getName(), destFile.getName()); if (hdfs.exists(destFile) && !config.overwrite) { LOG.info("File already exists on HDFS, Skipping", destFile.getName()); return null; } LOG.info("Copying file to {}", smbSourceFile, destFile.toString()); try (InputStream in = smbFile.getInputStream(); BufferedOutputStream out = new BufferedOutputStream(hdfs.create(destFile), config.bufferSize)) { ByteStreams.copy(in, out); } catch (IOException e) { LOG.warn("Exception in copying the file {}", name, e); } return name; }