auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
boolean invoke(Object receiver, String methodName, String argument) { try { Method method = TextView.class.getMethod(methodName, mArgType); method.invoke(receiver, convertArgument(argument)); return true; } catch (NoSuchMethodException e) { LogUtil.w("Method with name " + methodName + " and argument of type " + mArgType.getSimpleName() + " not found"); } catch (InvocationTargetException e) { LogUtil.w("InvocationTargetException: " + e.getMessage()); } catch (IllegalAccessException e) { LogUtil.w("IllegalAccessException: " + e.getMessage()); } catch (IllegalArgumentException e) { LogUtil.w("IllegalArgumentException: " + e.getMessage()); } return false; }

Target:
boolean invoke(Object receiver, String methodName, String argument) { try { Method method = receiver.getClass().getMethod(methodName, mArgType); method.invoke(receiver, convertArgument(argument)); return true; } catch (NoSuchMethodException ignored) { } catch (InvocationTargetException e) { LogUtil.w("InvocationTargetException: " + e.getMessage()); } catch (IllegalAccessException e) { LogUtil.w("IllegalAccessException: " + e.getMessage()); } catch (IllegalArgumentException e) { LogUtil.w("IllegalArgumentException: " + e.getMessage()); } return false; }
Source:
protected List<String> buildRetrieveStatusCommand() { String cmd = "if test -s "+exitStatusPath+"; then"+"\n"+ " cat "+exitStatusPath+"\n"+ "elif test -s "+pidPath+"; then"+"\n"+ " pid=`cat "+pidPath+"`"+"\n"+ " if ! ps -p $pid > /dev/null < /dev/null; then"+"\n"+ " # no exit status, and not executing; give a few seconds grace in case just about to write exit status"+"\n"+ " sleep 3"+"\n"+ " if test -s "+exitStatusPath+"; then"+"\n"+ " cat "+exitStatusPath+""+"\n"+ " else"+"\n"+ " echo \"No exit status in a.exitstatus, and pid in a.pid ($pid) not executing\""+"\n"+ " exit 1"+"\n"+ " fi"+"\n"+ " fi"+"\n"+ "else"+"\n"+ " echo \"No exit status in "+exitStatusPath+", and "+pidPath+" is empty\""+"\n"+ " exit 1"+"\n"+ "fi"+"\n"; MutableList.Builder<String> cmds = MutableList.<String>builder() .add((runAsRoot ? BashCommands.sudo(cmd) : cmd)) .add("RESULT=$?"); cmds.add("exit $RESULT"); return cmds.build(); }

Target:
protected List<String> buildRetrieveStatusCommand() { List<String> cmdParts = ImmutableList.of( "# Retrieve status", "if test -s "+exitStatusPath+"; then", " cat "+exitStatusPath, "elif test -s "+pidPath+"; then", " pid=`cat "+pidPath+"`", " if ! ps -p $pid > /dev/null < /dev/null; then", " # no exit status, and not executing; give a few seconds grace in case just about to write exit status", " sleep 3", " if test -s "+exitStatusPath+"; then", " cat "+exitStatusPath+"", " else", " echo \"No exit status in "+exitStatusPath+", and pid in "+pidPath+" ($pid) not executing\"", " exit 1", " fi", " fi", "else", " echo \"No exit status in "+exitStatusPath+", and "+pidPath+" is empty\"", " exit 1", "fi"+"\n"); String cmd = Joiner.on("\n").join(cmdParts); MutableList.Builder<String> cmds = MutableList.<String>builder() .add((runAsRoot ? BashCommands.sudo(cmd) : cmd)) .add("RESULT=$?"); cmds.add("exit $RESULT"); return cmds.build(); }
Source:
public void close() throws IOException { if ( treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED) ) { client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); executorService.close(); try { root.wasDeleted(); } catch ( Exception e ) { handleException(e); } } }

Target:
public void close() { if ( treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED) ) { client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); executorService.close(); try { root.wasDeleted(); } catch ( Exception e ) { handleException(e); } } }
Source:
public void handleDownload(HttpServletRequest req, HttpServletResponse resp, String baseUrl, String path) throws IOException { Pair<String, Action> pair = getDownloadPathAndAction(path); if (pair == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid URL syntax"); return; } String downloadPath = pair.getLeft(); Action action = pair.getRight(); switch (action) { case INFO: handleDownload(req, resp, downloadPath, baseUrl, true); break; case DOWNLOAD_FROM_DOC: handleDownload(req, resp, downloadPath, baseUrl, false); break; case DOWNLOAD: downloadBlob(req, resp, downloadPath, EVENT_NAME); break; default: resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid URL syntax"); } }

Target:
public void handleDownload(HttpServletRequest req, HttpServletResponse resp, String baseUrl, String path) throws IOException { Pair<String, Action> pair = getDownloadPathAndAction(path); if (pair == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid URL syntax"); return; } String downloadPath = pair.getLeft(); Action action = pair.getRight(); switch (action) { case INFO: handleDownload(req, resp, downloadPath, baseUrl, true); break; case DOWNLOAD_FROM_DOC: handleDownload(req, resp, downloadPath, baseUrl, false); break; case DOWNLOAD: downloadBlob(req, resp, downloadPath, "download"); break; default: resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid URL syntax"); } }
Source:
protected void onPostExecute(String result) { mLogTV.setText(result); dismissLoadingDialog(); }

Target:
protected void onPostExecute(String result) { if (textViewReference != null && result != null) { final TextView logTV = textViewReference.get(); if (logTV != null) { logTV.setText(result); dismissLoadingDialog(); } } }
Source:
public void doStart() throws MuleException { try { logger.debug("Starting subreceiver on queue: " + getQueueName() + " on channel: " + getChannel()); super.doStart(); channel = amqpConnector.getChannelHandler().getOrCreateChannel(endpoint); parentReceiver.declareEndpoint(channel); if (logger.isDebugEnabled()) { logger.debug("Connected queue: " + getQueueName() + " on channel: " + getChannel()); } if (endpoint.getTransactionConfig().isTransacted()) { channel.txSelect(); } queueName = parentReceiver.getQueueOrCreateTemporaryQueue(channel); consumerTag = channel.basicConsume(getQueueName(), amqpConnector.getAckMode().isAutoAck(), getClientConsumerTag(), amqpConnector.isNoLocal(), amqpConnector.isExclusiveConsumers(), null, new MessageReceiverConsumer(this, channel)); logger.info("Started subscription: " + consumerTag + " on " + (endpoint.getTransactionConfig().isTransacted() ? "transacted " : "") + "channel: " + channel); } catch (final Exception e) { try { amqpConnector.stop(); } catch (MuleException w) { logger.error("Unable to stop channel's connection"); } throw new StartException( MessageFactory.createStaticMessage("Error when subscribing to queue: " + getQueueName() + " on channel: " + channel), e, this); } logger.debug("Started subreceiver on queue: " + getQueueName() + " on channel: " + getChannel()); }

Target:
public void doStart() throws MuleException { try { logger.debug("Starting subreceiver on queue: " + getQueueName() + " on channel: " + getChannel()); super.doStart(); channel = amqpConnector.getChannelHandler().getOrCreateChannel(endpoint); parentReceiver.declareEndpoint(channel); if (logger.isDebugEnabled()) { logger.debug("Connected queue: " + getQueueName() + " on channel: " + getChannel()); } if (endpoint.getTransactionConfig().isTransacted()) { channel.txSelect(); } queueName = parentReceiver.getQueueOrCreateTemporaryQueue(channel); consumerTag = channel.basicConsume(getQueueName(), amqpConnector.getAckMode().isAutoAck(), getClientConsumerTag(), amqpConnector.isNoLocal(), amqpConnector.isExclusiveConsumers(), null, new MessageReceiverConsumer(this, channel)); logger.info("Started subscription: " + consumerTag + " on " + (endpoint.getTransactionConfig().isTransacted() ? "transacted " : "") + "channel: " + channel); } catch (final Exception e) { try { amqpConnector.stop(); } catch (MuleException w) { logger.error("Unable to stop amqp connector"); } throw new StartException( MessageFactory.createStaticMessage("Error when subscribing to queue: " + getQueueName() + " on channel: " + channel), e, this); } logger.debug("Started subreceiver on queue: " + getQueueName() + " on channel: " + getChannel()); }
Source:
private void executeQueryWithCriticalHeapCalledAfterTimeout(VM server, VM client) { createLatchTestHook(server, false, VM.getController()); AsyncInvocation queryExecution = executeQueryWithTimeout(client); try { Thread.sleep(1 + TEST_QUERY_TIMEOUT); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } vmHitsCriticalHeap(server); releaseHook(server); try { assertThat(queryExecution.get(60, SECONDS)).isEqualTo(0); } catch (Throwable e) { e.printStackTrace(); fail("queryExecution.getResult() threw Exception " + e.toString()); } }

Target:
private void executeQueryWithCriticalHeapCalledAfterTimeout(VM server, VM client) throws InterruptedException { createLatchTestHook(server, false, VM.getController()); AsyncInvocation queryExecution = executeQueryWithTimeout(client); Thread.sleep(1 + TEST_QUERY_TIMEOUT); vmHitsCriticalHeap(server); releaseHook(server); await().untilAsserted(() -> assertThat(queryExecution.get()).isEqualTo(0)); }
Source:
public static long unzipNoGuava( final Path zip, final Configuration configuration, final File outDir, final Progressable progressable, final RetryPolicy retryPolicy ) throws IOException { final RetryPolicy effectiveRetryPolicy; if (retryPolicy == null) { effectiveRetryPolicy = RetryPolicies.exponentialBackoffRetry( NUM_RETRIES, SECONDS_BETWEEN_RETRIES, TimeUnit.SECONDS ); } else { effectiveRetryPolicy = retryPolicy; } final DataPusher zipPusher = (DataPusher) RetryProxy.create( DataPusher.class, new DataPusher() { @Override public long push() throws IOException { try { final FileSystem fileSystem = zip.getFileSystem(configuration); long size = 0L; final byte[] buffer = new byte[1 << 13]; progressable.progress(); try (ZipInputStream in = new ZipInputStream(fileSystem.open(zip, 1 << 13))) { for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) { final String fileName = entry.getName(); final String outputPath = outDir.getAbsolutePath() + File.separator + fileName; CompressionUtils.validateZipOutputFile( zip.getName(), new File(outputPath), outDir ); try (final OutputStream out = new BufferedOutputStream( new FileOutputStream(outputPath), 1 << 13 )) { for (int len = in.read(buffer); len >= 0; len = in.read(buffer)) { progressable.progress(); if (len == 0) { continue; } size += len; out.write(buffer, 0, len); } out.flush(); } } } progressable.progress(); return size; } catch (IOException | RuntimeException exception) { log.error(exception, "Exception in unzip retry loop"); throw exception; } } }, effectiveRetryPolicy ); return zipPusher.push(); }

Target:
public static long unzipNoGuava( final Path zip, final Configuration configuration, final File outDir, final Progressable progressable, final RetryPolicy retryPolicy ) throws IOException { final RetryPolicy effectiveRetryPolicy; if (retryPolicy == null) { effectiveRetryPolicy = RetryPolicies.exponentialBackoffRetry( NUM_RETRIES, SECONDS_BETWEEN_RETRIES, TimeUnit.SECONDS ); } else { effectiveRetryPolicy = retryPolicy; } final DataPusher zipPusher = (DataPusher) RetryProxy.create( DataPusher.class, new DataPusher() { @Override public long push() throws IOException { try { final FileSystem fileSystem = zip.getFileSystem(configuration); long size = 0L; final byte[] buffer = new byte[1 << 13]; progressable.progress(); try (ZipInputStream in = new ZipInputStream(fileSystem.open(zip, 1 << 13))) { for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) { final String fileName = entry.getName(); final String outputPath = new File(outDir, fileName).getAbsolutePath(); CompressionUtils.validateZipOutputFile(zip.getName(), new File(outputPath), outDir); try (final OutputStream out = new BufferedOutputStream(new FileOutputStream(outputPath))) { for (int len = in.read(buffer); len >= 0; len = in.read(buffer)) { progressable.progress(); if (len == 0) { continue; } size += len; out.write(buffer, 0, len); } out.flush(); } } } progressable.progress(); return size; } catch (IOException | RuntimeException exception) { log.error(exception, "Exception in unzip retry loop"); throw exception; } } }, effectiveRetryPolicy ); return zipPusher.push(); }
Source:
public static void input(@AggregationState DigestAndPercentileArrayState state, @SqlType(StandardTypes.DOUBLE) double value, @SqlType(StandardTypes.DOUBLE) double lowerQuantile, @SqlType(StandardTypes.DOUBLE) double upperQuantile) { ApproximateDoublePercentileArrayAggregations.input(state, value, ApproximateLongTruncatedMeanAggregations.quantileBoundsToArray(lowerQuantile, upperQuantile)); }

Target:
public static void input( @AggregationState DigestAndPercentileArrayState state, @SqlType(StandardTypes.DOUBLE) double value, @SqlType(StandardTypes.DOUBLE) double lowerQuantile, @SqlType(StandardTypes.DOUBLE) double upperQuantile) { ApproximateDoublePercentileArrayAggregations.input(state, value, quantileBoundsToArray(lowerQuantile, upperQuantile)); }
Source:
private Map<String, DbParameterAccessor> readIntoParams( String tableOrViewName, String query) throws SQLException { try (PreparedStatement dc = getConnection().prepareStatement(query)) { dc.setString(1, tableOrViewName); ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String columnName = rs.getString(1); String dataType = rs.getString(2); DbParameterAccessor dbp = new DbParameterAccessor(columnName, Direction.INPUT, typeMapper.getJDBCSQLTypeForDBType(dataType), getJavaClass(dataType), position++, typeSpecifiers); allParams.put(NameNormaliser.normaliseName(columnName), dbp); } rs.close(); return allParams; } }

Target:
private Map<String, DbParameterAccessor> readIntoParams( String tableOrViewName, String query) throws SQLException { try (PreparedStatement dc = getConnection().prepareStatement(query)) { dc.setString(1, tableOrViewName); ResultSet rs = dc.executeQuery(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; while (rs.next()) { String columnName = rs.getString(1); String dataType = rs.getString(2); DbParameterAccessor dbp = createDbParameterAccessor( columnName, Direction.INPUT, typeMapper.getJDBCSQLTypeForDBType(dataType), getJavaClass(dataType), position++); allParams.put(NameNormaliser.normaliseName(columnName), dbp); } rs.close(); return allParams; } }
Source:
public static Collection<String> getAllPackagesInDirectory(@Nullable final PsiDirectory dir) { if (dir == null) { return Collections.emptyList(); } return CachedValuesManager.getCachedValue(dir, new CachedValueProvider<Collection<String>>() { @Nullable @Override public Result<Collection<String>> compute() { Collection<String> set = ContainerUtil.newLinkedHashSet(); for (PsiFile file : dir.getFiles()) { if (allowed(file)) { String name = ((GoFile)file).getPackageName(); if (name != null) { set.add(name); } } } return Result.create(set, dir); } }); }

Target:
public static Collection<String> getAllPackagesInDirectory(@Nullable final PsiDirectory dir) { if (dir == null) { return Collections.emptyList(); } return CachedValuesManager.getCachedValue(dir, new CachedValueProvider<Collection<String>>() { @Nullable @Override public Result<Collection<String>> compute() { Collection<String> set = ContainerUtil.newLinkedHashSet(); for (PsiFile file : dir.getFiles()) { if (file instanceof GoFile && !libraryDirectoryToIgnore(file.getName())) { String name = ((GoFile)file).getPackageName(); if (name != null) { set.add(name); } } } return Result.create(set, dir); } }); }
Source:
private void add(Point point) throws IllegalStateException { if (done) { throw new IllegalStateException("Computation of spherical excess has already been performed"); } double phi = toRadians(point.getY()); double tan = Math.tan(phi / 2); double longitude = toRadians(point.getX()); if (longitude == previousLongitude && phi == previousPhi) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Polygon is not valid: it has two identical consecutive vertices"); } double deltaLongitude = longitude - previousLongitude; sphericalExcess += 2 * Math.atan2(Math.tan(deltaLongitude / 2) * (previousTan + tan), 1 + previousTan * tan); double cos = Math.cos(phi); double sin = Math.sin(phi); double sinOfDeltaLongitude = Math.sin(deltaLongitude); double cosOfDeltaLongitude = Math.cos(deltaLongitude); double y = sinOfDeltaLongitude * cos; double x = previousCos * sin - previousSin * cos * cosOfDeltaLongitude; double initialBearing = (Math.atan2(y, x) + TWO_PI) % TWO_PI; double finalY = -sinOfDeltaLongitude * previousCos; double finalX = previousSin * cos - previousCos * sin * cosOfDeltaLongitude; double finalBearing = (Math.atan2(finalY, finalX) + PI) % TWO_PI; if (firstPoint) { firstInitialBearing = initialBearing; firstPoint = false; } else { courseDelta += (initialBearing - previousFinalBearing + THREE_PI) % TWO_PI - PI; } courseDelta += (finalBearing - initialBearing + THREE_PI) % TWO_PI - PI; previousFinalBearing = finalBearing; previousCos = cos; previousSin = sin; previousPhi = phi; previousTan = tan; previousLongitude = longitude; }

Target:
private void add(Point point) throws IllegalStateException { checkState(!done, "Computation of spherical excess is complete"); double phi = toRadians(point.getY()); double tan = Math.tan(phi / 2); double longitude = toRadians(point.getX()); if (longitude == previousLongitude && phi == previousPhi) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Polygon is not valid: it has two identical consecutive vertices"); } double deltaLongitude = longitude - previousLongitude; sphericalExcess += 2 * Math.atan2(Math.tan(deltaLongitude / 2) * (previousTan + tan), 1 + previousTan * tan); double cos = Math.cos(phi); double sin = Math.sin(phi); double sinOfDeltaLongitude = Math.sin(deltaLongitude); double cosOfDeltaLongitude = Math.cos(deltaLongitude); double y = sinOfDeltaLongitude * cos; double x = previousCos * sin - previousSin * cos * cosOfDeltaLongitude; double initialBearing = (Math.atan2(y, x) + TWO_PI) % TWO_PI; double finalY = -sinOfDeltaLongitude * previousCos; double finalX = previousSin * cos - previousCos * sin * cosOfDeltaLongitude; double finalBearing = (Math.atan2(finalY, finalX) + PI) % TWO_PI; if (firstPoint) { firstInitialBearing = initialBearing; firstPoint = false; } else { courseDelta += (initialBearing - previousFinalBearing + THREE_PI) % TWO_PI - PI; } courseDelta += (finalBearing - initialBearing + THREE_PI) % TWO_PI - PI; previousFinalBearing = finalBearing; previousCos = cos; previousSin = sin; previousPhi = phi; previousTan = tan; previousLongitude = longitude; }
Source:
private void updateOldSelection(ListView<DetailsListElement<E>> container, ListWidgetSelection<E> oldSelection) { Optional.ofNullable(oldSelection).map(ListWidgetSelection::getSelection).ifPresent(selection -> { final int oldValueIndex = getControl().getElements().indexOf(selection); if (oldValueIndex != -1) { container.getSelectionModel().clearSelection(oldValueIndex); } }); }

Target:
private void updateOldSelection(ListView<DetailsListElement<E>> container, ListWidgetSelection<E> oldSelection) { Optional.ofNullable(oldSelection).map(ListWidgetSelection::getSelection).ifPresent(selection -> { final int oldValueIndex = getControl().getElements().indexOf(selection); if (mappedElements.size() > oldValueIndex && oldValueIndex != -1) { container.getSelectionModel().clearSelection(oldValueIndex); } }); }
Source:
@Test public void multipleParameters() throws IOException { String expected = "@com.example.Thing(name = \"Hello, world!\", value = 42)"; writer.setMember("name", "Hello, world!"); writer.setMember("value", 42); String actual = writer.write(new StringBuilder(), context).toString(); assertThat(actual).isEqualTo(expected); }

Target:
@Test public void multipleParameters() throws IOException { String expected = "@com.example.Thing(name = \"Hello, world!\", value = 42)"; writer.setMember("name", "Hello, world!"); writer.setMember("value", 42); assertThat(Writables.writeToString(writer)).isEqualTo(expected); }
Source:
public void cleanup() { labelsWidget.cleanup(); driver.cleanup(); }

Target:
public void cleanup() { driver.cleanup(); }
Source:
public void countError(CoordinatorOperationType operation, CoordinatorError error) { operationExceptionRate.mark(); switch (error) { case UnexpectedInternalError: updateOperationMetric(operation); unexpectedInternalError.inc(); break; case BlobAlreadyExistInLocalColo: updateOperationMetric(operation); blobAlreadyExistInLocalColoError.inc(); break; case BlobAlreadyExistInRemoteColo: updateOperationMetric(operation); blobAlreadyExistInRemoteColoError.inc(); break; case AmbryUnavailable: updateOperationMetric(operation); ambryUnavailableError.inc(); break; case OperationTimedOut: updateOperationMetric(operation); operationTimedOutError.inc(); break; case InvalidBlobId: updateOperationMetric(operation); invalidBlobIdError.inc(); break; case InvalidPutArgument: updateOperationMetric(operation); invalidPutArgumentError.inc(); break; case InsufficientCapacity: updateOperationMetric(operation); insufficientCapacityError.inc(); break; case BlobTooLarge: updateOperationMetric(operation); blobTooLargeError.inc(); break; case BlobDoesNotExist: blobDoesNotExistError.inc(); break; case BlobDeleted: blobDeletedError.inc(); break; case BlobExpired: blobExpiredError.inc(); break; default: updateOperationMetric(operation); logger.warn("Unknown CoordinatorError being counted: " + error); unknownError.inc(); break; } }

Target:
public void countError(CoordinatorOperationType operation, CoordinatorError error) { operationExceptionRate.mark(); switch (error) { case UnexpectedInternalError: updateOperationMetric(operation); unexpectedInternalError.inc(); break; case AmbryUnavailable: updateOperationMetric(operation); ambryUnavailableError.inc(); break; case OperationTimedOut: updateOperationMetric(operation); operationTimedOutError.inc(); break; case InvalidBlobId: updateOperationMetric(operation); invalidBlobIdError.inc(); break; case InvalidPutArgument: updateOperationMetric(operation); invalidPutArgumentError.inc(); break; case InsufficientCapacity: updateOperationMetric(operation); insufficientCapacityError.inc(); break; case BlobTooLarge: updateOperationMetric(operation); blobTooLargeError.inc(); break; case BlobDoesNotExist: blobDoesNotExistError.inc(); break; case BlobDeleted: blobDeletedError.inc(); break; case BlobExpired: blobExpiredError.inc(); break; default: updateOperationMetric(operation); logger.warn("Unknown CoordinatorError being counted: " + error); unknownError.inc(); break; } }
Source:
boolean isSuccessful() { return isComplete() && failedEvents.size() == 0; }

Target:
boolean isSuccessful() { return isComplete() && failedEvents.isEmpty(); }
Source:
public Target onboard( @NonNull String thingID, @NonNull String thingPassword) throws ThingIFException { return thingIfApi.onboard(thingID, thingPassword); }

Target:
public Target onboard( @NonNull String thingID, @NonNull String thingPassword) throws ThingIFException { return this.thingIfApi.onboard(thingID, thingPassword); }
Source:
private void configureRemoteStream() { try { LOG.debug("Setting up remote stream"); RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName(zeppelinConfiguration.getZeppelinNotebookGitRemoteOrigin()); remoteAddCommand.setUri(new URIish(zeppelinConfiguration.getZeppelinNotebookGitURL())); remoteAddCommand.call(); } catch (GitAPIException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } }

Target:
private void configureRemoteStream() { try { LOG.debug("Setting up remote stream"); RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName(zeppelinConfiguration.getZeppelinNotebookGitRemoteOrigin()); remoteAddCommand.setUri(new URIish(zeppelinConfiguration.getZeppelinNotebookGitURL())); remoteAddCommand.call(); } catch (GitAPIException e) { LOG.error("Error configuring GitHub", e); } catch (URISyntaxException e) { LOG.error("Error in GitHub URL provided", e); } }
Source:
public JsonDeserializer() { this(Collections.emptySet(), false); }

Target:
public JsonDeserializer() { this(Collections.emptySet(), JsonNodeFactory.withExactBigDecimals(true)); }
Source:
public FeaturePath getFeaturePath(String propertyPath) { String[] featureNames = propertyPath.split("\\."); EStructuralFeature[] features = new EStructuralFeature[featureNames.length]; int i = 0; EClass currentClass = source.eClass(); for (String featureName : featureNames) { featureName = featureName.replaceAll("\\s", ""); EStructuralFeature feature = currentClass.getEStructuralFeature(featureName); features[i++] = feature; if (i < featureNames.length) { if (feature instanceof EReference) { EReference reference = (EReference) feature; EClassifier type = reference.getEType(); if (type instanceof EClass) { currentClass = (EClass) type; continue; } } Activator.log.warn("Cannot find feature path " + propertyPath + " for EClass " + source.eClass()); return null; } } return FeaturePath.fromList(features); }

Target:
public FeaturePath getFeaturePath(String propertyPath) { String[] featureNames = propertyPath.split("\\."); EStructuralFeature[] features = new EStructuralFeature[featureNames.length]; int i = 0; EClass currentClass = source.eClass(); for (String featureName : featureNames) { featureName = featureName.replaceAll("\\s", ""); EStructuralFeature feature = currentClass.getEStructuralFeature(featureName); features[i++] = feature; if (i < featureNames.length) { if (feature instanceof EReference) { EReference reference = (EReference) feature; EClassifier type = reference.getEType(); if (type instanceof EClass) { currentClass = (EClass) type; continue; } } final StringBuilder warningMessage = new StringBuilder("Cannot find feature path "); warningMessage.append(propertyPath); warningMessage.append(" for EClass "); warningMessage.append(source.eClass()); Activator.log.warn(warningMessage.toString()); return null; } } return FeaturePath.fromList(features); }
Source:
@Test public void testRequestResponseApiError() throws Throwable { enqueueFromFile("api_error.json"); CreateAccountClient.Callback cb = mock(CreateAccountClient.Callback.class); Call<MwCreateAccountResponse> call = request(cb); server().takeRequest(); assertCallbackThrowableFailure(call, cb); }

Target:
@Test public void testRequestResponseApiError() throws Throwable { enqueueFromFile("api_error.json"); CreateAccountClient.Callback cb = mock(CreateAccountClient.Callback.class); Call<CreateAccountResponse> call = request(cb); server().takeRequest(); assertCallbackFailure(call, cb, MwApiErrorException.class); }
Source:
private boolean isMbusDeviceCoupled(final SmartMeter mbusDevice) { if (mbusDevice.getChannel() == null) { return false; } else { return true; } }

Target:
private boolean isMbusDeviceCoupled(final SmartMeter mbusDevice) { return mbusDevice.getChannel() == null; }
Source:
protected ByteBuf prepareDecompressBuffer(ChannelHandlerContext ctx, ByteBuf buffer, int preferredSize) { if (buffer == null) { if (maxAllocation == 0) { return ctx.alloc().heapBuffer(preferredSize); } else { return ctx.alloc().heapBuffer(Math.min(preferredSize, maxAllocation), maxAllocation); } } if (buffer.ensureWritable(preferredSize, true) == 1) { return maxAllocationReached(buffer); } return buffer; }

Target:
protected ByteBuf prepareDecompressBuffer(ChannelHandlerContext ctx, ByteBuf buffer, int preferredSize) { if (buffer == null) { if (maxAllocation == 0) { return ctx.alloc().heapBuffer(preferredSize); } return ctx.alloc().heapBuffer(Math.min(preferredSize, maxAllocation), maxAllocation); } if (buffer.ensureWritable(preferredSize, true) == 1) { decompressionBufferExhausted(buffer.duplicate()); buffer.skipBytes(buffer.readableBytes()); throw new DecompressionException("Decompression buffer has reached maximum size: " + buffer.maxCapacity()); } return buffer; }
Source:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; for (int i = 0; i < localTime_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, localTime_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }

Target:
public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < localTime_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, localTime_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; }
Source:
public void testPosixConnectionWithInvalidMountOptions() { StorageServerConnections conn =createConnection(StorageType.POSIXFS, "timeo=30, vfs_type=nfs"); params.setStorageServerConnection(conn); ValidationResult result = command.validateMountOptions(); assertFalse(result.isValid()); }

Target:
public void testPosixConnectionWithInvalidMountOptions() { testConnectionMountOptionsValidations(StorageType.POSIXFS, "timeo=30, vfs_type=nfs", false); }
Source:
public Object execute(ExecutionEvent arg0) { IProject project = null; ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); if (selection instanceof IStructuredSelection) { Object item = ((IStructuredSelection)selection).getFirstElement(); if (item instanceof IProject) { project = (IProject)item; } else if (item instanceof IAdaptable) { project = ((IAdaptable)item).getAdapter(IProject.class); } } if (project == null) { return null; } SmartImportWizard wizard = new SmartImportWizard(); wizard.setInitialImportSource(project.getLocation().toFile()); Set<IWorkingSet> workingSets = new HashSet<>(); for (IWorkingSet workingSet : PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets()) { for (IAdaptable element : workingSet.getElements()) { if (project.getAdapter(element.getClass()) == element) { workingSets.add(workingSet); } } } wizard.setInitialWorkingSets(workingSets); return new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), wizard).open(); }

Target:
public Object execute(ExecutionEvent arg0) { IProject project = null; ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); if (selection instanceof IStructuredSelection) { Object item = ((IStructuredSelection)selection).getFirstElement(); project = Adapters.adapt(item, IProject.class); } if (project == null) { return null; } SmartImportWizard wizard = new SmartImportWizard(); wizard.setInitialImportSource(project.getLocation().toFile()); Set<IWorkingSet> workingSets = new HashSet<>(); for (IWorkingSet workingSet : PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets()) { for (IAdaptable element : workingSet.getElements()) { if (project.getAdapter(element.getClass()) == element) { workingSets.add(workingSet); } } } wizard.setInitialWorkingSets(workingSets); return new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), wizard).open(); }
Source:
public void onBackPressed() { if (isPhotoPickerShowing()) { hidePhotoPicker(); } handleBackPressed(); }

Target:
public void onBackPressed() { if (isPhotoPickerShowing()) { hidePhotoPicker(); return; } handleBackPressed(); }
Source:
private void checkForFullyLostDatasets(Set<IntermediateDataSetID> dataSetsWithLostPartitions) { dataSetsWithLostPartitions.forEach(dataSetId -> { if (getHostingTaskExecutors(dataSetId).isEmpty()) { LOG.debug("There are no longer partitions being tracked for dataset {}.", dataSetId); dataSetMetaInfo.remove(dataSetId); Optional.ofNullable(partitionReleaseCompletionFutures.get(dataSetId)).map(future -> future.complete(null)); } }); }

Target:
private void checkForFullyLostDatasets(Set<IntermediateDataSetID> dataSetsWithLostPartitions) { dataSetsWithLostPartitions.forEach(dataSetId -> { if (getHostingTaskExecutors(dataSetId).isEmpty()) { LOG.debug("There are no longer partitions being tracked for dataset {}.", dataSetId); dataSetMetaInfo.remove(dataSetId); Optional.ofNullable(partitionReleaseCompletionFutures.remove(dataSetId)).map(future -> future.complete(null)); } }); }
Source:
private JestClient createJestClient(String connectionUrl, String username, String password) { log.info("Create a jest elastic search client for connection url [{}]", connectionUrl); JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig( new HttpClientConfig.Builder(connectionUrl) .defaultCredentials(username, password) .multiThreaded(true) .build()); return factory.getObject(); }

Target:
private JestClient createJestClient(String connectionUrl, String username, String password) { log.info("Create a jest elastic search client for connection url [{}]", connectionUrl); JestClientFactory factory = new JestClientFactory(); HttpClientConfig.Builder httpClientBuilder = new HttpClientConfig.Builder(connectionUrl).connTimeout(connTimeout).readTimeout(readTimeout).multiThreaded(true); if (StringUtils.isNotEmpty(username)) { httpClientBuilder.defaultCredentials(username, password); } factory.setHttpClientConfig(httpClientBuilder.build()); return factory.getObject(); }
Source:
public MetricRegistry getMetrics() { return metrics != null ? metrics : new MetricRegistry(); }

Target:
public MetricRegistry getMetrics() { if(metrics == null) { metrics = new MetricRegistry(); } return metrics; }
Source:
public synchronized void deleteOldLogs() throws IOException { if (maxAge <= 0) { logDebug("maxage feature is disabled."); return; } Path prefixPath = Paths.get(prefix); Path logNamePath = prefixPath.subpath(prefixPath.getNameCount() - 1, prefixPath.getNameCount()); String rotatedLogRegex = ".*" + logNamePath.toString() + ".+\\" + suffix + "\\" + compressedSuffix; long currentSystemTime = System.currentTimeMillis(); try { Files.find(prefixPath.getParent(), DEF_MAXDEPTH, (path, attributes) -> path.toString().matches(rotatedLogRegex) && attributes.isRegularFile() && currentSystemTime - attributes.lastModifiedTime().toMillis() >= maxAge) .forEach(path -> { try { Files.delete(path); } catch (IOException e) { e.printStackTrace(System.err); } }); } catch (IOException e) { e.printStackTrace(System.err); } }

Target:
public synchronized void deleteOldLogs() throws IOException { if (maxAge <= 0) { logDebug("maxage feature is disabled."); return; } Path logBasePath = Paths.get(prefix).getParent(); long currentSystemTime = System.currentTimeMillis(); try { Files.find(logBasePath, DEF_MAXDEPTH, (path, attributes) -> path.getFileName().toString().matches(deleteRegex) && attributes.isRegularFile() && currentSystemTime - attributes.lastModifiedTime().toMillis() >= maxAge) .forEach(path -> { try { Files.delete(path); } catch (IOException e) { e.printStackTrace(System.err); } }); } catch (IOException e) { e.printStackTrace(System.err); } }
Source:
public ScheduleCriteria(@JsonProperty("schedule") Schedule schedule, @JsonProperty("criteria") Criteria criteria) { checkNotNull(schedule); this.schedule = schedule; this.criteria = criteria; }

Target:
public ScheduleCriteria(@JsonProperty("schedule") Schedule schedule, @JsonProperty("criteria") Criteria criteria) { checkNotNull(schedule); checkNotNull(criteria); this.schedule = schedule; this.criteria = criteria; }
Source:
public void AESGCM_Encryption_Test_Correct_Encryption_And_Decryption() throws IOException, AEADBadTagException { AccumuloConfiguration conf = setAndGetAccumuloConfig(CRYPTO_ON_CONF); byte[] encryptedBytes = testEncryption(conf, new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20}); Integer result = testDecryption(conf, encryptedBytes); assert (result.equals(1)); }

Target:
public void AESGCM_Encryption_Test_Correct_Encryption_And_Decryption() throws IOException, AEADBadTagException { AccumuloConfiguration conf = setAndGetAccumuloConfig(CRYPTO_ON_CONF); byte[] encryptedBytes = testEncryption(conf, new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20}); Integer result = testDecryption(conf, encryptedBytes); assertEquals(result, Integer.valueOf(1)); }
Source:
public void reportIsHealthyWhenEverythingIsRight() { FeedbackHandler feedbackHandler = new FeedbackHandler(); EndpointStatistics statistics = EndpointStatistics .builder() .p99(P_99 - 1) .oneMin(RATE + 1) .errorRate(0) .build(); PointHealthStatusReport healthStatusForMetric = feedbackHandler.getHealthStatusForMetric( CLIENT_1, statistics, Constants.LEADER_TIME_SERVICE_LEVEL_OBJECTIVES); assertThat(healthStatusForMetric.status()).isEqualTo(HealthStatus.HEALTHY); assertThat(healthStatusForMetric.message().isPresent()).isFalse(); }

Target:
public void reportIsHealthyWhenEverythingIsRight() { FeedbackHandler feedbackHandler = new FeedbackHandler(); EndpointStatistics statistics = EndpointStatistics .builder() .p99(P_99 - 1) .oneMin(RATE + 1) .errorRate(0) .build(); HealthStatus healthStatus = getHealthStatus(feedbackHandler, statistics); assertThat(healthStatus).isEqualTo(HealthStatus.HEALTHY); }
Source:
public void getTextFromPart_withUnknownEncoding_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), "unknown encoding"); part.setBody(body); assertNull(MessageExtractor.getTextFromPart(part)); }

Target:
public void getTextFromPart_withUnknownEncoding_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), "unknown encoding"); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertNull(result); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NetworkFilter that = (NetworkFilter) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version) && Objects.equals(id, that.id); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NetworkFilter that = (NetworkFilter) o; return Objects.equals(name, that.name) && Objects.equals(version, that.version) && Objects.equals(id, that.id); }
Source:
private void forEach(InputObjectState uids, Consumer<Uid> consumer) { do { try { Uid uid = new Uid(uids.unpackBytes()); if (uid.equals(Uid.nullUid())) { return; } consumer.accept(uid); } catch (IOException e) { if (LRALogger.logger.isTraceEnabled()) { LRALogger.logger.tracef( "LRARecoverModule: Exception while unpacking records of type %s", _transactionType, e); } else if (LRALogger.logger.isInfoEnabled()) { LRALogger.logger.infof("LRARecoverModule: Exception while unpacking records of type: %s", e.getMessage()); } return; } } while (true); }

Target:
private void forEach(InputObjectState uids, Consumer<Uid> consumer) { do { try { Uid uid = new Uid(uids.unpackBytes()); if (uid.equals(Uid.nullUid())) { return; } consumer.accept(uid); } catch (IOException e) { if (LRALogger.logger.isTraceEnabled()) { LRALogger.logger.tracef(e, "LRARecoverModule: Object store exception %s while unpacking a record of type %s", e.getMessage(), _transactionType); } else if (LRALogger.logger.isInfoEnabled()) { LRALogger.logger.infof( "LRARecoverModule: Object store exception %s while unpacking a record of type: %s", e.getMessage()); } return; } } while (true); }
Source:
private static void asyncRename( HdfsEnvironment hdfsEnvironment, ListeningExecutorService executor, AtomicBoolean cancelled, List<ListenableFuture<?>> fileRenameFutures, HdfsContext context, Path currentPath, Path targetPath, List<String> fileNames) { FileSystem fileSystem = getFileSystem(hdfsEnvironment, context, currentPath); for (String fileName : fileNames) { Path source = new Path(currentPath, fileName); Path target = new Path(targetPath, fileName); fileRenameFutures.add(executor.submit(() -> renameFile(fileSystem, source, target, cancelled::get))); } }

Target:
private static void asyncRename( HdfsEnvironment hdfsEnvironment, ListeningExecutorService executor, AtomicBoolean cancelled, List<ListenableFuture<?>> fileRenameFutures, HdfsContext context, Path currentPath, Path targetPath, List<String> fileNames) { FileSystem fileSystem = getFileSystem(hdfsEnvironment, context, currentPath); for (String fileName : fileNames) { Path source = new Path(currentPath, fileName); Path target = new Path(targetPath, fileName); fileRenameFutures.add(executor.submit(() -> { if (cancelled.get()) { return; } renameFile(fileSystem, source, target); })); } }
Source:
public void testToDateWithIncorrectFormatPattern() throws Exception { String sqlText = "values to_date('2018-12','MM-DDD')"; try (ResultSet rs = methodWatcher.executeQuery(sqlText)) { fail("Expected exception the syntax of the string representation of a datetime value is incorrect"); } catch (SQLDataException e) { assertEquals("The syntax of the string representation of a datetime value is incorrect.", e.getLocalizedMessage()); } }

Target:
public void testToDateWithIncorrectFormatPattern() throws Exception { String sqlText = "values to_date('2018-12','MM-DDD')"; try (ResultSet rs = methodWatcher.executeQuery(sqlText)) { fail("Expected exception the syntax of the string representation of a datetime value is incorrect"); } catch (SQLDataException e) { assertEquals("22007", e.getSQLState()); } }
Source:
public static TimeLockAgent create(MetricsManager metricsManager, TimeLockInstallConfiguration install, Supplier<TimeLockRuntimeConfiguration> runtime, UserAgent userAgent, int threadPoolSize, long blockingTimeoutMs, Consumer<Object> registrar, Optional<Consumer<UndertowService>> undertowRegistrar, OrderableSlsVersion timeLockVersion) { TimeLockDialogueServiceProvider timeLockDialogueServiceProvider = createTimeLockDialogueServiceProvider( metricsManager, install, userAgent); PaxosResourcesFactory.TimelockPaxosInstallationContext installationContext = ImmutableTimelockPaxosInstallationContext .of(install, userAgent, timeLockDialogueServiceProvider, timeLockVersion); PaxosResources paxosResources = PaxosResourcesFactory.create( installationContext, metricsManager, Suppliers.compose(TimeLockRuntimeConfiguration::paxos, runtime::get)); PersistedSchemaVersion persistedSchemaVersion = PersistedSchemaVersion .create(installationContext.sqliteDataSource()); persistedSchemaVersion.upgradeVersion(SCHEMA_VERSION); verifySchemaVersion(persistedSchemaVersion); TimeLockAgent agent = new TimeLockAgent( metricsManager, install, runtime, undertowRegistrar, threadPoolSize, blockingTimeoutMs, registrar, paxosResources, userAgent, persistedSchemaVersion, installationContext.sqliteDataSource()); agent.createAndRegisterResources(); return agent; }

Target:
public static TimeLockAgent create( MetricsManager metricsManager, TimeLockInstallConfiguration install, Supplier<TimeLockRuntimeConfiguration> runtime, UserAgent userAgent, int threadPoolSize, long blockingTimeoutMs, Consumer<Object> registrar, Optional<Consumer<UndertowService>> undertowRegistrar, OrderableSlsVersion timeLockVersion) { TimeLockDialogueServiceProvider timeLockDialogueServiceProvider = createTimeLockDialogueServiceProvider(metricsManager, install, userAgent); PaxosResourcesFactory.TimelockPaxosInstallationContext installationContext = ImmutableTimelockPaxosInstallationContext.of( install, userAgent, timeLockDialogueServiceProvider, timeLockVersion); PersistedSchemaVersion persistedSchemaVersion = PersistedSchemaVersion.create(installationContext.sqliteDataSource()); persistedSchemaVersion.upgradeVersion(SCHEMA_VERSION); verifySchemaVersion(persistedSchemaVersion); PaxosResources paxosResources = PaxosResourcesFactory.create( installationContext, metricsManager, Suppliers.compose(TimeLockRuntimeConfiguration::paxos, runtime::get)); TimeLockAgent agent = new TimeLockAgent( metricsManager, install, runtime, undertowRegistrar, threadPoolSize, blockingTimeoutMs, registrar, paxosResources, userAgent, persistedSchemaVersion, installationContext.sqliteDataSource()); agent.createAndRegisterResources(); return agent; }
Source:
public VirtualFile[] getFiles(String s) throws TranslatorException { if (s == null || s.isEmpty()) { return null; } if(s3Client.doesObjectExist(s3Config.getBucket(), s)){ ListObjectsRequest listObjectsRequest = new ListObjectsRequest() .withBucketName(s3Config.getBucket()) .withPrefix(s); ObjectListing objectListing = s3Client.listObjects(listObjectsRequest); return new VirtualFile[] {new S3VirtualFile(s3Client, objectListing.getObjectSummaries().get(0), s3Config)}; } if(isDirectory(s)){ if(!s.endsWith(SLASH)) { s += SLASH; } return convert(s); } String parentPath; if(s.contains(SLASH)) { parentPath = s.substring(0, s.lastIndexOf(SLASH) + 1); } else { parentPath = ""; } if(!isDirectory(parentPath)) { return null; } if(s.contains(STAR)) { return globSearch(parentPath, s); } return null; }

Target:
public VirtualFile[] getFiles(String s) throws TranslatorException { if (s == null) { return null; } if(s3Client.doesObjectExist(s3Config.getBucket(), s)){ ListObjectsRequest listObjectsRequest = new ListObjectsRequest() .withBucketName(s3Config.getBucket()) .withPrefix(s); ObjectListing objectListing = s3Client.listObjects(listObjectsRequest); return new VirtualFile[] {new S3VirtualFile(s3Client, objectListing.getObjectSummaries().get(0), s3Config)}; } if(isDirectory(s)){ if(!s.isEmpty() && !s.endsWith(SLASH)) { s += SLASH; } return convert(s); } String parentPath = ""; if(s.contains(SLASH)) { parentPath = s.substring(0, s.lastIndexOf(SLASH) + 1); } if(!isDirectory(parentPath)) { return null; } if(s.contains(STAR)) { return globSearch(parentPath, s); } return null; }
Source:
protected void activate(ComponentContext context) { TenantMgtService tenantMgt = new TenantMgtImpl(); context.getBundleContext().registerService(TenantMgtService.class.getName(), tenantMgt, null); if (log.isDebugEnabled()) { log.debug("*************Tenant management component is activated.**************"); } }

Target:
protected void activate(ComponentContext context) { TenantMgtService tenantMgt = new TenantMgtImpl(); context.getBundleContext().registerService(TenantMgtService.class.getName(), tenantMgt, null); if (log.isDebugEnabled()) { log.debug("Tenant management component is activated."); } }
Source:
public void serveNotFoundIndexHtml_requestWithRootPath_failsWithIOException() { VaadinServletRequest vaadinServletRequest = createVaadinRequest("/"); VaadinService vaadinService = vaadinServletRequest.getService(); String indexHtmlPathInProductionMode = VAADIN_SERVLET_RESOURCES + INDEX_HTML; URL url = vaadinService.getClassLoader().getResource(indexHtmlPathInProductionMode); try { Objects.requireNonNull(url); File indexHtmlFile = new File(url.getPath()); indexHtmlFile.delete(); } catch (Exception ignored) try { indexHtmlRequestHandler.synchronizedHandleRequest(session, vaadinServletRequest, response); throw new IllegalStateException("Must not reach to this point since index.html is not found"); } catch (IOException iOExeption) { String expectedError = "Failed to load content of './frontend/index.html'." + "It is required to have './frontend/index.html' file " + "when using client side bootstrapping."; assertEquals(expectedError, iOExeption.getMessage()); } }

Target:
public void serveNotFoundIndexHtml_requestWithRootPath_failsWithIOException() throws IOException { VaadinServletRequest vaadinServletRequest = createVaadinRequest("/"); VaadinService vaadinService = vaadinServletRequest.getService(); String indexHtmlPathInProductionMode = VAADIN_SERVLET_RESOURCES + INDEX_HTML; URL url = vaadinService.getClassLoader().getResource(indexHtmlPathInProductionMode); assertNotNull(url); File indexHtmlFile = new File(url.getPath()); File indexHtmlFileTmp = new File(url.getPath() + "_tmp"); try { boolean renamed = indexHtmlFile.renameTo(indexHtmlFileTmp); assertTrue(renamed); String expectedError = "Failed to load content of './frontend/index.html'. " + "It is required to have './frontend/index.html' file " + "when using client side bootstrapping."; exceptionRule.expect(IOException.class); exceptionRule.expectMessage(expectedError); indexHtmlRequestHandler.synchronizedHandleRequest(session, vaadinServletRequest, response); } finally { boolean renamed = indexHtmlFileTmp.renameTo(indexHtmlFile); assertTrue(renamed); } }