auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testWhenAnyComplete() throws Exception { assertGetUncheckedListenable(future -> getFutureValue(MoreFutures.whenAnyComplete(ImmutableList.of(SettableFuture.create(), future, SettableFuture.create())))); assertFailure(() -> MoreFutures.whenAnyComplete(null), e -> assertInstanceOf(e, NullPointerException.class)); assertFailure(() -> MoreFutures.whenAnyComplete(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); assertEquals(tryGetFutureValue(MoreFutures.whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS), Optional.empty()); }

Target:
public void testWhenAnyComplete() throws Exception { assertGetUncheckedListenable(future -> getFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), future, SettableFuture.create())))); assertFailure(() -> whenAnyComplete(null), e -> assertInstanceOf(e, NullPointerException.class)); assertFailure(() -> whenAnyComplete(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); assertEquals( tryGetFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS), Optional.empty()); }
Source:
protected void executeQueryCommand() { GlusterVolumeEntity volumeCheck = glusterVolumeDao.getByName(getParameters().getClusterId(), getGlusterVolumeName(getParameters().getVolumeId())); boolean nfs = volumeCheck.isNfsEnabled() && getParameters().isNfs(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), nfs)); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (!nfs) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }

Target:
protected void executeQueryCommand() { GlusterVolumeEntity volumeCheck = glusterVolumeDao.getById(getParameters().getVolumeId()); boolean nfs = volumeCheck.isNfsEnabled() && getParameters().isNfs(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), nfs)); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (!nfs) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }
Source:
public Mono<Void> uploadFromFile(String uploadFilePath, FileRangeWriteType type) { AsynchronousFileChannel channel = channelSetup(uploadFilePath); return Flux.fromIterable(sliceFile(uploadFilePath)) .flatMap(chunk -> { return upload(FluxUtil.byteBufStreamFromFile(channel, chunk.start(), chunk.end() - chunk.start() + 1), chunk.end() - chunk.start() + 1, chunk.start(), type) .timeout(Duration.ofSeconds(300)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException); }) .then() .doOnTerminate(() -> channelCleanUp(channel)); }

Target:
public Mono<Void> uploadFromFile(String uploadFilePath, FileRangeWriteType type) { AsynchronousFileChannel channel = channelSetup(uploadFilePath); return Flux.fromIterable(sliceFile(uploadFilePath)) .flatMap(chunk -> { return upload(FluxUtil.byteBufStreamFromFile(channel, chunk.start(), chunk.end() - chunk.start() + 1), chunk.end() - chunk.start() + 1, chunk.start(), type) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException); }) .then() .doOnTerminate(() -> channelCleanUp(channel)); }
Source:
public static synchronized void deleteDatabase(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { StringBuffer dbName = new StringBuffer(dbNamePrefix); if (account != null) { final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); final DBOpenHelper helper = openHelpers.get(fullDBName); if (helper != null) { helper.close(); openHelpers.remove(fullDBName); } ctx.deleteDatabase(fullDBName); if (account != null && TextUtils.isEmpty(communityId)) { StringBuffer communityDBNamePrefix = new StringBuffer(dbNamePrefix); String accountSuffix = account.getUserLevelFilenameSuffix(); communityDBNamePrefix.append(accountSuffix); final String dbPath = ctx.getApplicationInfo().dataDir + "/databases"; final File dir = new File(dbPath); if (dir != null) { final SmartStoreFileFilter fileFilter = new SmartStoreFileFilter(communityDBNamePrefix.toString()); final File[] fileList = dir.listFiles(); if (fileList != null) { for (final File file : fileList) { if (file != null && fileFilter.accept(dir, file.getName())) { file.delete(); openHelpers.remove(file.getName()); } } } } } }

Target:
public static synchronized void deleteDatabase(Context ctx, String dbNamePrefix, UserAccount account, String communityId) { try { StringBuffer dbName = new StringBuffer(dbNamePrefix); if (account != null) { final String accountSuffix = account.getCommunityLevelFilenameSuffix(communityId); dbName.append(accountSuffix); } dbName.append(DB_NAME_SUFFIX); final String fullDBName = dbName.toString(); final DBOpenHelper helper = openHelpers.get(fullDBName); if (helper != null) { helper.close(); openHelpers.remove(fullDBName); } ctx.deleteDatabase(fullDBName); if (account != null && TextUtils.isEmpty(communityId)) { StringBuffer communityDBNamePrefix = new StringBuffer(dbNamePrefix); String accountSuffix = account.getUserLevelFilenameSuffix(); communityDBNamePrefix.append(accountSuffix); final String dbPath = ctx.getApplicationInfo().dataDir + "/databases"; final File dir = new File(dbPath); if (dir != null) { final SmartStoreFileFilter fileFilter = new SmartStoreFileFilter(communityDBNamePrefix.toString()); final File[] fileList = dir.listFiles(); if (fileList != null) { for (final File file : fileList) { if (file != null && fileFilter.accept(dir, file.getName())) { file.delete(); openHelpers.remove(file.getName()); } } } } } } catch (Exception e) { Log.e("DBOpenHelper:deleteDatabase", "Exception occurred while attempting to delete database.", e); } }
Source:
private void populateCube(Cube cube) { int cubeX = cube.getX(); int cubeY = cube.getY(); int cubeZ = cube.getZ(); cubeGen.getPopulationRequirement(cube).forEachPoint((x, y, z) -> { Cube popcube = getCube(x + cubeX, y + cubeY, z + cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } }); if (CubicChunks.Config.BoolOptions.USE_VANILLA_CHUNK_WORLD_GENERATORS.getValue()) { for (int y = 15; y >= 0; y--) { Cube popcube = getCube(cubeX, y + cubeY, cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } } GameRegistry.generateWorld(cubeX, cubeZ, world, chunkGenerator, this); } cube.setFullyPopulated(true); }

Target:
private void populateCube(Cube cube) { int cubeX = cube.getX(); int cubeY = cube.getY(); int cubeZ = cube.getZ(); cubeGen.getPopulationRequirement(cube).forEachPoint((x, y, z) -> { Cube popcube = getCube(x + cubeX, y + cubeY, z + cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } }); if (!(cubeGen instanceof VanillaCompatibilityGenerator) && CubicChunks.Config.BoolOptions.USE_VANILLA_CHUNK_WORLD_GENERATORS.getValue()) { for (int x = 0; x < 2; x++) { for (int z = 0; z < 2; z++) { for (int y = 15; y >= 0; y--) { Cube popcube = getCube(x + cubeX, y + cubeY, z + cubeZ); if (!popcube.isPopulated()) { cubeGen.populate(popcube); popcube.setPopulated(true); } } } } GameRegistry.generateWorld(cubeX, cubeZ, world, chunkGenerator, this); } cube.setFullyPopulated(true); }
Source:
private IStatus validateMappings(ResourceMapping[] mappings) { for (ResourceMapping mapping : mappings) { if (mapping instanceof EMFResourceMapping && mapping.getModelObject() instanceof StorageTraversal) { final StorageTraversal traversal = (StorageTraversal)mapping.getModelObject(); if (traversal.getDiagnostic().getSeverity() != Diagnostic.OK) { return BasicDiagnostic.toIStatus(traversal.getDiagnostic()); } } else { return new Status(IStatus.ERROR, EMFCompareIDEUIPlugin.PLUGIN_ID, EMFCompareIDEUIMessages .getString("EMFResourceMappingMerger.mergeFailedInvalidMapping")); } } return Status.OK_STATUS; }

Target:
private IStatus validateMappings(ResourceMapping[] mappings) { for (ResourceMapping mapping : mappings) { if (mapping instanceof EMFResourceMapping && mapping.getModelObject() instanceof StorageTraversal) { final StorageTraversal traversal = (StorageTraversal)mapping.getModelObject(); if (traversal.getDiagnostic().getSeverity() >= Diagnostic.WARNING) { return BasicDiagnostic.toIStatus(traversal.getDiagnostic()); } } else { return new Status(IStatus.ERROR, EMFCompareIDEUIPlugin.PLUGIN_ID, EMFCompareIDEUIMessages .getString("EMFResourceMappingMerger.mergeFailedInvalidMapping")); } } return Status.OK_STATUS; }
Source:
private HashMap<ArchitectureType, HashMap<Version, Boolean>> getMap(ArchCapabilitiesVerb archCapabilitiesVerb) { HashMap<ArchitectureType, HashMap<Version, Boolean>> supportMap = new HashMap<ArchitectureType, HashMap<Version, Boolean>>(); for (ArchitectureType arch : ArchitectureType.values()) { HashMap<Version, Boolean> archMap = new HashMap<Version, Boolean>(); for (Version version : Version.ALL) { boolean isSupported = isSupported(archCapabilitiesVerb, arch, version); archMap.put(version, isSupported); } supportMap.put(arch, archMap); } return supportMap; }

Target:
private Map<ArchitectureType, Map<Version, Boolean>> getMap(ArchCapabilitiesVerb archCapabilitiesVerb) { if (verbMap.containsKey(archCapabilitiesVerb)) { return verbMap.get(archCapabilitiesVerb); } else { Map<ArchitectureType, Map<Version, Boolean>> supportMap = new HashMap<ArchitectureType, Map<Version, Boolean>>(); for (ArchitectureType arch : ArchitectureType.values()) { Map<Version, Boolean> archMap = new HashMap<Version, Boolean>(); for (Version version : Version.ALL) { boolean isSupported = isSupported(archCapabilitiesVerb, arch, version); archMap.put(version, isSupported); } supportMap.put(arch, archMap); } verbMap.put(archCapabilitiesVerb, supportMap); return supportMap; } }
Source:
public Object call() throws Exception { ObjectReader or = block.templateReader.newReader(); try { for (;;) { Slice s; synchronized (this) { if (slices.isEmpty()) break; s = slices.removeFirst(); } doSlice(or, s); } for (Slice s = block.stealWork(); s != null; s = block.stealWork()) doSlice(or, s); } finally { or.release(); block.pm.endWorker(); } return null; }

Target:
public Object call() throws Exception { ObjectReader or = block.templateReader.newReader(); try { for (;;) { Slice s; synchronized (this) { if (slices.isEmpty()) break; s = slices.removeFirst(); } runWorker(or, s); } for (Slice s = block.stealWork(); s != null; s = block.stealWork()) runWorker(or, s); } finally { or.release(); block.pm.endWorker(); } return null; }
Source:
static Status run(List<String> command, File workingDirectory, long timeout) throws ProcessException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(workingDirectory); TimeLimitProcess p; try { p = new TimeLimitProcess(processBuilder.start(), timeout, true); } catch (IOException e) { throw new ProcessException("Exception starting process", e); } int exitValue; try { exitValue = p.waitFor(); } catch (InterruptedException e) { throw new ProcessException("Exception running process", e); } List<String> standardOutputLines; try { standardOutputLines = StreamUtils.captureLinesFromStream(p.getInputStream()); } catch (IOException e) { throw new ProcessException("Exception getting process stream output", e); } List<String> errorOutputLines; try { errorOutputLines = StreamUtils.captureLinesFromStream(p.getErrorStream()); } catch (IOException e) { throw new ProcessException("Error getting process error output", e); } if (p.timed_out()) { for (String line : standardOutputLines) { System.out.println(line); } assert !p.timed_out() : "Process timed out after " + p.timeout_msecs() + " msecs"; } return new Status(command, exitValue, standardOutputLines, errorOutputLines); }

Target:
static Status run(List<String> command, File workingDirectory, long timeout) throws CommandException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(workingDirectory); TimeLimitProcess p; try { p = new TimeLimitProcess(processBuilder.start(), timeout, true); } catch (IOException e) { throw new CommandException("Exception starting process", e); } int exitValue = -1; try { exitValue = p.waitFor(); } catch (InterruptedException e) { } List<String> standardOutputLines; try { standardOutputLines = UtilMDE.streamLines(p.getInputStream()); } catch (IOException e) { throw new CommandException("Exception getting process standard output", e); } List<String> errorOutputLines; try { errorOutputLines = UtilMDE.streamLines(p.getErrorStream()); } catch (IOException e) { throw new CommandException("Exception getting process error output", e); } return new Status(command, exitValue, p.timed_out(), standardOutputLines, errorOutputLines); }
Source:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(invoker, args); } String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { if ("toString".equals(methodName)) { return invoker.toString(); } else if ("$destroy".equals(methodName)) { invoker.destroy(); return null; } else if ("hashCode".equals(methodName)) { return invoker.hashCode(); } } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return invoker.equals(args[0]); } RpcInvocation rpcInvocation = new RpcInvocation(method, invoker.getInterface().getName(), args); String serviceKey = invoker.getUrl().getServiceKey(); if (serviceKey != null) { rpcInvocation.setTargetServiceUniqueName(serviceKey); ConsumerModel consumerModel = ApplicationModel.getConsumerModel(serviceKey); rpcInvocation.put("consumerModel", consumerModel); } return invoker.invoke(rpcInvocation).recreate(); }

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(invoker, args); } String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { if ("toString".equals(methodName)) { return invoker.toString(); } else if ("$destroy".equals(methodName)) { invoker.destroy(); return null; } else if ("hashCode".equals(methodName)) { return invoker.hashCode(); } } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return invoker.equals(args[0]); } RpcInvocation rpcInvocation = new RpcInvocation(method, invoker.getInterface().getName(), args); String serviceKey = invoker.getUrl().getServiceKey(); rpcInvocation.setTargetServiceUniqueName(serviceKey); if (consumerModel != null) { rpcInvocation.put(Constants.CONSUMER_MODEL, consumerModel); rpcInvocation.put(Constants.METHOD_MODEL, consumerModel.getMethodModel(method)); } return invoker.invoke(rpcInvocation).recreate(); }
Source:
public void testFilenameBatchedUnique() throws Exception { ExportToFileClient client = new ExportToFileClient(); Properties props = new Properties(); props.put("nonce", Long.toString(System.currentTimeMillis())); props.put("type", "csv"); props.put("outdir", m_dir); props.put("period", "1"); props.put("with-schema", "true"); props.put("batched", "true"); props.put("uniquenames", "true"); client.configure(props); final AdvertisedDataSource source = constructTestSource(false, 0); final ExportToFileClient.ExportToFileDecoder decoder = client.constructExportDecoder(source); long l = System.currentTimeMillis(); vtable.addRow(l, l, l, 0, l, l, (byte) 1, (short) 2, 3, 4, 5.5, 6, "xx", new BigDecimal(88), GEOG_POINT, GEOG); vtable.advanceRow(); byte[] rowBytes = ExportEncoder.encodeRow(vtable, "mytable", 0, 1L); ExportRow row = ExportRow.decodeRow(null, 0, 0L, rowBytes); decoder.onBlockStart(row); decoder.processRow(row); decoder.onBlockCompletion(row); boolean validName = true; final File dir = new File(m_dir); final File[] subdirs = dir.listFiles(); List<File> remainingFiles = new ArrayList<>(); if (subdirs != null) { for (File file : subdirs) { if (file.isDirectory()) { remainingFiles.addAll(Arrays.asList(file.listFiles())); } else if (!file.getName().matches("\\d\\-mytable\\-\\(\\d\\).*\\.[a-z]{3,4}")) { validName = false; break; } } for (File file : remainingFiles) { if (!file.getName().matches("\\d\\-mytable\\-\\(\\d\\).*\\.[a-z]{3,4}")) { validName = false; break; } } } assertTrue(validName); }

Target:
public void testFilenameBatchedUnique() throws Exception { ExportToFileClient client = new ExportToFileClient(); Properties props = new Properties(); props.put("nonce", Long.toString(System.currentTimeMillis())); props.put("type", "csv"); props.put("outdir", m_dir); props.put("period", "1"); props.put("with-schema", "true"); props.put("batched", "true"); props.put("uniquenames", "true"); client.configure(props); final AdvertisedDataSource source = constructTestSource(false, 0); final ExportToFileClient.ExportToFileDecoder decoder = client.constructExportDecoder(source); long l = System.currentTimeMillis(); vtable.addRow(l, l, l, 0, l, l, (byte) 1, (short) 2, 3, 4, 5.5, 6, "xx", new BigDecimal(88), GEOG_POINT, GEOG); vtable.advanceRow(); byte[] rowBytes = ExportEncoder.encodeRow(vtable, "mytable", 0, 1L); ExportRow row = ExportRow.decodeRow(null, 0, 0L, rowBytes); decoder.onBlockStart(row); decoder.processRow(row); decoder.onBlockCompletion(row); boolean validName = true; final File dir = new File(m_dir); final File[] subdirs = dir.listFiles(); List<File> allFiles = new ArrayList<>(); if (subdirs != null) { for (File file : subdirs) { if (file.isDirectory()) { allFiles.addAll(Arrays.asList(file.listFiles())); } else { allFiles.add(file); } } for (File file : allFiles) { if (!(file.getName().matches("\\d\\-mytable\\-\\(\\d\\)\\.[a-z]{3}")||file.getName().matches("\\d\\-mytable\\-\\(\\d\\)-schema\\.json"))) { validName = false; break; } } } assertTrue(validName); }
Source:
private Object transform(ConfigKey<?> key, Object value) { if (value instanceof CharSequence) { String raw = value.toString(); if (raw.startsWith(EXTERNAL_CONFIG_PREFIX)) { CampYamlParser parser = mgmt.getConfig().getConfig(CampYamlParser.YAML_PARSER_KEY); if (parser == null) { LOG.debug("Not transforming external-config {}, as no camp-yaml parser available", key); return value; } return parser.parse(raw); } } return value; }

Target:
private Object transform(ConfigKey<?> key, Object value) { if (value instanceof CharSequence) { String raw = value.toString(); if (raw.startsWith(BROOKLYN_YAML_PREFIX)) { CampYamlParser parser = mgmt.getConfig().getConfig(CampYamlParser.YAML_PARSER_KEY); if (parser == null) { LOG.debug("Not transforming external-config {}, as no camp-yaml parser available", key); return value; } return parser.parse(raw); } } return value; }
Source:
public FilesWatcher() { watchers = new ConcurrentHashMap<>(); executorPollTime = getPollTimeOrDefault(); init(); }

Target:
public FilesWatcher() { executorPollTime = getPollTimeOrDefault(); init(); }
Source:
static String getVarName(Path path) { return "Var_" + Hashing.sha256() .hashString(MorePaths.pathWithUnixSeparators(path.getFileName()), Charsets.UTF_8) .toString() .substring(0, 10); }

Target:
static String getVarName(Path path) { return "Var_" + Hashing.sha256().hashString(path.getFileName().toString(), Charsets.UTF_8); }
Source:
public void testGetDiagram(){ final CanvasHandler handler = mock(CanvasHandler.class); doNothing().when(presenter).refreshTreeView(); final Diagram expectedDiagram = mock(Diagram.class); doReturn(expectedDiagram).when(handler).getDiagram(); presenter.setHandler(handler); final Diagram actual = presenter.getDiagram(); assertEquals(expectedDiagram, actual); }

Target:
public void testGetDiagram() { final CanvasHandler handler = mock(CanvasHandler.class); final Diagram expectedDiagram = mock(Diagram.class); doNothing().when(presenter).refreshTreeView(); doReturn(expectedDiagram).when(handler).getDiagram(); presenter.setHandler(handler); final Diagram actual = presenter.getDiagram(); assertEquals(expectedDiagram, actual); }
Source:
public void run() { consumerThreadsMap = new HashMap<String, List<FetcherRunnable>>(); topicToConsumerMap = new HashMap<String, String>(); queues = new HashMap<String, BlockingQueue<FetchedDataChunk>>(); allPartitions = new ConcurrentHashMap<String, Map<String, PartitionTopicInfo>>(); Properties prop = new Properties(); try { prop.load(new FileReader(new File("consumer.properties"))); } catch (IOException e) { LOG.error("Oops, got an exception, thread start fail.", e); return; } if (Consumer.config.isAutoCommit()) { int autoCommitIntervalMs = Consumer.config.getAutoCommitIntervalMs(); LOG.info("starting auto committer every " + autoCommitIntervalMs + " ms"); scheduler.scheduleWithRate(new AutoCommitTask(), autoCommitIntervalMs, autoCommitIntervalMs); } try { String serverhost = prop.getProperty("supervisor.host"); int serverport = Integer.parseInt(prop.getProperty("supervisor.port")); init(serverhost, serverport); } catch (IOException e) { LOG.error("Oops, got an exception, thread start fail.", e); return; } super.loop(); }

Target:
public void run() { consumerThreadsMap = new HashMap<String, List<FetcherRunnable>>(); queues = new ConcurrentHashMap<String, BlockingQueue<FetchedDataChunk>>(); allPartitions = new HashMap<String, List<PartitionTopicInfo>>(); if (Consumer.config.isAutoCommit()) { int autoCommitIntervalMs = Consumer.config.getAutoCommitIntervalMs(); LOG.info("starting auto committer every " + autoCommitIntervalMs + " ms"); scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); scheduler.scheduleAtFixedRate(new AutoCommitTask(), autoCommitIntervalMs, autoCommitIntervalMs, TimeUnit.MILLISECONDS); } try { String supervisorHost = Consumer.config.getSupervisorHost(); int supervisorPort = Consumer.config.getSupervisorPort(); init(supervisorHost, supervisorPort); } catch (IOException e) { LOG.error("Oops, got an exception, thread start fail.", e); return; } super.loop(); }
Source:
public <T> Promise<Response<T>> sendRequest(final Request<T> request, final RequestContext requestContext) { final SettablePromise<Response<T>> promise = Promises.settable(); try { _client.sendRequest(request, requestContext, new PromiseCallbackAdapter<T>(promise)); } catch (Exception e) { promise.fail(e); } return promise; }

Target:
public <T> Promise<Response<T>> sendRequest(final Request<T> request, final RequestContext requestContext) { final SettablePromise<Response<T>> promise = Promises.settable(); try { _client.sendRequest(request, requestContext, new PromiseCallbackAdapter<T>(promise)); } catch (Throwable e) { promise.fail(e); } return promise; }
Source:
public LeafConditionSettingIterator(LeafCondition condition, EObject domainModel, boolean includeNonValueRelatedSettings) { this.condition = condition; dmrs = new LinkedHashSet<VDomainModelReference>(); this.includeNonValueRelatedSettings = includeNonValueRelatedSettings; iteratorToCurrentChildrenMap = new LinkedHashMap<Iterator<Setting>, Iterator<EObject>>(); expectedStackSize = 1; if (condition.getValueDomainModelReference() != null) { expectedStackSize = expectedStackSize + 1; } else { } iterators = new Stack<Iterator<Setting>>(); final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); final ServiceReference<EMFFormsDatabindingEMF> serviceReference = bundleContext .getServiceReference(EMFFormsDatabindingEMF.class); final EMFFormsDatabindingEMF databinding = bundleContext.getService(serviceReference); try { final Setting setting = databinding.getSetting(condition.getDomainModelReference(), domainModel); final Iterator<Setting> iterator = Collections.singleton(setting).iterator(); iterators.push(iterator); } catch (final DatabindingFailedException ex) { final ServiceReference<ReportService> reportReference = bundleContext .getServiceReference(ReportService.class); final ReportService reportService = bundleContext.getService(reportReference); reportService.report(new AbstractReport(ex, String.format("Could not get the setting iterator for DMR: %s and domain model: %s", condition.getDomainModelReference(), domainModel))); bundleContext.ungetService(reportReference); } bundleContext.ungetService(serviceReference); organizeStack(); }

Target:
public LeafConditionSettingIterator(LeafCondition condition, EObject domainModel, boolean includeNonValueRelatedSettings) { isDisposed = false; this.condition = condition; dmrs = new LinkedHashSet<VDomainModelReference>(); this.includeNonValueRelatedSettings = includeNonValueRelatedSettings; iteratorToCurrentChildrenMap = new LinkedHashMap<Iterator<Setting>, Iterator<EObject>>(); expectedStackSize = 1; if (condition.getValueDomainModelReference() != null) { expectedStackSize = expectedStackSize + 1; } iterators = new Stack<Iterator<Setting>>(); try { final Setting setting = getDatabinding().getSetting(condition.getDomainModelReference(), domainModel); final Iterator<Setting> iterator = Collections.singleton(setting).iterator(); iterators.push(iterator); } catch (final DatabindingFailedException ex) { getReportService().report(new AbstractReport(ex, String.format("Could not get the setting iterator for DMR: %s and domain model: %s", condition.getDomainModelReference(), domainModel))); } organizeStack(); }
Source:
public Statement apply(TemplateOptions options) { List<Statement> bootstrap = newArrayList(); if (options.getRunScript() != null) { bootstrap.add(options.getRunScript()); } if (options.getPrivateKey() != null) { bootstrap.add(new InstallRSAPrivateKey(options.getPrivateKey())); } if (bootstrap.size() >= 1) { if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) { options.nameTask("bootstrap"); } return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap); } return null; }

Target:
public Statement apply(TemplateOptions options) { ImmutableList.Builder<Statement> builder = ImmutableList.builder(); if (options.getRunScript() != null) { builder.add(options.getRunScript()); } if (options.getPrivateKey() != null) { builder.add(new InstallRSAPrivateKey(options.getPrivateKey())); } ImmutableList<Statement> bootstrap = builder.build(); if (!bootstrap.isEmpty()) { if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) { options.nameTask("bootstrap"); } return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap); } return null; }
Source:
public void testAddCollectionToAdminUnit() throws UnsupportedOperationException, Exception { PID parentPid = makePid(); AdminUnit parent = repositoryObjectFactory.createAdminUnit(parentPid, null); contentRoot.addMember(parent); treeIndexer.indexAll(baseAddress); String label = "collection_label"; String patronOnly = "false"; MvcResult result = mvc.perform(post("/edit/create/collection/" + parentPid.getId()) .param("label", label) .param("patronOnly", patronOnly)) .andExpect(status().is2xxSuccessful()) .andReturn(); treeIndexer.indexAll(baseAddress); assertChildContainerAdded(parent, label, CollectionObject.class); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(parentPid.getUUID(), respMap.get("pid")); assertEquals("create", respMap.get("action")); }

Target:
public void testAddCollectionToAdminUnit() throws UnsupportedOperationException, Exception { PID parentPid = makePid(); AdminUnit parent = repositoryObjectFactory.createAdminUnit(parentPid, null); contentRoot.addMember(parent); treeIndexer.indexAll(baseAddress); String label = "collection_label"; MvcResult result = mvc.perform(post("/edit/create/collection/" + parentPid.getId()) .param("label", label)) .andExpect(status().is2xxSuccessful()) .andReturn(); treeIndexer.indexAll(baseAddress); assertChildContainerAdded(parent, label, CollectionObject.class); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(parentPid.getUUID(), respMap.get("pid")); assertEquals("create", respMap.get("action")); assertPatronDoesNotHaveNonePermission(parent, label); }
Source:
public void testGetUsersInGroupAndSubgroupsWithoutInfiniteLoop() throws Exception { deleteTestObjects(); DocumentModel u1 = getUser("test_u1"); DocumentModel u2 = getUser("test_u2"); DocumentModel u2bis = getUser("test_u2bis"); userManager.createUser(u1); userManager.createUser(u2); userManager.createUser(u2bis); DocumentModel g1 = getGroup("test_g1"); DocumentModel g2 = getGroup("test_g2"); List<String> g1Users = Collections.singletonList("test_u1"); List<String> g2Users = Arrays.asList("test_u2", "test_u2bis"); List<String> g2Groups = Collections.singletonList("test_g1"); List<String> g1Groups = Collections.singletonList("test_g2"); g1.setProperty("group", "members", g1Users); g1.setProperty("group", "subGroups", g1Groups); userManager.createGroup(g1); g2.setProperty("group", "members", g2Users); g2.setProperty("group", "subGroups", g2Groups); userManager.createGroup(g2); List<String> expectedUsersInGroup2 = Arrays.asList("test_u2bis", "test_u2", "test_u1"); List<String> usersInGroupAndSubGroups2 = userManager.getUsersInGroupAndSubGroups("test_g2"); Collections.sort(expectedUsersInGroup2); Collections.sort(usersInGroupAndSubGroups2); assertEquals(expectedUsersInGroup2, usersInGroupAndSubGroups2); List<String> g1AncestorGroups = userManager.getAncestorGroups("test_g1"); assertEquals(Arrays.asList("test_g2", "test_g1"), g1AncestorGroups); }

Target:
public void testGetUsersInGroupAndSubgroupsWithoutInfiniteLoop() throws Exception { deleteTestObjects(); DocumentModel u1 = getUser("test_u1"); DocumentModel u2 = getUser("test_u2"); DocumentModel u2bis = getUser("test_u2bis"); userManager.createUser(u1); userManager.createUser(u2); userManager.createUser(u2bis); DocumentModel g1 = getGroup("test_g1"); DocumentModel g2 = getGroup("test_g2"); List<String> g1Users = Collections.singletonList("test_u1"); List<String> g2Users = Arrays.asList("test_u2", "test_u2bis"); List<String> g2Groups = Collections.singletonList("test_g1"); List<String> g1Groups = Collections.singletonList("test_g2"); g1.setProperty("group", "members", g1Users); g1.setProperty("group", "subGroups", g1Groups); userManager.createGroup(g1); g2.setProperty("group", "members", g2Users); g2.setProperty("group", "subGroups", g2Groups); userManager.createGroup(g2); List<String> expectedUsersInGroup2 = Arrays.asList("test_u2bis", "test_u2", "test_u1"); List<String> usersInGroupAndSubGroups2 = userManager.getUsersInGroupAndSubGroups("test_g2"); Collections.sort(expectedUsersInGroup2); Collections.sort(usersInGroupAndSubGroups2); assertEquals(expectedUsersInGroup2, usersInGroupAndSubGroups2); List<String> g1AncestorGroups = userManager.getAncestorGroups("test_g1"); assertTrue(CollectionUtils.isEqualCollection(Arrays.asList("test_g2", "test_g1"), g1AncestorGroups)); }
Source:
private ITimeGraphState createTimeGraphState(ITmfStateInterval interval, ITmfStateSystem ss) throws StateSystemDisposedException { long startTime = interval.getStartTime(); long endTime = interval.getEndTime(); long duration = endTime - startTime + 1; Object statusObj = interval.getValue(); if (statusObj instanceof Integer) { int status = (int) statusObj; if (status == StateValues.CPU_STATUS_RUN_USERMODE || status == StateValues.CPU_STATUS_RUN_SYSCALL) { return fTimeEventNames.getUnchecked(interval); } if (status != 0) { Object processName = null; if (execNameIntervals.containsEntry(status, new OverlapComparableInterval(interval))) { processName = execNameIntervals.get(status).first().getInterval().getValue(); } else { int quark = ss.optQuarkAbsolute(Attributes.THREADS, Integer.toString(status), Attributes.EXEC_NAME); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE) { ITmfStateInterval namedInterval = ss.querySingleState(endTime, quark); execNameIntervals.put(status, new OverlapComparableInterval(namedInterval)); processName = namedInterval.getValue(); } } if (processName instanceof String) { return new TimeGraphState(startTime, duration, status, (String) processName + '/' + status); } } return new TimeGraphState(startTime, duration, status); } return new TimeGraphState(startTime, duration, Integer.MIN_VALUE); }

Target:
private ITimeGraphState createTimeGraphState(ITmfStateInterval interval, ITmfStateSystem ss) throws StateSystemDisposedException { long startTime = interval.getStartTime(); long endTime = interval.getEndTime(); long duration = endTime - startTime + 1; Object statusObj = interval.getValue(); Type type = fEntryModelTypes.get(interval.getAttribute()); if (statusObj instanceof Integer) { int status = (int) statusObj; if (type == Type.CPU) { if (status == StateValues.CPU_STATUS_RUN_USERMODE || status == StateValues.CPU_STATUS_RUN_SYSCALL) { return fTimeEventNames.getUnchecked(interval); } } else if (type == Type.CURRENT_THREAD) { Object processName = null; if (fExecNamesCache.containsEntry(status, interval)) { processName = fExecNamesCache.get(status).first().getValue(); } else { int quark = ss.optQuarkAbsolute(Attributes.THREADS, Integer.toString(status), Attributes.EXEC_NAME); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE) { ITmfStateInterval namedInterval = ss.querySingleState(endTime, quark); fExecNamesCache.put(status, namedInterval); processName = namedInterval.getValue(); } } if (processName instanceof String) { return new TimeGraphState(startTime, duration, status, (String) processName + '/' + status); } } return new TimeGraphState(startTime, duration, status); } return new TimeGraphState(startTime, duration, Integer.MIN_VALUE); }
Source:
public boolean isEveryHeaderAllowed(String headers) { Boolean result = false; if (!Strings.isNullOrEmpty(headers)) { if (this.allowedHeadersRaw.equals(ALLOW_ANY_HEADER)) { result = true; } else { for (String header: Splitter.on(HEADER_VALUE_SEPARATOR).split( headers)) { result = this.allowedHeaders.contains(header); if (!result) { break; } } } } if (result) { logger.debug("CORS headers allowed: {}", headers); } else { logger.debug("CORS headers not allowed: {}", headers); } return result; }

Target:
public boolean isEveryHeaderAllowed(String headers) { boolean result = false; if (!Strings.isNullOrEmpty(headers)) { if (this.allowedHeadersRaw.equals(ALLOW_ANY_HEADER)) { result = true; } else { for (String header : Splitter.on(HEADER_VALUE_SEPARATOR).split( headers)) { result = this.allowedHeaders.contains(header); if (!result) { break; } } } } if (result) { logger.debug("CORS headers allowed: {}", headers); } else { logger.debug("CORS headers not allowed: {}", headers); } return result; }
Source:
public PropertyPlaceholderWrapper( DefaultConditionsProvider conditionsProvider, StaticSTSProperties properties) { samlConditionsProvider = conditionsProvider; stsProperties = properties; samlConditionsProvider.setLifetime(DEFAULT_LIFETIME); stsProperties.setSignatureUsername(SystemBaseUrl.EXTERNAL.getHost()); stsProperties.setIssuer(SystemBaseUrl.EXTERNAL.getHost()); stsProperties.setEncryptionUsername(SystemBaseUrl.EXTERNAL.getHost()); }

Target:
public PropertyPlaceholderWrapper( DefaultConditionsProvider conditionsProvider, StaticSTSProperties properties) { samlConditionsProvider = conditionsProvider; stsProperties = properties; samlConditionsProvider.setLifetime(DEFAULT_LIFETIME); stsProperties.setSignatureUsername(SystemBaseUrl.INTERNAL.getHost()); stsProperties.setIssuer(SystemBaseUrl.INTERNAL.getHost()); stsProperties.setEncryptionUsername(SystemBaseUrl.INTERNAL.getHost()); }
Source:
public Object receiveNewComment(HttpServletRequest request, @SiteParam Site site, @RequestParam("commentTitle") String commentTitle, @RequestParam("comment") String commentBody, @RequestParam("isCompetingInterest") boolean hasCompetingInterest, @RequestParam(value = "ciStatement", required = false) String ciStatement, @RequestParam(value = "target", required = false) String parentArticleDoi, @RequestParam(value = "inReplyTo", required = false) String parentCommentUri) throws IOException { enforceDevFeature("commentsTab"); Map<String, Object> validationErrors = commentValidationService.validate(site, commentTitle, commentBody, hasCompetingInterest, ciStatement); if (!validationErrors.isEmpty()) { return ImmutableMap.of("errors", validationErrors); } parentCommentUri = parentCommentUri == null ? "" : parentCommentUri; URI forwardedUrl = UriUtil.concatenate(soaService.getServerUrl(), COMMENT_NAMESPACE); HttpEntity entity = new StringEntity("{'articleDoi':'" + parentArticleDoi + "','creatorAuthId':'" + request.getRemoteUser() + "','parentCommentId':'" + parentCommentUri + "','title':'" + commentTitle + "','body':'" + commentBody + "','competingInterestStatement':'" + ciStatement + "'}", ContentType.create("application/json")); HttpUriRequest commentPostRequest = HttpMessageUtil.buildEntityPostRequest(forwardedUrl, entity); CloseableHttpResponse response = soaService.getResponse(commentPostRequest); String createdCommentUri = HttpMessageUtil.readResponse(response); response.close(); return ImmutableMap.of("createdCommentUri", createdCommentUri); }

Target:
public Object receiveNewComment(HttpServletRequest request, @SiteParam Site site, @RequestParam("commentTitle") String commentTitle, @RequestParam("comment") String commentBody, @RequestParam("isCompetingInterest") boolean hasCompetingInterest, @RequestParam(value = "ciStatement", required = false) String ciStatement, @RequestParam(value = "target", required = false) String parentArticleDoi, @RequestParam(value = "inReplyTo", required = false) String parentCommentUri) throws IOException { enforceDevFeature("commentsTab"); Map<String, Object> validationErrors = commentValidationService.validate(site, commentTitle, commentBody, hasCompetingInterest, ciStatement); if (!validationErrors.isEmpty()) { return ImmutableMap.of("errors", validationErrors); } URI forwardedUrl = UriUtil.concatenate(soaService.getServerUrl(), COMMENT_NAMESPACE); ArticleComment comment = new ArticleComment(parentArticleDoi, request.getRemoteUser(), parentCommentUri, commentTitle, commentBody, ciStatement); String articleCommentJson = new Gson().toJson(comment); HttpEntity entity = new StringEntity(articleCommentJson, ContentType.create("application/json")); HttpUriRequest commentPostRequest = HttpMessageUtil.buildEntityPostRequest(forwardedUrl, entity); try (CloseableHttpResponse response = soaService.getResponse(commentPostRequest)) { String createdCommentUri = HttpMessageUtil.readResponse(response); return ImmutableMap.of("createdCommentUri", createdCommentUri); } }
Source:
public void testRefreshingHostedTool() { ApiClient webClient = getWebClient(); ContainersApi containersApi = new ContainersApi(webClient); HostedApi hostedApi = new HostedApi(webClient); DockstoreTool hostedTool = hostedApi.createHostedTool("awesomeTool", "cwl", "quay.io", "coolNamespace"); thrown.expect(ApiException.class); DockstoreTool refreshedTool = containersApi.refresh(hostedTool.getId()); refreshedTool.getUsers().forEach(entryUser -> { Assert.assertNotEquals("refresh() endpoint should have user profiles", null, entryUser.getUserProfiles()); }); }

Target:
public void testRefreshingHostedTool() { ApiClient webClient = getWebClient(); ContainersApi containersApi = new ContainersApi(webClient); HostedApi hostedApi = new HostedApi(webClient); DockstoreTool hostedTool = hostedApi.createHostedTool("awesomeTool", "cwl", "quay.io", "coolNamespace"); thrown.expect(ApiException.class); DockstoreTool refreshedTool = containersApi.refresh(hostedTool.getId()); Assert.assertTrue("There should be at least one user of the workflow", refreshedTool.getUsers().size() > 0); refreshedTool.getUsers().forEach(entryUser -> { Assert.assertNotEquals("refresh() endpoint should have user profiles", null, entryUser.getUserProfiles()); }); }
Source:
public void should_throw_a_PageNotFoundException_when_no_page_is_found_for_id_in_mapping() throws Exception { final SPageMapping mapping = mock(SPageMapping.class); final SPage page = mock(SPage.class); when(mapping.getId()).thenReturn(1L); when(pageService.getPage(1L)).thenThrow(SBonitaReadException.class); when(pageMappingService.get("apiExtension|GET|myPathTemplate")).thenReturn(mapping); expectedException.expect(PageNotFoundException.class); pageAPIDelegate.getPageByMappingKey("apiExtension|GET|myPathTemplate"); }

Target:
public void should_throw_a_PageNotFoundException_when_no_page_is_found_for_id_in_mapping() throws Exception { final SPageMapping mapping = mock(SPageMapping.class); final SPage page = mock(SPage.class); when(mapping.getId()).thenReturn(1L); when(pageService.getPage(1L)).thenThrow(SObjectNotFoundException.class); when(pageMappingService.get("apiExtension|GET|myPathTemplate")).thenReturn(mapping); expectedException.expect(PageNotFoundException.class); pageAPIDelegate.getPageByMappingKey("apiExtension|GET|myPathTemplate"); }
Source:
public PdbHeader getPdbHeader(String pdbId) throws PdbHeaderNotFoundException, PdbHeaderWebServiceException { Optional<PdbHeader> pdbHeader = null; try { pdbHeader = this.cachedExternalResourceFetcher.fetchAndCache(pdbId); pdbHeader.ifPresent(x -> x.setPdbId(pdbId)); } catch (HttpClientErrorException e) { throw new PdbHeaderWebServiceException(pdbId, e.getResponseBodyAsString(), e.getStatusCode()); } catch (ResourceMappingException e) { throw new PdbHeaderNotFoundException(pdbId); } catch (ResourceAccessException e) { throw new PdbHeaderWebServiceException(pdbId, e.getMessage()); } return pdbHeader.map(x -> x).orElseThrow(() -> new PdbHeaderNotFoundException(pdbId)); }

Target:
public PdbHeader getPdbHeader(String pdbId) throws PdbHeaderNotFoundException, PdbHeaderWebServiceException { Optional<PdbHeader> pdbHeader = null; try { pdbHeader = Optional.of(this.cachedExternalResourceFetcher.fetchAndCache(pdbId)); pdbHeader.ifPresent(x -> x.setPdbId(pdbId)); } catch (HttpClientErrorException e) { throw new PdbHeaderWebServiceException(pdbId, e.getResponseBodyAsString(), e.getStatusCode()); } catch (ResourceMappingException e) { throw new PdbHeaderNotFoundException(pdbId); } catch (ResourceAccessException e) { throw new PdbHeaderWebServiceException(pdbId, e.getMessage()); } try { return pdbHeader.get(); } catch(NoSuchElementException e) { throw new PdbHeaderNotFoundException(pdbId); } }
Source:
private void setRequestId(HttpBaseMethod method) { deleteHeaderForAllRequests(OC_X_REQUEST_ID); String requestId = RandomUtils.generateRandomUUID(); addHeaderForAllRequests(OC_X_REQUEST_ID, requestId); Timber.d("Executing " + method.getClass().getSimpleName() + " in request with id " + requestId); }

Target:
private void setRequestId(HttpBaseMethod method) { deleteHeaderForAllRequests(OC_X_REQUEST_ID); String requestId = RandomUtils.generateRandomUUID(); addHeaderForAllRequests(OC_X_REQUEST_ID, requestId); Timber.d("Executing in request with id %s", requestId); }
Source:
public HiveWriter(HiveFileWriter fileWriter, Optional<String> partitionName, UpdateMode updateMode, String fileName, String writePath, String targetPath, Consumer<HiveWriter> onCommit, HiveWriterStats hiveWriterStats) { this.fileWriter = requireNonNull(fileWriter, "fileWriter is null"); this.partitionName = requireNonNull(partitionName, "partitionName is null"); this.updateMode = requireNonNull(updateMode, "updateMode is null"); this.fileName = requireNonNull(fileName, "fileName is null"); this.writePath = requireNonNull(writePath, "writePath is null"); this.targetPath = requireNonNull(targetPath, "targetPath is null"); this.onCommit = onCommit; this.hiveWriterStats = requireNonNull(hiveWriterStats); }

Target:
public HiveWriter( HiveFileWriter fileWriter, Optional<String> partitionName, UpdateMode updateMode, String fileName, String writePath, String targetPath, Consumer<HiveWriter> onCommit, HiveWriterStats hiveWriterStats) { this.fileWriter = requireNonNull(fileWriter, "fileWriter is null"); this.partitionName = requireNonNull(partitionName, "partitionName is null"); this.updateMode = requireNonNull(updateMode, "updateMode is null"); this.fileName = requireNonNull(fileName, "fileName is null"); this.writePath = requireNonNull(writePath, "writePath is null"); this.targetPath = requireNonNull(targetPath, "targetPath is null"); this.onCommit = requireNonNull(onCommit, "onCommit is null"); this.hiveWriterStats = requireNonNull(hiveWriterStats, "hiveWriterStats is null"); }
Source:
public void init (RuleConfig rc, RuleConfigTableModel model) { this.rc = rc; this.model = model; this.removeAllFields(); this.addReadOnlyField(FIELD_KEY, rc.getKey(), false); this.addReadOnlyField(FIELD_DEFAULT, rc.getDefaultValue(), false); this.addTextField(FIELD_VALUE, rc.getValue()); String desc = ""; if (Constant.messages.containsKey(rc.getKey())) { desc = Constant.messages.getString(rc.getKey()); } this.addMultilineField(FIELD_DESC, desc); ZapTextArea descField = ((ZapTextArea)this.getField(FIELD_DESC)); descField.setEditable(false); descField.setWrapStyleWord(true); }

Target:
public void init (RuleConfig rc, RuleConfigTableModel model) { this.rc = rc; this.model = model; this.removeAllFields(); this.addReadOnlyField(FIELD_KEY, rc.getKey(), false); this.addReadOnlyField(FIELD_DEFAULT, rc.getDefaultValue(), false); this.addTextField(FIELD_VALUE, rc.getValue()); String desc = ""; if (Constant.messages.containsKey(rc.getKey())) { desc = Constant.messages.getString(rc.getKey()); } this.addMultilineField(FIELD_DESC, desc); ZapTextArea descField = (ZapTextArea)this.getField(FIELD_DESC); descField.setEditable(false); descField.setWrapStyleWord(true); }
Source:
public String getUDN() { if (udn == null) { ZonePlayerConfiguration configuration = getConfigAs(ZonePlayerConfiguration.class); udn = configuration.udn; } return udn; }

Target:
public String getUDN() { return getConfigAs(ZonePlayerConfiguration.class).udn; }
Source:
public String toString() { return "SecretEnvVar [secretName=" + secretName + ", secretKey=" + secretKey + ", getKey()=" + getKey() + ", potional=" + String.valueOf(getOptional()) + "]"; }

Target:
public String toString() { return "SecretEnvVar [secretName=" + secretName + ", secretKey=" + secretKey + ", getKey()=" + getKey() + ", optional=" + String.valueOf(getOptional()) + "]"; }
Source:
private File createFileFromAttachement(Attachment attachment) { try (InputStream inputStream = attachment.getDataHandler().getInputStream()) { if (inputStream == null) { LOGGER.debug("No file attachment found"); return null; } if (inputStream.available() == 0) { inputStream.reset(); } String filename = getFileName(attachment.getContentDisposition()); if (!filename.endsWith(JAR_EXT) && !filename.endsWith(KAR_EXT)) { LOGGER.debug("Wrong file type: {}", FilenameUtils.getExtension(filename)); Response.ResponseBuilder responseBuilder = Response.serverError(); responseBuilder.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE_415); return null; } File uploadDir = new File(defaultFileLocation); if (!uploadDir.exists() && uploadDir.mkdirs()) { LOGGER.info("Unable to make directory {}", uploadDir.getAbsolutePath()); } File newFile = new File(uploadDir, filename); FileUtils.copyInputStreamToFile(inputStream, newFile); return newFile; } catch (IOException e) { LOGGER.debug("Unable to write file", e); return null; } }

Target:
private File createFileFromAttachement(Attachment attachment) { InputStream inputStream = null; try { inputStream = attachment.getDataHandler().getInputStream(); if (inputStream == null) { LOGGER.debug("No file attachment found"); return null; } if (inputStream.available() == 0) { inputStream.reset(); } String filename = getFileName(attachment.getContentDisposition()); if (!filename.endsWith(JAR_EXT) && !filename.endsWith(KAR_EXT)) { LOGGER.debug("Wrong file type: {}", FilenameUtils.getExtension(filename)); return null; } File uploadDir = new File(defaultFileLocation); if (!uploadDir.exists() && !uploadDir.mkdirs()) { LOGGER.info("Unable to make directory {}", uploadDir.getAbsolutePath()); } File newFile = new File(uploadDir, filename); FileUtils.copyInputStreamToFile(inputStream, newFile); return newFile; } catch (IOException e) { LOGGER.debug("Unable to write file", e); return null; } finally { IOUtils.closeQuietly(inputStream); } }