auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<SDVariable> doDiff(List<SDVariable> i_v1) { SDVariable absIn = sameDiff.abs(arg()); SDVariable maxnorm = outputVariables()[0]; SDVariable maxnormBc = sameDiff.f().reductionBroadcastableWithOrigShape(arg().getShape().length, dimensions, maxnorm); maxnormBc = sameDiff.onesLike(arg()).mul(maxnormBc); SDVariable eq = sameDiff.eq(absIn, maxnormBc); SDVariable dAbsXdX = sameDiff.sign(arg()); SDVariable ret = eq.mul(dAbsXdX); return Collections.singletonList(ret); }

Target:
public List<SDVariable> doDiff(List<SDVariable> i_v1) { SDVariable absIn = sameDiff.abs(arg()); SDVariable maxnorm = outputVariables()[0]; int origRank = Shape.rankFromShape(arg().getShape()); SDVariable maxnormBc = sameDiff.f().reductionBroadcastableWithOrigShape(origRank, dimensions, maxnorm); maxnormBc = sameDiff.onesLike(arg()).mul(maxnormBc); SDVariable eq = sameDiff.eq(absIn, maxnormBc); SDVariable dAbsXdX = sameDiff.sign(arg()); SDVariable ret = eq.mul(dAbsXdX); return Collections.singletonList(ret); }
Source:
AbstractDataSetNormalizer(NormalizerStrategy<S> strategy) { super(strategy); }

Target:
protected AbstractDataSetNormalizer(NormalizerStrategy<S> strategy) { super(strategy); }
Source:
public static Set<BoltServerAddress> serverSet( String... addresses ) { Set<BoltServerAddress> result = new HashSet<>(); for ( String address : addresses ) { result.add( new BoltServerAddress( address ) ); } return result; }

Target:
private static Set<BoltServerAddress> serverSet( String... addresses ) { Set<BoltServerAddress> result = new HashSet<>(); for ( String address : addresses ) { result.add( new BoltServerAddress( address ) ); } return result; }
Source:
public static Iterable<Path> searchFiles(final String id, final String bucketName, final BulkJobType type) throws IOException { ensureDirExists(); List<Path> matches = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(getTempdir(), "*" + RECOVERY_FILE_EXTENSION)) { for (final Path file : stream) { final RecoveryJob job = getRecoveryJobByFile(file.toFile()); if(id == null || job.getId().compareTo(UUID.fromString(id)) == 0) { if(Guard.isStringNullOrEmpty(bucketName) || job.getBucketName().equals(bucketName)) { if(type == null || job.getJobType().equals(type)) { matches.add(file); } } } } } catch (final IOException e) { throw new IOException("Could not search files." , e); } return matches; }

Target:
public static Iterable<Path> searchFiles(final String id, final String bucketName, final BulkJobType type) throws IOException { ensureDirExists(); final List<Path> matches = new ArrayList<>(); try (final DirectoryStream<Path> stream = Files.newDirectoryStream(getTempdir(), "*" + RECOVERY_FILE_EXTENSION)) { for (final Path file : stream) { final RecoveryJob job = getRecoveryJobByFile(file.toFile()); if(id == null || job.getId().compareTo(UUID.fromString(id)) == 0) { if(Guard.isStringNullOrEmpty(bucketName) || job.getBucketName().equals(bucketName)) { if(type == null || job.getJobType().equals(type)) { matches.add(file); } } } } } catch (final IOException e) { throw new IOException("Could not search files." , e); } return matches; }
Source:
public void testAppendWithKey() throws Exception { final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKey"); final LogEvent logEvent = createLogEvent(); appender.append(logEvent); final List<ProducerRecord<byte[], byte[]>> history = kafka.history(); assertEquals(1, history.size()); final ProducerRecord<byte[], byte[]> item = history.get(0); assertNotNull(item); assertEquals(TOPIC_NAME, item.topic()); String msgKey = item.key().toString(); byte[] keyValue = "key".getBytes(); assertArrayEquals(item.key(), keyValue); assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8)); }

Target:
public void testAppendWithKey() throws Exception { final Appender appender = ctx.getRequiredAppender("KafkaAppenderWithKey"); final LogEvent logEvent = createLogEvent(); appender.append(logEvent); final List<ProducerRecord<byte[], byte[]>> history = kafka.history(); assertEquals(1, history.size()); final ProducerRecord<byte[], byte[]> item = history.get(0); assertNotNull(item); assertEquals(TOPIC_NAME, item.topic()); String msgKey = item.key().toString(); byte[] keyValue = "key".getBytes(StandardCharsets.UTF_8); assertArrayEquals(item.key(), keyValue); assertEquals(LOG_MESSAGE, new String(item.value(), StandardCharsets.UTF_8)); }
Source:
protected void copyVmDevices() { ArrayList<VmDevice> devices = new ArrayList<VmDevice>(vmFromConfiguration.getVmUnamagedDeviceList()); devices.addAll(vmFromConfiguration.getManagedVmDeviceMap().values()); VmDeviceUtils.copyVmDevices(getVmIdFromSnapshot(), getVmId(), vmFromConfiguration, vmFromConfiguration.getStaticData(), true, devices, newDiskImages, _vmInterfaces); }

Target:
protected void copyVmDevices() { List<VmDevice> devices = new ArrayList<VmDevice>(vmFromConfiguration.getVmUnamagedDeviceList()); devices.addAll(vmFromConfiguration.getManagedVmDeviceMap().values()); VmDeviceUtils.copyVmDevices(getVmIdFromSnapshot(), getVmId(), vmFromConfiguration, vmFromConfiguration.getStaticData(), true, devices, newDiskImages, _vmInterfaces); }
Source:
private Token finishToken(Token token) { _currentToken = token; if (_currentToken == START_OBJECT) { if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue << 1; } else if (_currentToken == START_ARRAY) { if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue; } else if (_currentToken != NOT_AVAILABLE) { _currComplexObjTokenSize--; } return _currentToken; }

Target:
private Token finishToken(Token token) { _currentToken = token; switch (_currentToken) { case START_OBJECT: if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue << 1; break; case START_ARRAY: if (_currComplexObjTokenSize > 0) { _complexObjTokenSizeStack.push(_currComplexObjTokenSize); } _currComplexObjTokenSize = _intValue; break; case NOT_AVAILABLE: break; default: _currComplexObjTokenSize--; } return _currentToken; }
Source:
public ByteBuf decode(DataBuffer dataBuffer, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { int byteCount = dataBuffer.readableByteCount(); ByteBuf copy = Unpooled.buffer(byteCount); copy.writeBytes(dataBuffer.asByteBuffer()); copy.readerIndex(0); DataBufferUtils.release(dataBuffer); if (logger.isDebugEnabled()) { logger.debug(Hints.getLogPrefix(hints) + "Read " + byteCount + " bytes"); } return copy; }

Target:
public ByteBuf decode(DataBuffer dataBuffer, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { ByteBuf byteBuf; if (dataBuffer instanceof NettyDataBuffer) { byteBuf = ((NettyDataBuffer) dataBuffer).getNativeBuffer(); } else { byteBuf = Unpooled.wrappedBuffer(dataBuffer.asByteBuffer()); DataBufferUtils.release(dataBuffer); } if (logger.isDebugEnabled()) { logger.debug(Hints.getLogPrefix(hints) + "Read " + byteBuf.readableBytes() + " bytes"); } return byteBuf; }
Source:
public void testVersionedDelete() { System.out.println("*********** testing versioned delete ***********"); ByteArray key = new ByteArray("keyOne".getBytes()); List<Versioned<byte[]>> conflictingVersions = generatePutWithConflictionVersions(key); if(conflictingVersions.size() == 0) { Assert.fail("Could not generate conflicting versions "); } testDelete(key, conflictingVersions.get(0).getVersion()); }

Target:
public void testVersionedDelete() { logger.info("*********** testing versioned delete ***********"); ByteArray key = new ByteArray("keyOne".getBytes()); List<Versioned<byte[]>> conflictingVersions = generatePutWithConflictionVersions(key); if(conflictingVersions.size() == 0) { Assert.fail("Could not generate conflicting versions "); } testDelete(key, conflictingVersions.get(0).getVersion()); }
Source:
private void threadSummary() { List<String> prefixes = Lists.newArrayList("HTTP", "IntraLineDiff", "ReceiveCommits", "SSH git-receive-pack", "SSH git-upload-pack", "SSH-Interactive-Worker", "SSH-Stream-Worker", "SshCommandStart"); String other = "Other"; Runtime r = Runtime.getRuntime(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); stdout.format("Threads: %d CPUs available, %d threads\n", r.availableProcessors(), threadMXBean.getThreadCount()); if (showThreads) { Table<String, Thread.State, Integer> count = HashBasedTable.create(); threadLoop: for (long id : threadMXBean.getAllThreadIds()) { ThreadInfo info = threadMXBean.getThreadInfo(id); if (info == null) { continue; } String name = info.getThreadName(); Thread.State state = info.getThreadState(); for (String p : prefixes) { if (name.startsWith(p)) { Integer c = count.get(p, state); count.put(p, info.getThreadState(), c != null ? c + 1 : 1); continue threadLoop; } } Integer c = count.get(other, state); count.put(other, info.getThreadState(), c != null ? c + 1 : 1); } stdout.print(String.format(" %22s", "")); for (Thread.State s : Thread.State.values()) { stdout.print(String.format(" %14s", s.name())); } stdout.print('\n'); for (String p : prefixes) { stdout.print(String.format(" %-22s", p)); for (Thread.State s : Thread.State.values()) { stdout.print(String.format(" %14d", nullToZero(count.get(p, s)))); } stdout.print('\n'); } stdout.print(String.format(" %-22s", other)); for (Thread.State s : Thread.State.values()) { stdout.print(String.format(" %14d", nullToZero(count.get(other, s)))); } stdout.print('\n'); } stdout.print('\n'); }

Target:
private void threadSummary() { List<String> prefixes = Arrays.asList("HTTP", "IntraLineDiff", "ReceiveCommits", "SSH git-receive-pack", "SSH git-upload-pack", "SSH-Interactive-Worker", "SSH-Stream-Worker", "SshCommandStart"); String other = "Other"; Runtime r = Runtime.getRuntime(); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); stdout.format("Threads: %d CPUs available, %d threads\n", r.availableProcessors(), threadMXBean.getThreadCount()); if (showThreads) { Table<String, Thread.State, Integer> count = HashBasedTable.create(); threadLoop: for (long id : threadMXBean.getAllThreadIds()) { ThreadInfo info = threadMXBean.getThreadInfo(id); if (info == null) { continue; } String name = info.getThreadName(); Thread.State state = info.getThreadState(); for (String p : prefixes) { if (name.startsWith(p)) { Integer c = count.get(p, state); count.put(p, info.getThreadState(), c != null ? c + 1 : 1); continue threadLoop; } } Integer c = count.get(other, state); count.put(other, info.getThreadState(), c != null ? c + 1 : 1); } stdout.print(String.format(" %22s", "")); for (Thread.State s : Thread.State.values()) { stdout.print(String.format(" %14s", s.name())); } stdout.print('\n'); for (String p : prefixes) { printThreadCounts(p, count.row(p)); } printThreadCounts(other, count.row(other)); } stdout.print('\n'); }
Source:
public void onError(Throwable t) { L.logRemoteErrorIfProd(t); Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); }

Target:
public void onError(Throwable t) { Toast.makeText(context, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show(); }
Source:
protected void executeCommand() { boolean isNew = false; UserProfile profile = userProfileDao.getByUserId(getUserId()); if (profile == null) { isNew = true; profile = new UserProfile(Guid.newGuid(), getUserId()); } if (StringUtils.isNotEmpty(getParameters().getUserProfile().getSshPublicKey())) { profile.setSshPublicKey(getParameters().getUserProfile().getSshPublicKey()); } if (getParameters().getUserProfile().isUserPortalVmLoginAutomatically() != null) { profile.setUserPortalVmLoginAutomatically(getParameters().getUserProfile().isUserPortalVmLoginAutomatically()); } if (isNew) { userProfileDao.save(profile); } else { userProfileDao.update(profile); } setSucceeded(true); }

Target:
protected void executeCommand() { UserProfile profile = userProfileDao.getByUserId(getUserId()); if (StringUtils.isNotEmpty(getParameters().getUserProfile().getSshPublicKey())) { profile.setSshPublicKey(getParameters().getUserProfile().getSshPublicKey()); } if (getParameters().getUserProfile().isUserPortalVmLoginAutomatically() != null) { profile.setUserPortalVmLoginAutomatically(getParameters().getUserProfile().isUserPortalVmLoginAutomatically()); } userProfileDao.update(profile); setSucceeded(true); }
Source:
public String getKeyStorePath() { String path = getString(ConfVars.ZEPPELIN_SSL_KEYSTORE_PATH); if (path != null && path.startsWith("/")) { return path; } else { return getRelativeDir( String.format("%s/%s", getConfDir(), getString(path))); } }

Target:
public String getKeyStorePath() { String path = getString(ConfVars.ZEPPELIN_SSL_KEYSTORE_PATH); if (path != null && path.startsWith("/") || isWindowsPath(path)) { return path; } else { return getRelativeDir( String.format("%s/%s", getConfDir(), getString(path))); } }
Source:
private void updateAll(Config config) throws IOException, ConfigInvalidException { if (config == null) { return; } updateAll(config.getBaseConfig()); if (config instanceof FileBasedConfig) { FileBasedConfig cfg = (FileBasedConfig) config; if (cfg.isOutdated()) { LOG.debug("loading system config {}", cfg); cfg.load(); } } }

Target:
private void updateAll(Config config) throws IOException, ConfigInvalidException { if (config == null) { return; } updateAll(config.getBaseConfig()); if (config instanceof FileBasedConfig) { FileBasedConfig cfg = (FileBasedConfig) config; if (!cfg.getFile().exists()) { return; } if (cfg.isOutdated()) { LOG.debug("loading system config {}", cfg); cfg.load(); } } }
Source:
protected void onLoad() { super.onLoad(); CallbackGroup group = new CallbackGroup(); if (Gerrit.isSignedIn()) { ChangeApi.edit(changeId.get(), group.add( new GerritCallback<EditInfo>() { @Override public void onSuccess(EditInfo result) { edit = result; } public void onFailure(Throwable caught) { int i = 0; i++; }; })); } loadChangeInfo(true, group.addFinal( new GerritCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo info) { info.init(); loadConfigInfo(info, base); } })); }

Target:
protected void onLoad() { super.onLoad(); CallbackGroup group = new CallbackGroup(); if (Gerrit.isSignedIn()) { ChangeApi.edit(changeId.get(), group.add( new GerritCallback<EditInfo>() { @Override public void onSuccess(EditInfo result) { edit = result; } })); } loadChangeInfo(true, group.addFinal( new GerritCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo info) { info.init(); loadConfigInfo(info, base); } })); }
Source:
public void testInsert() throws Exception { execute("CREATE TABLE tpch.test_insert (x bigint, y varchar(100), t_ts timestamp)"); assertUpdate(getQueryRunner().getDefaultSession(), "INSERT INTO test_insert VALUES (123, 'test', date_parse('1970-12-01 00:00:01','%Y-%m-%d %H:%i:%s'))", 1); assertUpdate(getQueryRunner().getDefaultSession(), "INSERT INTO test_insert VALUES (123, 'test', date_parse('2030-01-01 23:59:59','%Y-%m-%d %H:%i:%s'))", 1); MaterializedResult actual = computeActual("SELECT * FROM test_insert"); MaterializedResult expected = MaterializedResult.resultBuilder(getSession(), BIGINT, VarcharType.createVarcharType(100), TIMESTAMP) .row((long) 123, "test", Timestamp.valueOf("1970-12-01 00:00:01")) .row((long) 123, "test", Timestamp.valueOf("2030-01-01 23:59:59")) .build(); assertEquals(actual, expected); assertUpdate("DROP TABLE test_insert"); }

Target:
public void testInsert() throws Exception { execute("CREATE TABLE tpch.test_insert (c_bigint bigint, c_varchar_100 varchar(100), c_timestamp timestamp)"); assertUpdate(getQueryRunner().getDefaultSession(), "INSERT INTO test_insert VALUES (123, 'test', date_parse('1970-12-01 00:00:01','%Y-%m-%d %H:%i:%s'))", 1); assertUpdate(getQueryRunner().getDefaultSession(), "INSERT INTO test_insert VALUES (123, 'test', date_parse('2030-01-01 23:59:59','%Y-%m-%d %H:%i:%s'))", 1); MaterializedResult actual = computeActual("SELECT * FROM test_insert"); MaterializedResult expected = MaterializedResult.resultBuilder(getSession(), BIGINT, VarcharType.createVarcharType(100), TIMESTAMP) .row((long) 123, "test", Timestamp.valueOf("1970-12-01 00:00:01")) .row((long) 123, "test", Timestamp.valueOf("2030-01-01 23:59:59")) .build(); assertEquals(actual, expected); assertUpdate("DROP TABLE test_insert"); }
Source:
public DynamicTableSource createDynamicTableSource(Context context) { FactoryUtil.TableFactoryHelper helper = FactoryUtil .createTableFactoryHelper(this, context); Properties connectorProperties = KinesisOptions .getConnectorProperties(context.getCatalogTable().getOptions()); ReadableConfig tableOptions = helper.getOptions(); DecodingFormat<DeserializationSchema<RowData>> decodingFormat = helper .discoverDecodingFormat(DeserializationFormatFactory.class, FactoryUtil.FORMAT); helper.validateExcept(KinesisOptions.PROPERTIES_PREFIX); validateTableOptionsAndConnectorProperties(tableOptions, connectorProperties); return new KinesisDynamicSource( context.getCatalogTable().getSchema().toPhysicalRowDataType(), tableOptions.get(KinesisOptions.STREAM), KinesisOptions.getConnectorProperties(context.getCatalogTable().getOptions()), decodingFormat ); }

Target:
public DynamicTableSource createDynamicTableSource(Context context) { FactoryUtil.TableFactoryHelper helper = FactoryUtil.createTableFactoryHelper(this, context); ReadableConfig tableOptions = helper.getOptions(); CatalogTable catalogTable = context.getCatalogTable(); Properties properties = KinesisOptions.getConsumerProperties(catalogTable.getOptions()); DecodingFormat<DeserializationSchema<RowData>> decodingFormat = helper .discoverDecodingFormat(DeserializationFormatFactory.class, FactoryUtil.FORMAT); helper.validateExcept(KinesisOptions.NON_VALIDATED_PREFIXES); validateConsumerProperties(tableOptions.get(KinesisOptions.STREAM), properties); return new KinesisDynamicSource( catalogTable.getSchema().toPhysicalRowDataType(), tableOptions.get(KinesisOptions.STREAM), properties, decodingFormat ); }
Source:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)) .onErrorReturn(new Func1<Throwable, Result<R>>() { @Override public Result<R> call(Throwable throwable) { return Result.error(throwable); } }); }

Target:
@Override public <R> Observable<Result<R>> adapt(Call<R> call, Retrofit retrofit) { return Observable.create(new CallOnSubscribe<>(call, retrofit)); }
Source:
private boolean hasNext() throws IOException { return seekableStream.position() <= (end >> 16); }

Target:
public boolean hasNext() { try { return seekableStream.position() <= (end >> 16); } catch (final IOException e) { throw new RuntimeIOException(e); } }
Source:
private static String getExtension(String filename) { String extension = filename.toLowerCase().substring(filename.lastIndexOf(".") + 1); return extension; }

Target:
private static String getExtension(String filename) { String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase(); return extension; }
Source:
public void finalizeUpload( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = true) final String accessToken, @PathVariable(value = "object-id") String objectId, @RequestParam(value = "uploadId", required = true) String uploadId ) { val startMs = System.currentTimeMillis(); uploadService.finalizeUpload(objectId, uploadId); val endMs = System.currentTimeMillis(); log.info("Finalize upload completed in ms", endMs - startMs); }

Target:
public void finalizeUpload( @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = true) final String accessToken, @PathVariable(value = "object-id") String objectId, @RequestParam(value = "uploadId", required = true) String uploadId) { val watch = Stopwatch.createStarted(); uploadService.finalizeUpload(objectId, uploadId); log.info("Finalize upload completed in {}", watch); }
Source:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, courseId); String courseName = getRequestParamValue(Const.ParamsNames.COURSE_NAME); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_NAME, courseName); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible(instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE); CourseAttributes courseToEdit = new CourseAttributes(); courseToEdit.id = Sanitizer.sanitizeName(courseId); courseToEdit.name = Sanitizer.sanitizeName(courseName); try { logic.updateCourse(courseToEdit); statusToUser.add(new StatusMessage(Const.StatusMessages.COURSE_EDITED, StatusMessageColor.SUCCESS)); statusToAdmin = "Course name for Course <span class=\"bold\">[" + courseId + "]</span> edited.<br>" + "New name: " + courseName; } catch (InvalidParametersException e) { setStatusForException(e); } RedirectResult result = createRedirectResult(Const.ActionURIs.INSTRUCTOR_COURSE_EDIT_PAGE); result.addResponseParam(Const.ParamsNames.COURSE_ID, courseId); return result; }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, courseId); String courseName = getRequestParamValue(Const.ParamsNames.COURSE_NAME); Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_NAME, courseName); InstructorAttributes instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible(instructor, logic.getCourse(courseId), Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_COURSE); CourseAttributes courseToEdit = new CourseAttributes(); courseToEdit.id = courseId; courseToEdit.name = courseName; try { logic.updateCourse(courseToEdit); statusToUser.add(new StatusMessage(Const.StatusMessages.COURSE_EDITED, StatusMessageColor.SUCCESS)); statusToAdmin = "Course name for Course <span class=\"bold\">[" + courseId + "]</span> edited.<br>" + "New name: " + courseName; } catch (InvalidParametersException e) { setStatusForException(e); } RedirectResult result = createRedirectResult(Const.ActionURIs.INSTRUCTOR_COURSE_EDIT_PAGE); result.addResponseParam(Const.ParamsNames.COURSE_ID, courseId); return result; }
Source:
public WebClientStartProperties getWebClientStartProperties() { WebClientProperties webClientProperties = databaseService.getWebClientProperties(); Map<String, Set<String>> defaultMonitoringParameters = databaseService.getDefaultMonitoringParameters(); WebClientStartProperties startProperties = new WebClientStartProperties(); startProperties.setWebClientProperties(webClientProperties); startProperties.setDefaultMonitoringParameters(defaultMonitoringParameters); return startProperties; }

Target:
public WebClientStartProperties getWebClientStartProperties() { WebClientStartProperties startProperties = new WebClientStartProperties(); startProperties.setWebClientProperties(databaseService.getWebClientProperties()); startProperties.setDefaultMonitoringParameters(databaseService.getDefaultMonitoringParameters()); return startProperties; }
Source:
public void setReplyTimeout(long timeout) { if (System.currentTimeMillis() + timeout > Long.MAX_VALUE) throw new IllegalArgumentException("Extremely long reply timeout"); else replyTimeout = timeout; }

Target:
public void setReplyTimeout(long timeout) { if (Long.MAX_VALUE - System.currentTimeMillis() < timeout) { throw new IllegalArgumentException("Extremely long reply timeout"); } else { replyTimeout = timeout; } }
Source:
public Deque<Transition<State, Alphabet>> getPath(State initialState, Alphabet initialLetter, State finalState) { Deque<State> toProcess = new ArrayDeque<>(); Map<State, Transition<State, Alphabet>> considered = new HashMap<>(); considered.put(initialState, null); for (Transition<State, Alphabet> transition : getTransitions(initialState, initialLetter)) { State endState = transition.getEnd(); if (endState.equals(finalState)) { Deque<Transition<State, Alphabet>> result = new ArrayDeque<>(); result.push(transition); return result; } if (considered.containsKey(endState)) continue; considered.put(endState, transition); toProcess.add(endState); } return getPath(finalState, toProcess, considered); }

Target:
public Deque<Transition<State, Alphabet>> getPath(State initialState, Alphabet initialLetter, State finalState) { Deque<State> toProcess = new ArrayDeque<>(); Map<State, Transition<State, Alphabet>> considered = new HashMap<>(); considered.put(initialState, null); Deque<Transition<State, Alphabet>> result = getPathBFSStep(getTransitions(initialState, initialLetter), finalState, considered, toProcess); if (result != null) return result; return getPathBFS(finalState, toProcess, considered); }
Source:
public void test_SSLSocket_setSoWriteTimeout() throws Exception { if (StandardNames.IS_RI) { return; } final TestSSLContext c = TestSSLContext.create(); SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(); int sendBufferSize = 1024; client.setSendBufferSize(sendBufferSize); sendBufferSize = client.getSendBufferSize(); final int recvBufferSize = 128; c.serverSocket.setReceiveBufferSize(recvBufferSize); client.connect(new InetSocketAddress(c.host, c.port)); final SSLSocket server = (SSLSocket) c.serverSocket.accept(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { server.startHandshake(); return null; } }); executor.shutdown(); client.startHandshake(); String expectedClassName = "com.android.org.conscrypt.ConscryptFileDescriptorSocket"; Class<?> actualClass = client.getClass(); assertEquals(expectedClassName, actualClass.getName()); Method setSoWriteTimeout = actualClass.getMethod("setSoWriteTimeout", new Class<?>[] { Integer.TYPE }); setSoWriteTimeout.invoke(client, 1); try { final int extra = 1; client.getOutputStream().write(new byte[sendBufferSize + extra]); fail(); } catch (SocketTimeoutException expected) { } future.get(); client.close(); server.close(); c.close(); }

Target:
public void test_SSLSocket_setSoWriteTimeout() throws Exception { if (StandardNames.IS_RI) { return; } final TestSSLContext c = TestSSLContext.create(); SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(); int sendBufferSize = 1024; client.setSendBufferSize(sendBufferSize); sendBufferSize = client.getSendBufferSize(); final int recvBufferSize = 128; c.serverSocket.setReceiveBufferSize(recvBufferSize); client.connect(new InetSocketAddress(c.host, c.port)); final SSLSocket server = (SSLSocket) c.serverSocket.accept(); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { server.startHandshake(); return null; } }); executor.shutdown(); client.startHandshake(); String expectedClassName = "com.android.org.conscrypt.ConscryptFileDescriptorSocket"; Class<?> actualClass = client.getClass(); assertEquals(expectedClassName, actualClass.getName()); Class<?> superClass = actualClass.getSuperclass(); assertEquals("com.android.org.conscrypt.OpenSSLSocketImpl", superClass.getName()); Method setSoWriteTimeout = actualClass.getMethod("setSoWriteTimeout", new Class<?>[] { Integer.TYPE }); setSoWriteTimeout.invoke(client, 1); try { final int extra = 1; client.getOutputStream().write(new byte[sendBufferSize + extra]); fail(); } catch (SocketTimeoutException expected) { } future.get(); client.close(); server.close(); c.close(); }
Source:
public static ReadCountCollection removeColumnsWithBadValues(final ReadCountCollection readCounts, final Logger logger) { final List<String> columnNames = readCounts.columnNames(); final Set<String> columnsToKeep = new LinkedHashSet<>(readCounts.columnNames().size()); final Set<String> columnsToDrop = new HashSet<>(); for (int i = 0; i < columnNames.size(); i++) { if (Arrays.stream(readCounts.getColumn(i)) .filter(d -> Double.isNaN(d) || Double.isInfinite(d)) .count() == 0) { columnsToKeep.add(columnNames.get(i)); } else { columnsToDrop.add(columnNames.get(i)); } } if (columnsToKeep.isEmpty()) { throw new UserException.BadInput("No column count left after removing those with NaN and infinities"); } else if (columnsToKeep.size() == columnNames.size()) { logger.info("No column dropped due to bad values"); return readCounts; } else { final double droppedPercentage = ((double)(columnsToDrop.size()) / columnNames.size()) * 100; logger.info(String.format("Some columns dropped (%d out of %d, %.2f%%) as they contained bad values: %s", columnsToDrop.size(), columnNames.size(), droppedPercentage, columnsToDrop.stream().collect(Collectors.joining(", ", "[", "]")))); return readCounts.subsetColumns(columnsToKeep); } }

Target:
public static ReadCountCollection removeColumnsWithBadValues(final ReadCountCollection readCounts, final Logger logger) { final List<String> columnNames = readCounts.columnNames(); final Set<String> columnsToKeep = new LinkedHashSet<>(readCounts.columnNames().size()); final Set<String> columnsToDrop = new HashSet<>(); for (int i = 0; i < columnNames.size(); i++) { if (Arrays.stream(readCounts.getColumn(i)).noneMatch(d -> Double.isNaN(d) || Double.isInfinite(d) || d < 0)) { columnsToKeep.add(columnNames.get(i)); } else { columnsToDrop.add(columnNames.get(i)); } } if (columnsToKeep.isEmpty()) { throw new UserException.BadInput("No column count left after removing those with NaN and infinities"); } else if (columnsToKeep.size() == columnNames.size()) { logger.info("No column dropped due to bad values"); return readCounts; } else { final double droppedPercentage = ((double)(columnsToDrop.size()) / columnNames.size()) * 100; logger.info(String.format("Some columns dropped (%d out of %d, %.2f%%) as they contained bad values: %s", columnsToDrop.size(), columnNames.size(), droppedPercentage, columnsToDrop.stream().collect(Collectors.joining(", ", "[", "]")))); return readCounts.subsetColumns(columnsToKeep); } }
Source:
public KeyVaultOperation( final SecretClient secretClient, final long refreshInMillis, List<String> secretKeys, boolean caseSensitive ) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); if (refreshInMillis > 0) { final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; this.timer.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } }

Target:
public KeyVaultOperation( final SecretClient secretClient, final long refreshInMillis, List<String> secretKeys, boolean caseSensitive ) { this.caseSensitive = caseSensitive; this.secretClient = secretClient; this.secretKeys = secretKeys; refreshProperties(); if (refreshInMillis > 0) { final TimerTask task = new TimerTask() { @Override public void run() { refreshProperties(); } }; TIMER.scheduleAtFixedRate(task, refreshInMillis, refreshInMillis); } }
Source:
LogEventHandler(final Configuration conf) { namedQueueServices .put(NamedQueuePayload.NamedQueueEvent.SLOW_LOG, new SlowLogQueueService(conf)); }

Target:
LogEventHandler(final Configuration conf) { for (String implName : conf.getStringCollection(NAMED_QUEUE_PROVIDER_CLASSES)) { Class<?> clz; try { clz = Class.forName(implName); } catch (ClassNotFoundException e) { LOG.warn("Failed to find NamedQueueService implementor class {}", implName, e); continue; } if (!NamedQueueService.class.isAssignableFrom(clz)) { LOG.warn("Class is not implementor of NamedQueueService.", clz); continue; } try { NamedQueueService namedQueueService = (NamedQueueService) clz.getConstructor(Configuration.class).newInstance(conf); namedQueueServices.put(namedQueueService.getEvent(), namedQueueService); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { LOG.warn("Unable to instantiate/add NamedQueueService implementor to service map.", clz); } } }
Source:
public void shouldReturnApiKeyAvailability() { when(apiKeyService.exists(anyString())).thenReturn(true); Response response = envTarget("verify") .queryParam("apiKey", "atLeast10CharsButLessThan64") .request() .get(); assertEquals(HttpStatusCode.OK_200, response.getStatus()); assertEquals(false, response.readEntity(Boolean.class)); }

Target:
public void shouldReturnApiKeyAvailability() { when(apiKeyService.exists(anyString())).thenReturn(true); Response response = envTarget("_verify") .queryParam("apiKey", "atLeast10CharsButLessThan64") .request() .post(null); assertEquals(HttpStatusCode.OK_200, response.getStatus()); assertEquals(false, response.readEntity(Boolean.class)); }
Source:
private IResourceVariant findFileVariant(IResource resource, Repository repository) throws TeamException { RepositoryMapping repoMapping = RepositoryMapping.getMapping(resource); if (repoMapping == null) { return null; } String gitPath = repoMapping.getRepoRelativePath(resource); ObjectId objectId = updated.get(gitPath); if (objectId != null) { File root = repository.getWorkDir(); File file = new File(root, gitPath); if (resource.getLocation().toFile().equals(file)) { try { Tree merge = trees.get(repository); TreeEntry tree = merge.findBlobMember(gitPath); GitBlobResourceVariant variant = new GitBlobResourceVariant( resource, repository, tree.getId(), dates .get(gitPath)); return variant; } catch (IOException e) { throw new TeamException(new Status(IStatus.ERROR, Activator .getPluginId(), NLS.bind( CoreText.GitResourceVariantTree_couldNotFindBlob, gitPath), e)); } } } return null; }

Target:
private IResourceVariant findFileVariant(IResource resource, Repository repository) throws TeamException { RepositoryMapping repoMapping = RepositoryMapping.getMapping(resource); if (repoMapping == null) return null; String gitPath = repoMapping.getRepoRelativePath(resource); ObjectId objectId = updated.get(gitPath); if (objectId != null) { File root = repository.getWorkDir(); File file = new File(root, gitPath); if (resource.getLocation().toFile().equals(file)) { try { Tree merge = trees.get(repository); TreeEntry tree = merge.findBlobMember(gitPath); GitBlobResourceVariant variant = new GitBlobResourceVariant( resource, repository, tree.getId(), dates .get(gitPath)); return variant; } catch (IOException e) { throw new TeamException(new Status(IStatus.ERROR, Activator .getPluginId(), NLS.bind( CoreText.GitResourceVariantTree_couldNotFindBlob, gitPath), e)); } } } return null; }
Source:
private void advance() { int totalCycleCount = 0; CbclData data = new CbclData(outputLengths, cycleData[totalCycleCount].tileInfo.tileNum); for (int read = 0; read < outputLengths.length; read++) { for (int cycle = 0; cycle < outputLengths[read]; cycle++) { CycleData currentCycleData = cycleData[totalCycleCount]; if (cachedTilePosition[totalCycleCount] >= cachedTile[totalCycleCount].length || cachedTilePosition[totalCycleCount] >= cycleData[totalCycleCount].getTileInfo().getNumClustersInTile()) { return; } int singleByte = cachedTile[totalCycleCount][cachedTilePosition[totalCycleCount]++]; decodeQualityBinnedBasecall(data, read, cycle, singleByte, currentCycleData); totalCycleCount++; } } data.setPositionInfo(positionInfoIterator.next()); this.queue = data; }

Target:
private void advance() { int totalCycleCount = 0; final CbclData data = new CbclData(outputLengths, cycleData[totalCycleCount].tileInfo.tileNum); for (int read = 0; read < outputLengths.length; read++) { for (int cycle = 0; cycle < outputLengths[read]; cycle++) { final CycleData currentCycleData = cycleData[totalCycleCount]; if (cachedTilePosition[totalCycleCount] >= cachedTile[totalCycleCount].length || cachedTilePosition[totalCycleCount] >= cycleData[totalCycleCount].getTileInfo().getNumClustersInTile()) { return; } final int singleByte = cachedTile[totalCycleCount][cachedTilePosition[totalCycleCount]++]; decodeQualityBinnedBasecall(data, read, cycle, singleByte, currentCycleData); totalCycleCount++; } } data.setPositionInfo(positionInfoIterator.next()); this.queue = data; }
Source:
public void testIgnoreLinesSorted() throws Exception { final RegexpHeaderCheck check = new RegexpHeaderCheck(); check.setMultiLines(5, 9, 9, 11, 2); int[] multiLines = (int[]) Whitebox.getInternalState(check, "multiLines"); assertArrayEquals(new int[]{2, 5, 9, 9, 11}, multiLines); }

Target:
public void testIgnoreLinesSorted() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(RegexpHeaderCheck.class); checkConfig.addAttribute("headerFile", getPath("regexp.header5")); checkConfig.addAttribute("multiLines", "7,5,3"); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputRegexpHeader8.java"), expected); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_welcome_back_password_prompt_layout); if (savedInstanceState != null) { mPendingPassword = savedInstanceState.getString(ExtraConstants.EXTRA_PASSWORD, null); } getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); mIdpResponse = IdpResponse.fromResultIntent(getIntent()); mEmail = mIdpResponse.getEmail(); mPasswordLayout = findViewById(R.id.password_layout); mPasswordField = findViewById(R.id.password); ImeHelper.setImeOnDoneListener(mPasswordField, this); String bodyText = getString(R.string.fui_welcome_back_password_prompt_body, mEmail); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(bodyText); int emailStart = bodyText.indexOf(mEmail); spannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD), emailStart, emailStart + mEmail.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); TextView bodyTextView = findViewById(R.id.welcome_back_password_body); bodyTextView.setText(spannableStringBuilder); findViewById(R.id.button_done).setOnClickListener(this); findViewById(R.id.trouble_signing_in).setOnClickListener(this); mHandler = ViewModelProviders.of(this).get(WelcomeBackPasswordHandler.class); mHandler.init(getFlowHolder().getArguments()); mHandler.getPendingResolution().observe(this, new Observer<PendingResolution>() { @Override public void onChanged(@Nullable PendingResolution resolution) { onPendingResolution(resolution); } }); mHandler.getSignInOperation().observe(this, new Observer<Resource<IdpResponse>>() { @Override public void onChanged(@Nullable Resource<IdpResponse> resource) { onSignInOperation(resource); } }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fui_welcome_back_password_prompt_layout); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); mIdpResponse = IdpResponse.fromResultIntent(getIntent()); mEmail = mIdpResponse.getEmail(); mPasswordLayout = findViewById(R.id.password_layout); mPasswordField = findViewById(R.id.password); ImeHelper.setImeOnDoneListener(mPasswordField, this); String bodyText = getString(R.string.fui_welcome_back_password_prompt_body, mEmail); SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(bodyText); int emailStart = bodyText.indexOf(mEmail); spannableStringBuilder.setSpan(new StyleSpan(Typeface.BOLD), emailStart, emailStart + mEmail.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); TextView bodyTextView = findViewById(R.id.welcome_back_password_body); bodyTextView.setText(spannableStringBuilder); findViewById(R.id.button_done).setOnClickListener(this); findViewById(R.id.trouble_signing_in).setOnClickListener(this); mHandler = ViewModelProviders.of(this).get(WelcomeBackPasswordHandler.class); mHandler.init(getFlowHolder().getArguments()); mHandler.getSignInOperation().observe(this, new Observer<Resource<IdpResponse>>() { @Override public void onChanged(@Nullable Resource<IdpResponse> resource) { onSignInOperation(resource); } }); }
Source:
public void testEvaluateWithValidIPv4() throws URISyntaxException, HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedDataUDF geocodedDataUDF = new GeocodedDataUDF( TestGeocodedDataUDF.class.getResource(defaultDatabaseFile).getFile()); try { geocodedDataUDF.initialize(initArguments); } catch (UDFArgumentLengthException lenEx) { fail("UDFArgumentLengthException was thrown for valid argument"); } catch (UDFArgumentTypeException typeEx) { fail("UDFArgumentTypeException was thrown for valid argument"); } catch (RuntimeException rEx) { fail("RuntimeException was thrown for valid argument"); } String ip = "81.2.69.160"; DeferredObject[] args = new DeferredObject[] { new DeferredJavaObject(ip) }; Map<String, String> result = (Map<String, String>)geocodedDataUDF.evaluate(args); assertEquals("Continent check", "Europe", result.get("continent")); assertEquals("ISO country code check", "GB", result.get("country_code")); assertEquals("Country check", "United Kingdom", result.get("country")); assertEquals("Subdivision check", "England", result.get("subdivision")); assertEquals("City check", "London", result.get("city")); assertEquals("Postal code check", "Unknown", result.get("postal_code")); assertEquals("Latitude check", "51.5142", result.get("latitude")); assertEquals("Longitude check", "-0.0931", result.get("longitude")); assertEquals("Timezone check", "Europe/London", result.get("timezone")); }

Target:
public void testEvaluateWithValidIPv4() throws HiveException { String ip = "81.2.69.160"; Map<String, String> result = evaluate (ip); assertEquals("Continent check", "Europe", result.get("continent")); assertEquals("ISO country code check", "GB", result.get("country_code")); assertEquals("Country check", "United Kingdom", result.get("country")); assertEquals("Subdivision check", "England", result.get("subdivision")); assertEquals("City check", "London", result.get("city")); assertEquals("Postal code check", "Unknown", result.get("postal_code")); assertEquals("Latitude check", "51.5142", result.get("latitude")); assertEquals("Longitude check", "-0.0931", result.get("longitude")); assertEquals("Timezone check", "Europe/London", result.get("timezone")); }
Source:
private void updateParents() throws OrmException, UnloggedFailure { String parentName = ""; if (newParent != null && newParent.getProject() != null) { parentName = newParent.getProject().getName(); } final List<Project.NameKey> childrenNameKey = new ArrayList<Project.NameKey>(); for (ProjectControl pc: children) { childrenNameKey.add(pc.getProject().getNameKey()); } final PerformSetParent perfSetParent = performSetParent.create(parentName, childrenNameKey); final StringBuilder err = perfSetParent.setParent(); if (err.toString().endsWith("All:")) { err.replace(err.length() - 4, err.length(), ""); } if (err.length() > 0) { while (err.charAt(err.length() - 1) == '\n') { err.setLength(err.length() - 1); } throw new UnloggedFailure(1, err.toString()); } }

Target:
private void updateParents() throws OrmException, UnloggedFailure { NameKey parentNameKey = null; if (newParent != null && newParent.getProject() != null) { parentNameKey = newParent.getProject().getNameKey(); } final List<Project.NameKey> childrenNameKey = new ArrayList<Project.NameKey>(); for (ProjectControl pc: children) { childrenNameKey.add(pc.getProject().getNameKey()); } final PerformSetParent perfSetParent = performSetParent.create(parentNameKey, childrenNameKey); try { perfSetParent.setParent(); } catch (OperationNotExecutedException e) { throw new UnloggedFailure(1, e.getMessage()); } catch (NoSuchProjectException e){ throw new UnloggedFailure(1, e.getMessage()); } }
Source:
public String apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { ObjectLoader loader = repo.open(tw.getObjectId(0)); CharArrayWriter w = new CharArrayWriter(4 * (((int)loader.getSize() - 1)/3 + 1)); loader.copyTo(BaseEncoding.base64().encodingStream(w)); return w.toString(); } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }

Target:
public StreamingResponse apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { final ObjectLoader loader = repo.open(tw.getObjectId(0)); return new StreamingResponse() { @Override public String getContentType() { return "text/plain;charset=UTF-8"; } @Override public void stream(OutputStream out) throws IOException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, Charsets.UTF_8)); try { loader.copyTo(BaseEncoding.base64().encodingStream(writer)); } finally { writer.flush(); } } }; } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }
Source:
public Void exec() throws NotFoundException { if (StringUtils.isNotEmpty(this.hostResource)) { if (this.tarInputStream != null) { throw new DockerClientException( "Only one of host resource or tar input stream should be defined to perform the copy, not both"); } Path toUpload = null; try { toUpload = Files.createTempFile("docker-java", ".tar.gz"); CompressArchiveUtil.tar(Paths.get(hostResource), toUpload, true, dirChildrenOnly); this.tarInputStream = Files.newInputStream(toUpload); return super.exec(); } catch (IOException e) { throw new DockerClientException("Unable to perform tar on host resource " + this.hostResource, e); } finally { if (toUpload != null) { toUpload.toFile().delete(); } } } else if (this.tarInputStream == null) { throw new DockerClientException( "One of host resource or tar input stream must be defined to perform the copy"); } return super.exec(); }

Target:
public Void exec() throws NotFoundException { if (StringUtils.isNotEmpty(this.hostResource)) { if (this.tarInputStream != null) { throw new DockerClientException( "Only one of host resource or tar input stream should be defined to perform the copy, not both"); } Path toUpload = null; try { toUpload = Files.createTempFile("docker-java", ".tar.gz"); CompressArchiveUtil.tar(Paths.get(hostResource), toUpload, true, dirChildrenOnly); } catch (IOException createFileIOException) { if (toUpload != null) { toUpload.toFile().delete(); } throw new DockerClientException("Unable to perform tar on host resource " + this.hostResource, createFileIOException); } try (InputStream uploadStream = Files.newInputStream(toUpload)) { this.tarInputStream = uploadStream; return super.exec(); } catch (IOException e) { throw new DockerClientException("Unable to read temp file " + toUpload.toFile().getAbsolutePath(), e); } finally { toUpload.toFile().delete(); } } else if (this.tarInputStream == null) { throw new DockerClientException("One of host resource or tar input stream must be defined to perform the copy"); } return super.exec(); }