auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_SUBSCRIPTION_KEY")) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.", "en"), new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") ); final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); final DocumentResultCollection<LinkedEntityResult> detectedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); System.out.printf("Model version: %s", detectedBatchResult.getModelVersion()); final TextBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); detectedBatchResult.forEach(linkedEntityDocumentResult -> linkedEntityDocumentResult.getLinkedEntities().stream().forEach(linkedEntity -> System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s", linkedEntity.getName(), linkedEntity.getUri(), linkedEntity.getDataSource()))); }

Target:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey("subscription-key") .endpoint("<LINK_0>") .buildClient(); List<TextDocumentInput> inputs = Arrays.asList( new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.", "en"), new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") ); final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); final DocumentResultCollection<RecognizeLinkedEntitiesResult> detectedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (RecognizeLinkedEntitiesResult linkedEntityDocumentResult : detectedBatchResult) { for (LinkedEntity linkedEntity : linkedEntityDocumentResult.getLinkedEntities()) { System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s%n", linkedEntity.getName(), linkedEntity.getUrl(), linkedEntity.getDataSource()); } } }
Source:
public ConfigurationClientBuilder connectionString(String connectionString) { if (CoreUtils.isNullOrEmpty(connectionString)) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be null or an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; }

Target:
public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); if (connectionString.isEmpty()) { throw logger.logExceptionAsError( new IllegalArgumentException("'connectionString' cannot be an empty string.")); } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; }
Source:
public void setUp() throws ComponentLookupException, IOException, SolrServerException, CacheException { MockitoAnnotations.initMocks(this); this.indexReturn = -1; SolrVocabularyResourceManager externalServicesAccess = this.mocker.getInstance(SolrVocabularyResourceManager.class); when(externalServicesAccess.getSolrConnection()).thenReturn(this.server); CacheManager cacheFactory = this.mocker.getInstance(CacheManager.class); when(cacheFactory.createNewLocalCache(any(CacheConfiguration.class))).thenReturn((Cache) this.cache); this.service = (HPOScriptService) this.mocker.getComponentUnderTest(); }

Target:
public void setUp() throws ComponentLookupException, IOException, SolrServerException, CacheException { MockitoAnnotations.initMocks(this); this.indexReturn = -1; SolrVocabularyResourceManager externalServicesAccess = this.mocker.getInstance(SolrVocabularyResourceManager.class); Mockito.doReturn(this.server).when(externalServicesAccess).getSolrConnection(); CacheManager cacheFactory = this.mocker.getInstance(CacheManager.class); Mockito.doReturn(this.cache).when(cacheFactory).createNewLocalCache(any(CacheConfiguration.class)); this.service = (HPOScriptService) this.mocker.getComponentUnderTest(); }
Source:
private JButton getBtnReopen() { if (btnReopen == null) { btnReopen = new JButton(); btnReopen.setIcon(REOPEN_ICON); btnReopen.setEnabled(true); btnReopen.setToolTipText(Constant.messages.getString("websocket.manual_send.btn_reopen_hint")); btnReopen.addActionListener(e -> { isOnConnectingProgress(true); String newSecWebSocketKey = null; if(!wsUiHelper.isAlwaysGenerate()){ newSecWebSocketKey = wsUiHelper.getWebSocketKey(); } ReEstablishConnection reEstablishConnection = new ReEstablishConnection(newSecWebSocketKey); reEstablishConnection.addPropertyChangeListener(propertyChangeEvent -> { if((propertyChangeEvent.getNewValue() == SwingWorker.StateValue.DONE)){ isOnConnectingProgress(false); int channelId1; try { channelId1 = reEstablishConnection.get(); if(channelId1 < 0){ if(channelId1 == ReEstablishConnection.REQUEST_OUT_OF_SCOPE){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.out_of_scope")); }else if(channelId1 == ReEstablishConnection.IOEXCEPTION){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.unable_reopen")); } }else{ wsUiHelper.setSelectedChannelId(channelId1); wsUiHelper.requestFocusChannelComboBox(); } } catch (Exception e1) { LOGGER.warn(e1.getStackTrace(), e1); } } }); reEstablishConnection.execute(); }); } return btnReopen; }

Target:
private JButton getBtnReopen() { if (btnReopen == null) { btnReopen = new JButton(); btnReopen.setIcon(REOPEN_ICON); btnReopen.setEnabled(true); btnReopen.setToolTipText(Constant.messages.getString("websocket.manual_send.btn_reopen_hint")); btnReopen.addActionListener((ActionEvent e) -> { isOnConnectingProgress(true); String newSecWebSocketKey = null; if(!wsUiHelper.isAlwaysGenerate()){ newSecWebSocketKey = wsUiHelper.getWebSocketKey(); } ReEstablishConnection reEstablishConnection = new ReEstablishConnection(newSecWebSocketKey); reEstablishConnection.addPropertyChangeListener(propertyChangeEvent -> { if((propertyChangeEvent.getNewValue() == SwingWorker.StateValue.DONE)){ isOnConnectingProgress(false); int channelId; try { channelId = reEstablishConnection.get(); if(channelId < 0){ if(channelId == ReEstablishConnection.RETRIVING_HANDSHAKE_ERROR){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.retrieve")); }else if(channelId == ReEstablishConnection.REQUEST_OUT_OF_SCOPE){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.out_of_scope")); }else if(channelId == ReEstablishConnection.IOEXCEPTION){ View.getSingleton().showWarningDialog(Constant.messages.getString("websocket.manual_send.fail.unable_reopen")); } }else{ wsUiHelper.setSelectedChannelId(channelId); wsUiHelper.requestFocusChannelComboBox(); } } catch (Exception ex){ LOGGER.error("An error occurred when trying to re-establish a websocket connection",ex); } } }); reEstablishConnection.execute(); }); } return btnReopen; }
Source:
public void merge_NullSafe() { assertThat(new ReportFeatureAppendableMerger().merge(null)).isNotNull().isEmpty(); }

Target:
public void merge_NullSafe() { ReportFeatureAppendableMerger merger = new ReportFeatureAppendableMerger(); List<Feature> result = merger.merge(null); assertThat(result).isNotNull().isEmpty(); }
Source:
protected void openDiagram(String name) { editor = (SWTBotSiriusDiagramEditor) openRepresentation(localSession.getOpenedSession(), VIEWPOINT_NAME + " " + name, name, DDiagram.class); editor.setSnapToGrid(false); editor.zoom(ZoomLevel.ZOOM_100); }

Target:
protected void openDiagram(String name) { openDiagram(name, ZoomLevel.ZOOM_100); }
Source:
public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; partitionedFileName = String.format(partitionedFileNameformat, outputFileName, physicalPartitionId); }

Target:
public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; }
Source:
public HealthThermometerServiceFragment() { mTemperatureMeasurementCharacteristic = new BluetoothGattCharacteristic(TEMPERATURE_MEASUREMENT_UUID, BluetoothGattCharacteristic.PROPERTY_INDICATE, 0); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getClientCharacteristicConfigurationDescriptor()); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(TEMPERATURE_MEASUREMENT_DESCRIPTION)); mMeasurementIntervalCharacteristic = new BluetoothGattCharacteristic(MEASUREMENT_INTERVAL_UUID, (BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE), (BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE)); mMeasurementIntervalCharacteristic.addDescriptor( Peripheral.getClientCharacteristicConfigurationDescriptor()); mMeasurementIntervalCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(MEASUREMENT_INTERVAL_DESCRIPTION)); mHealthThermometerService = new BluetoothGattService(HEALTH_THERMOMETER_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); mHealthThermometerService.addCharacteristic(mTemperatureMeasurementCharacteristic); mHealthThermometerService.addCharacteristic(mMeasurementIntervalCharacteristic); }

Target:
public HealthThermometerServiceFragment() { mTemperatureMeasurementCharacteristic = new BluetoothGattCharacteristic(TEMPERATURE_MEASUREMENT_UUID, BluetoothGattCharacteristic.PROPERTY_INDICATE, 0); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getClientCharacteristicConfigurationDescriptor()); mTemperatureMeasurementCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(TEMPERATURE_MEASUREMENT_DESCRIPTION)); mMeasurementIntervalCharacteristic = new BluetoothGattCharacteristic( MEASUREMENT_INTERVAL_UUID, (BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_INDICATE), (BluetoothGattCharacteristic.PERMISSION_READ | BluetoothGattCharacteristic.PERMISSION_WRITE)); mMeasurementIntervalCCCDescriptor = Peripheral.getClientCharacteristicConfigurationDescriptor(); mMeasurementIntervalCharacteristic.addDescriptor(mMeasurementIntervalCCCDescriptor); mMeasurementIntervalCharacteristic.addDescriptor( Peripheral.getCharacteristicUserDescriptionDescriptor(MEASUREMENT_INTERVAL_DESCRIPTION)); mHealthThermometerService = new BluetoothGattService(HEALTH_THERMOMETER_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY); mHealthThermometerService.addCharacteristic(mTemperatureMeasurementCharacteristic); mHealthThermometerService.addCharacteristic(mMeasurementIntervalCharacteristic); }
Source:
protected void validate(long timeWindow) throws Exception { if (this.mergedFreeBusyInterval > timeWindow) { throw new IllegalArgumentException(String.format("%s,%s", "MergedFreeBusyInterval must be smaller than the specified time window.", "MergedFreeBusyInterval")); } EwsUtilities.validateParamAllowNull(this.detailedSuggestionsWindow, "DetailedSuggestionsWindow"); }

Target:
protected void validate(long timeWindow) throws Exception { if (this.mergedFreeBusyInterval > timeWindow) { throw new IllegalArgumentException( "MergedFreeBusyInterval must be smaller than the specified time window."); } EwsUtilities.validateParamAllowNull(this.detailedSuggestionsWindow, "DetailedSuggestionsWindow"); }
Source:
public void close() throws IOException { this.executor.shutdown(); final long begin = System.currentTimeMillis(); int attempt = 0; try { while (true) { if (this.executor.awaitTermination(2, TimeUnit.SECONDS) || attempt >= MethodScheduler.SHUTDOWN_ATTEMPTS) { break; } final long age = System.currentTimeMillis() - begin; if (age > this.limit) { this.executor.shutdownNow(); attempt += 1; } Logger.info( this, "waiting %[ms]s for threads termination", age ); TimeUnit.SECONDS.sleep(1); } if (!this.executor.isTerminated()) { throw new IllegalStateException( Logger.format( "failed to shutdown %[type]s of %[type]s", this.executor, this.object ) ); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } Logger.info( this.object, "execution stopped after %[ms]s and %d tick(s)", System.currentTimeMillis() - this.start, this.counter.get() ); }

Target:
public void close() throws IOException { this.executor.shutdown(); final long begin = System.currentTimeMillis(); try { while (true) { if (this.executor.awaitTermination(1, TimeUnit.SECONDS)) { break; } final long age = System.currentTimeMillis() - begin; if (age > this.await) { break; } Logger.info( this, "waiting %[ms]s for threads termination", age ); } for (int attempt = 0; attempt < this.attempts; ++attempt) { this.executor.shutdownNow(); this.executor.awaitTermination(1, TimeUnit.SECONDS); } if (!this.executor.isTerminated()) { throw new IllegalStateException( Logger.format( "failed to shutdown %[type]s of %[type]s", this.executor, this.object ) ); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } Logger.info( this.object, "execution stopped after %[ms]s and %d tick(s)", System.currentTimeMillis() - this.start, this.counter.get() ); }
Source:
public Response toResponse(QosException exception) { log.debug("Possible quality-of-service intervention", exception); if (exception instanceof QosException.Retry) { QosException.Retry retry = (QosException.Retry) exception; if (!retry.getBackoff().isPresent() && !retry.getRedirectTo().isPresent()) { return retryAnyNow(); } else { if (retry.getBackoff().isPresent()) { return retryAnyLater(retry.getBackoff().get()); } else if (retry.getRedirectTo().isPresent()) { return retryThisHostNow(retry.getRedirectTo().get()); } else { throw new RuntimeException("Unexpected internal state: expected either backoff or redirectTo"); } } } else if (exception instanceof QosException.Unavailable) { return unavailable(); } else { throw new RuntimeException( "Internal error, unknown QosException subclass: " + exception.getClass().getSimpleName()); } }

Target:
public Response toResponse(QosException exception) { log.debug("Possible quality-of-service intervention", exception); if (exception instanceof QosException.Retry) { return retry(); } else if (exception instanceof QosException.RetryOther) { QosException.RetryOther retry = (QosException.RetryOther) exception; return retryOther(retry.getRedirectTo()); } else if (exception instanceof QosException.Unavailable) { return unavailable(); } else { throw new RuntimeException( "Internal error, unknown QosException subclass: " + exception.getClass().getSimpleName()); } }
Source:
public static void downloadCustomDockerImage() throws IOException { Utilities.executeCommand("docker pull ubuntu:latest", System.out, System.err); Utilities.executeCommand("docker tag ubuntu:latest " + FAKE_IMAGE_NAME, System.out, System.err); docker_images = Files.createTempDirectory("docker_images").toAbsolutePath().toString(); Utilities.executeCommand("docker save -o " + docker_images + "/fakeImage " + FAKE_IMAGE_NAME, System.out, System.err); }

Target:
public static void downloadCustomDockerImage() throws IOException { Utilities.executeCommand("docker build -f " + DOCKERFILE + " . -t " + FAKE_IMAGE_NAME, System.out, System.err); DOCKER_IMAGE_DIRECTORY = Files.createTempDirectory("docker_images").toAbsolutePath().toString(); Utilities.executeCommand("docker save -o " + DOCKER_IMAGE_DIRECTORY + "/fakeImage " + FAKE_IMAGE_NAME, System.out, System.err); }
Source:
public void expansionPath() { CartFixtures.withCart(client(), cart -> { withCustomObjectAndCustomClasses(client(), cart, existingCustomObject -> { final String id = existingCustomObject.getId(); final CustomObjectByIdGet<MyCustomClass> fetch = CustomObjectByIdGet.of(id, MyCustomClass.class); CustomObject<MyCustomClass> customObject = client().executeBlocking(fetch); assertThat(customObject).isEqualTo(existingCustomObject); final ExpansionPath<CustomObject<MyCustomClass>> expansionPath = ExpansionPath.of("value.cartReference"); CustomObjectByIdGet<MyCustomClass> expandedFetch = fetch.withExpansionPaths(expansionPath); customObject = client().executeBlocking(expandedFetch); assertThat(customObject).isNotNull(); assertThat(customObject.getValue().getCartReference().getObj()).isNotNull(); }); return cart; }); }

Target:
public void expansionPath() { CartFixtures.withCart(client(), cart -> { withCustomObjectAndCustomClasses(client(), cart, existingCustomObject -> { final String id = existingCustomObject.getId(); final CustomObjectByIdGet<MyCustomClass> fetch = CustomObjectByIdGet.of(id, MyCustomClass.class); CustomObject<MyCustomClass> customObject = client().executeBlocking(fetch); assertThat(customObject).isEqualTo(existingCustomObject); assertThat(customObject.getValue().getCartReference().getObj()).isNull(); final ExpansionPath<CustomObject<MyCustomClass>> expansionPath = ExpansionPath.of("value.cartReference"); CustomObjectByIdGet<MyCustomClass> expandedFetch = fetch.withExpansionPaths(expansionPath); customObject = client().executeBlocking(expandedFetch); assertThat(customObject).isNotNull(); assertThat(customObject.getValue().getCartReference().getObj()).isNotNull(); }); return cart; }); }
Source:
public void aggregation() { aggregatedApplicationContext = new AggregateApplicationBuilder( FooConfig.class, "--server.port=0", "--debug=true", "--spring.cloud.stream.default-binder=mock") .web(false).from(TestSource.class).to(TestProcessor.class).run(); SharedBindingTargetRegistry sharedBindingTargetRegistry = aggregatedApplicationContext .getBean(SharedBindingTargetRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext .getBean(SubscribableChannelBindingTargetFactory.class); assertThat(channelFactory).isNotNull(); assertThat(sharedBindingTargetRegistry.getAll().keySet()).hasSize(2); aggregatedApplicationContext.close(); }

Target:
public void aggregation() { aggregatedApplicationContext = new AggregateApplicationBuilder( AggregationAppConfig.class, "--spring.cloud.stream.default-binder=mock") .web(false).from(TestSource.class).to(TestProcessor.class).run(); SharedBindingTargetRegistry sharedBindingTargetRegistry = aggregatedApplicationContext .getBean(SharedBindingTargetRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext .getBean(SubscribableChannelBindingTargetFactory.class); assertThat(channelFactory).isNotNull(); assertThat(sharedBindingTargetRegistry.getAll().keySet()).hasSize(2); aggregatedApplicationContext.close(); }
Source:
public void close() throws IOException { if (lineIterator != null) { lineIterator.close(); } if (closer != null) { closer.close(); } }

Target:
public void close() throws IOException { try { if (lineIterator != null) { lineIterator.close(); } } catch (Throwable t) { try { if (closer != null) { closer.close(); } } catch (Exception e) { t.addSuppressed(e); } throw t; } if (closer != null) { closer.close(); } }
Source:
public RestRequestHandler getRequestHandler() throws RestServiceException { RestRequestHandler requestHandler; int index = currIndex.getAndIncrement(); try { requestHandler = requestHandlers.get(index % requestHandlers.size()); } catch (Exception e) { logger.error("Exception during selection of a RestRequestHandler to return", e); restServerMetrics.requestHandlerControllerHandlerSelectionError.inc(); throw new RestServiceException("Exception during selection of a RestRequestHandler to return", e, RestServiceErrorCode.RequestHandlerSelectionError); } if (requestHandler.isRunning()) { logger.debug("Monotonically increasing value was used to pick request handler at index {}", index, index % requestHandlers.size()); } else { logger.debug("Request handler at index is dead. Substitute request handler selection will be attempted", index % requestHandlers.size()); requestHandler = pickSubstituteRequestHandler(); } return requestHandler; }

Target:
public RestRequestHandler getRequestHandler() throws RestServiceException { RestRequestHandler requestHandler; int index = currIndex.getAndIncrement(); try { requestHandler = requestHandlers.get(index % requestHandlers.size()); logger.trace("Monotonically increasing value was used to pick request handler at index {}", index, index % requestHandlers.size()); } catch (Exception e) { restServerMetrics.requestHandlerSelectionError.inc(); throw new RestServiceException("Exception during selection of a RestRequestHandler to return", e, RestServiceErrorCode.RequestHandlerSelectionError); } return requestHandler; }
Source:
public static byte[] macToBytes(String mac) throws KuraException { if (mac == null) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } String[] items = mac.split("\\:"); if (items.length != 6) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } byte[] bytes = new byte[6]; for (int i = 0; i < 6; i++) { String item = items[i]; if (item.isEmpty() || (item.length() > 2)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } try { bytes[i] = (byte) Integer.parseInt(items[i], 16); } catch (NumberFormatException e) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } } return bytes; }

Target:
public static byte[] macToBytes(String mac) { if (mac == null) { throw new IllegalArgumentException("mac is null"); } String[] items = mac.split("\\:"); if (items.length != 6) { throw new IllegalArgumentException("mac is invalid: " + mac); } byte[] bytes = new byte[6]; for (int i = 0; i < 6; i++) { String item = items[i]; if (item.isEmpty() || (item.length() > 2)) { throw new IllegalArgumentException("mac is invalid: " + mac); } try { bytes[i] = (byte) Integer.parseInt(items[i], 16); } catch (NumberFormatException e) { throw new IllegalArgumentException("mac is invalid: " + mac, e); } } return bytes; }
Source:
public void testZkAdminTimeout() { boolean exceptionThrown = false; ZKHelixAdmin admin = null; try { admin = new ZKHelixAdmin("localhost:27999"); } catch (Exception e) { exceptionThrown = true; } finally { if (admin != null) { admin.close(); } } Assert.assertTrue(exceptionThrown); System.setProperty(ZKHelixAdmin.CONNECTION_TIMEOUT, "3"); exceptionThrown = false; long time = System.currentTimeMillis(); try { admin = new ZKHelixAdmin("localhost:27999"); } catch (Exception e) { exceptionThrown = true; } finally { if (admin != null) { admin.close(); } } Assert.assertTrue(exceptionThrown); Assert.assertTrue(System.currentTimeMillis() - time < 5000); }

Target:
public void testZkAdminTimeout() { boolean exceptionThrown = testZkAdminTimeoutHelper(); Assert.assertTrue(exceptionThrown); System.setProperty(ZKHelixAdmin.CONNECTION_TIMEOUT, "3"); exceptionThrown = testZkAdminTimeoutHelper(); long time = System.currentTimeMillis(); Assert.assertTrue(exceptionThrown); Assert.assertTrue(System.currentTimeMillis() - time < 5000); }
Source:
protected BinaryMetadataProcessor(String baseBinaryPath) { this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } }

Target:
public BinaryMetadataProcessor(String baseBinaryPath) { this.baseBinaryPath = baseBinaryPath; if (!baseBinaryPath.endsWith("/")) { this.baseBinaryPath += "/"; } }
Source:
private String generator() { String[] sentences = new String[] {"the cow jumped over the moon", "an apple a day keeps the doctor away", "four score and seven years ago", "snow white and the seven dwarfs", "i am at two with nature" }; String sentence = sentences[rand.nextInt(sentences.length)]; return sentence; }

Target:
private String generator() { final String[] sentences = new String[] {"the cow jumped over the moon", "an apple a day keeps the doctor away", "four score and seven years ago", "snow white and the seven dwarfs", "i am at two with nature" }; final String sentence = sentences[rand.nextInt(sentences.length)]; return sentence; }
Source:
private String executeDiscoveryScript(File discoveryScript, long gpuAmount, String args) throws Exception { final String cmd = discoveryScript.getAbsolutePath() + " " + gpuAmount + " " + args; final Process process = Runtime.getRuntime().exec(cmd); final BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); final int exitVal = process.waitFor(); if (exitVal != 0) { final String stdout = stdoutReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); final String stderr = stderrReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); LOG.error("Discovery script exit with {}. With output {}", exitVal, stdout, stderr); throw new FlinkException("Discovery script exit with non-zero."); } return stdoutReader.readLine(); }

Target:
private String executeDiscoveryScript(File discoveryScript, long gpuAmount, String args) throws Exception { final String cmd = discoveryScript.getAbsolutePath() + " " + gpuAmount + " " + args; final Process process = Runtime.getRuntime().exec(cmd); try (final BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader stderrReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { final boolean hasProcessTerminated = process.waitFor(DISCOVERY_SCRIPT_TIMEOUT_MS, TimeUnit.MILLISECONDS); if (!hasProcessTerminated) { throw new TimeoutException(String.format("The discovery script executed for over %d ms.", DISCOVERY_SCRIPT_TIMEOUT_MS)); } final int exitVal = process.exitValue(); if (exitVal != 0) { final String stdout = stdoutReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); final String stderr = stderrReader.lines().collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); LOG.warn("Discovery script exit with {}.\\nSTDOUT: {}\\nSTDERR: {}", exitVal, stdout, stderr); throw new FlinkException(String.format("Discovery script exit with non-zero return code: %s.", exitVal)); } Object[] stdout = stdoutReader.lines().toArray(); if (stdout.length > 1) { LOG.warn( "The output of the discovery script should only contain one single line. Finding lines with content: {}. Will only keep the first line.", stdout.length, Arrays.toString(stdout)); } if (stdout.length == 0) { return ""; } return (String) stdout[0]; } finally { process.destroyForcibly(); } }
Source:
public String getDisplayName() { return "Transform and archive various test result formats"; }

Target:
public String getDisplayName() { return Messages.xUnit_PublisherName(); }
Source:
private static <T> Stream<T> unwrap(CompletableFuture<Stream<T>> fut) { try { return fut.get(); } catch (InterruptedException | ExecutionException e) { return Stream.empty(); } }

Target:
private static <T> Stream<T> unwrap(CompletableFuture<Stream<T>> fut) { Stream<T> empty = Stream.empty(); try { return fut.getNow(empty); } catch (CompletionException | CancellationException e) { return empty; } }
Source:
public synchronized CompletableFuture<Void> addListener(String topic, LeadershipEventListener<byte[]> listener) { boolean empty = leadershipChangeListeners.isEmpty(); leadershipChangeListeners.compute(topic, (t, s) -> { if (s == null) { s = Sets.newCopyOnWriteArraySet(Collections.singleton(listener)); } else { s.add(listener); } return s; }); if (empty) { return proxy.invoke(ADD_LISTENER); } return CompletableFuture.completedFuture(null); }

Target:
public synchronized CompletableFuture<Void> addListener(String topic, LeadershipEventListener<byte[]> listener) { boolean empty = leadershipChangeListeners.isEmpty(); leadershipChangeListeners.compute(topic, (t, s) -> { if (s == null) { s = Sets.newCopyOnWriteArraySet(); } s.add(listener); return s; }); if (empty) { return proxy.invoke(ADD_LISTENER); } return CompletableFuture.completedFuture(null); }
Source:
private PhpCfgBlock createLabelBlock(LabelTree tree, PhpCfgBlock currentBlock) { String label = tree.label().text(); labelledBlocks.put(label, currentBlock); currentBlock.addElement(tree); PhpCfgBlock gotoWithoutTarget = gotosWithoutTarget.get(label); if (gotoWithoutTarget != null) { gotoWithoutTarget.replaceSuccessor(end, currentBlock); } return createSimpleBlock(currentBlock); }

Target:
private PhpCfgBlock createLabelBlock(LabelTree tree, PhpCfgBlock currentBlock) { String label = tree.label().text(); labelledBlocks.put(label, currentBlock); currentBlock.addElement(tree); List<PhpCfgBlock> gotoBlocks = gotosWithoutTarget.get(label); if (gotoBlocks != null) { gotoBlocks.forEach(gotoBlock -> gotoBlock.replaceSuccessor(end, currentBlock)); gotosWithoutTarget.remove(label); } return createSimpleBlock(currentBlock); }
Source:
private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }

Target:
private String _encode(String strVal) { try { return URLEncoder.encode(strVal, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
public static Set<URL> collectUrlFromRelease(final ImportConfiguration configuration) { final ReleaseFileSet releaseFileSet = configuration.getReleaseFileSet(); if (releaseFileSet == null) { return Collections.<URL>emptySet(); } final List<String> refSetsRelativePaths = releaseFileSet.getRefSetPaths(); final String relativeRoot = releaseFileSet.getRelativeRoot(); final Set<URL> collectedUrlSet = Sets.newHashSet(); for(final String refSetPath : refSetsRelativePaths) { Set<URL> parsedRefSetUrl = Sets.newHashSet(); if (configuration.getSourceKind().equals(ImportSourceKind.ARCHIVE)) { parsedRefSetUrl = parseZip(configuration.getArchiveFile(), relativeRoot, refSetPath); } else if (configuration.getSourceKind().equals(ImportSourceKind.ROOT_DIRECTORY)) { parsedRefSetUrl = parseDirectory(configuration.getRootFile(), relativeRoot, refSetPath); } collectedUrlSet.addAll(parsedRefSetUrl); } try { for (File langFiles : configuration.getLanguageRefSetFiles()) { collectedUrlSet.add(configuration.toURL(langFiles)); } if (null != configuration.getDescriptionType()) { collectedUrlSet.add(configuration.toURL(configuration.getDescriptionType())); } } catch (final IOException e) { e.printStackTrace(); } return collectedUrlSet; }

Target:
public static Set<URL> collectUrlFromRelease(final ImportConfiguration configuration) { final ReleaseFileSet releaseFileSet = configuration.getReleaseFileSet(); if (releaseFileSet == null) { return Collections.<URL>emptySet(); } final Set<URL> collectedUrlSet = Sets.newHashSet(); if (configuration.getSourceKind().equals(ImportSourceKind.ARCHIVE)) { final List<String> refSetsRelativePaths = releaseFileSet.getRefSetPaths(); final String relativeRoot = releaseFileSet.getRelativeRoot(); for (final String refSetPath : refSetsRelativePaths) { collectedUrlSet.addAll(parseZip(configuration.getArchiveFile(), relativeRoot, refSetPath)); } } return collectedUrlSet; }
Source:
public void testGetOtherDMNDiagramsDefinitions() { final Metadata metadata = mock(Metadata.class); final Path path1 = makePath("../file1.dmn"); final Path path2 = makePath("../file2.dmn"); final Path path3 = makePath("../file3.dmn"); final Path path4 = makePath("../file3.dmn"); final InputStreamReader inputStreamReader1 = mock(InputStreamReader.class); final InputStreamReader inputStreamReader2 = mock(InputStreamReader.class); final InputStreamReader inputStreamReader3 = mock(InputStreamReader.class); final Definitions definitions1 = mock(Definitions.class); final Definitions definitions2 = mock(Definitions.class); final Definitions definitions3 = mock(Definitions.class); final List<Path> paths = asList(path1, path2, path3, path4); when(pathsHelper.getDiagramsPaths(any())).thenReturn(paths); when(metadata.getPath()).thenReturn(path2); doReturn(Optional.of(inputStreamReader1)).when(helper).loadPath(path1); doReturn(Optional.of(inputStreamReader2)).when(helper).loadPath(path2); doReturn(Optional.of(inputStreamReader3)).when(helper).loadPath(path3); doReturn(Optional.empty()).when(helper).loadPath(path4); when(marshaller.unmarshal(inputStreamReader1)).thenReturn(definitions1); when(marshaller.unmarshal(inputStreamReader2)).thenReturn(definitions2); when(marshaller.unmarshal(inputStreamReader3)).thenReturn(definitions3); final List<Definitions> actualDefinitions = helper.getOtherDMNDiagramsDefinitions(metadata); final List<Definitions> expectedDefinitions = asList(definitions1, definitions3); assertEquals(expectedDefinitions, actualDefinitions); }

Target:
public void testGetOtherDMNDiagramsDefinitions() { final Metadata metadata = mock(Metadata.class); final Path path1 = makePath("../file1.dmn"); final Path path2 = makePath("../file2.dmn"); final Path path3 = makePath("../file3.dmn"); final Path path4 = makePath("../file4.dmn"); final InputStreamReader inputStreamReader1 = mock(InputStreamReader.class); final InputStreamReader inputStreamReader2 = mock(InputStreamReader.class); final InputStreamReader inputStreamReader3 = mock(InputStreamReader.class); final Definitions definitions1 = mock(Definitions.class); final Definitions definitions2 = mock(Definitions.class); final Definitions definitions3 = mock(Definitions.class); final List<Path> paths = asList(path1, path2, path3, path4); when(pathsHelper.getDiagramsPaths(any())).thenReturn(paths); when(metadata.getPath()).thenReturn(path2); doReturn(Optional.of(inputStreamReader1)).when(helper).loadPath(path1); doReturn(Optional.of(inputStreamReader2)).when(helper).loadPath(path2); doReturn(Optional.of(inputStreamReader3)).when(helper).loadPath(path3); doReturn(Optional.empty()).when(helper).loadPath(path4); when(marshaller.unmarshal(inputStreamReader1)).thenReturn(definitions1); when(marshaller.unmarshal(inputStreamReader2)).thenReturn(definitions2); when(marshaller.unmarshal(inputStreamReader3)).thenReturn(definitions3); final List<Definitions> actualDefinitions = helper.getOtherDMNDiagramsDefinitions(metadata); final List<Definitions> expectedDefinitions = asList(definitions1, definitions3); assertEquals(expectedDefinitions, actualDefinitions); }
Source:
public SeRandomizationDTO getRandomizationDTOObject(String studyOid) { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String randomizationUrl = CoreResources.getField("moduleManager") + "/app/rest/oc/se_randomizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setReadTimeout(RANDOMIZATION_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { SeRandomizationDTO response = rest.getForObject(randomizationUrl, SeRandomizationDTO.class); if (response.getStudyOid() != null) { return response; } else { return null; } } catch (Exception e) { logger.error("Response in not getting generated properly: ",e.getMessage(),e); } return null; }

Target:
public SeRandomizationDTO getRandomizationDTOObject(String studyOid) { String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid; String randomizationUrl = CoreResources.getField("moduleManager") + "/app/rest/oc/se_randomizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setReadTimeout(RANDOMIZATION_READ_TIMEOUT); RestTemplate rest = new RestTemplate(requestFactory); try { SeRandomizationDTO response = rest.getForObject(randomizationUrl, SeRandomizationDTO.class); if (response.getStudyOid() != null) { return response; } else { return null; } } catch (Exception e) { logger.error("Response in not getting generated properly: ", e); } return null; }
Source:
void tostring() { assertThat(new AttributeWithValue("data-id", "expected").toString()).isEqualTo("attribute data-id=\"expected\""); }

Target:
void tostring() { assertThat(new AttributeWithValue("data-id", "expected")).hasToString("attribute data-id=\"expected\""); }
Source:
public String docs() { return "boolean {name} Adds a new team to the scoreboard, returning true if successful." + " Returns false if a team already exists with the given name."; }

Target:
public String docs() { return "void {name} Adds a new team to the scoreboard," + " throws an exception if a team already exists with the given name."; }
Source:
public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); Assertions.assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry","afterInvocation"); }

Target:
public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry", "afterInvocation"); }
Source:
int getFirstRowIndexOfMergedBlock(final GridData model, final int rowIndex) { int currentIndex = rowIndex; GridCell<?> cell = model.getCell(rowIndex, getHighlightCellColumnIndex()); while (cell.getMergedCellCount() == 0) { currentIndex--; cell = model.getCell(currentIndex, getHighlightCellColumnIndex()); } return currentIndex; }

Target:
int getFirstRowIndexOfMergedBlock(final GridData model, final int rowIndex) { int currentIndex = rowIndex; GridCell<?> cell = model.getCell(rowIndex, getHighlightCellColumnIndex()); while (cell.getMergedCellCount() == 0 && currentIndex >= 0) { currentIndex--; cell = model.getCell(currentIndex, getHighlightCellColumnIndex()); } return currentIndex; }
Source:
public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { instance = new OVirtNodeInfo(); } return instance; }

Target:
public static synchronized OVirtNodeInfo getInstance() { if (instance == null) { instance = new OVirtNodeInfo(); } else { if (instance == null) { synchronized(OVirtNodeInfo.class) { if (instance == null) { instance = new OVirtNodeInfo(); } } } } return instance; }
Source:
protected void populateReservoirInputPortMap() { for (Entry<String,Operators.PortContextPair<InputPort<?>>> entry : descriptor.inputPorts.entrySet()) { if (entry.getValue().component instanceof InputPort) { if (inputs.containsKey(entry.getKey())) { reservoirPortMap.put(inputs.get(entry.getKey()), entry.getValue().component.getSink()); } } } }

Target:
protected void populateReservoirInputPortMap() { for (Entry<String,Operators.PortContextPair<InputPort<?>>> entry : descriptor.inputPorts.entrySet()) { if (entry.getValue().component != null && entry.getValue().component instanceof InputPort) { if (inputs.containsKey(entry.getKey())) { reservoirPortMap.put(inputs.get(entry.getKey()), entry.getValue().component.getSink()); } } } }
Source:
public Response getPurchaseOrder(@PathParam(PurapPropertyConstants.PURAP_DOC_ID) String purapDocumentIdentifier, @Context HttpHeaders headers) { try { HashMap<String, String> map = new HashMap<>(); map.put(PurapPropertyConstants.PURAP_DOC_ID, purapDocumentIdentifier); PurchaseOrderDocument poDoc = getLookupDao().findObjectByMap(PurchaseOrderDocument.class.newInstance(), map); if (ObjectUtils.isNull(poDoc)) { return respondNotFound(); } String responseBody = serializePoDocumentToJson(poDoc); return Response.ok(responseBody).build(); } catch (Exception ex) { LOG.error(ex); return respondInternalServerError(ex); } }

Target:
public Response getPurchaseOrder(@PathParam(PurapPropertyConstants.PURAP_DOC_ID) String purapDocumentIdentifier, @Context HttpHeaders headers) { try { HashMap<String, String> map = new HashMap<>(); map.put(PurapPropertyConstants.PURAP_DOC_ID, purapDocumentIdentifier); PurchaseOrderDocument poDoc = getLookupDao().findObjectByMap(PurchaseOrderDocument.class.newInstance(), map); if (ObjectUtils.isNull(poDoc)) { return respondNotFound(); } String responseBody = serializePoDocumentToJson(poDoc); return Response.ok(responseBody).build(); } catch (Exception ex) { LOG.error("getPurchaseOrder", ex); return respondInternalServerError(ex); } }
Source:
public Future<PlanResult> execute(final Plan plan) { return mainExecutor.submit(new Callable<PlanResult>() { @Override public PlanResult call() throws Exception { if (plan.getEvaluatorsToAdd().isEmpty() && plan.getTransferSteps().isEmpty()) { return new PlanResultImpl(); } executingPlan = new ExecutingPlan(plan, dolphinDriver.get()); for (final String evaluatorToAdd : plan.getEvaluatorsToAdd()) { LOG.log(Level.INFO, "Add new evaluator {0}", evaluatorToAdd); elasticMemory.add(1, 512, 1, new ContextActiveHandler()); } executingPlan.awaitActiveContexts(); LOG.log(Level.INFO, "All evaluators were added, will transfer data."); try { for (final TransferStep transferStep : plan.getTransferSteps()) { elasticMemory.move( transferStep.getDataInfo().getDataType(), transferStep.getDataInfo().getNumUnits(), transferStep.getSrcId(), executingPlan.getActualContextId(transferStep.getDstId()), new DataTransferredHandler(), new MovedHandler()); } } catch (final Exception e) { LOG.log(Level.WARNING, "Caught Exception, closing Evaluators.", e); executingPlan.onSynchronizedExecutionFailed(); } executingPlan.awaitDataTransfers(); LOG.log(Level.INFO, "All data transfers were completed, will submit evaluators and applyUpdates on pause."); driverSync.execute(new SynchronizedExecutionHandler(executingPlan), new SynchronizedExecutionFailedHandler(executingPlan)); executingPlan.awaitSynchronizedExecution(); executingPlan = null; return new PlanResultImpl(); } }); }

Target:
public Future<PlanResult> execute(final Plan plan) { return mainExecutor.submit(new Callable<PlanResult>() { @Override public PlanResult call() throws Exception { if (plan.getEvaluatorsToAdd().isEmpty() && plan.getTransferSteps().isEmpty()) { return new PlanResultImpl(); } executingPlan = new ExecutingPlan(plan, dolphinDriver.get()); for (final String evaluatorToAdd : plan.getEvaluatorsToAdd()) { LOG.log(Level.INFO, "Add new evaluator {0}", evaluatorToAdd); elasticMemory.add(1, evalSize, 1, new ContextActiveHandler()); } executingPlan.awaitActiveContexts(); LOG.log(Level.INFO, "All evaluators were added, will transfer data."); try { for (final TransferStep transferStep : plan.getTransferSteps()) { elasticMemory.move( transferStep.getDataInfo().getDataType(), transferStep.getDataInfo().getNumUnits(), transferStep.getSrcId(), executingPlan.getActualContextId(transferStep.getDstId()), new DataTransferredHandler(), new MovedHandler()); } } catch (final Exception e) { LOG.log(Level.WARNING, "Caught Exception, closing Evaluators.", e); executingPlan.onSynchronizedExecutionFailed(); } executingPlan.awaitDataTransfers(); LOG.log(Level.INFO, "All data transfers were completed, will submit evaluators and applyUpdates on pause."); driverSync.execute(new SynchronizedExecutionHandler(executingPlan), new SynchronizedExecutionFailedHandler(executingPlan)); executingPlan.awaitSynchronizedExecution(); executingPlan = null; return new PlanResultImpl(); } }); }
Source:
private void compactLog() { long lastApplied = raft.getLastApplied(); if (raft.getLog().isCompactable(lastApplied) && raft.getLog().getCompactableIndex(lastApplied) > lastCompacted) { this.lastCompacted = lastApplied; List<DefaultServiceContext> services = new ArrayList<>(this.services.values()); List<CompletableFuture<Void>> futures = services.stream() .map(context -> { long snapshotIndex = context.takeSnapshot().join(); return context.completeSnapshot(snapshotIndex); }) .collect(Collectors.toList()); CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .whenCompleteAsync((result, error) -> { logger.info("Compacting logs up to index {}", lastApplied); log.compact(lastApplied); scheduleCompaction(); }, threadContext); } }

Target:
private void compactLog() { long lastApplied = raft.getLastApplied(); if (raft.getLog().isCompactable(lastApplied) && raft.getLog().getCompactableIndex(lastApplied) > lastCompacted) { this.lastCompacted = lastApplied; List<DefaultServiceContext> services = new ArrayList<>(this.services.values()); List<CompletableFuture<Void>> futures = services.stream() .map(context -> { long snapshotIndex = context.takeSnapshot().join(); return context.completeSnapshot(snapshotIndex); }) .collect(Collectors.toList()); CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) .whenCompleteAsync((result, error) -> { logger.info("Compacting logs up to index {}", lastApplied); try { log.compact(lastApplied); } catch (Exception e) { logger.error("An exception occurred during log compaction: {}", e); } finally { scheduleCompaction(); } }, threadContext); } }
Source:
protected abstract Set<Capability> getCapabilities( AzkabanSequenceFileReader.Reader reader) throws Exception; protected abstract void displaySequenceFile( AzkabanSequenceFileReader.Reader reader, PrintWriter output, int startLine, int endLine) throws IOException; public Set<Capability> getCapabilites(FileSystem fs, Path file) { Set<Capability> result = EnumSet.noneOf(Capability.class); AzkabanSequenceFileReader.Reader reader = null; try { reader = new AzkabanSequenceFileReader.Reader(fs, file, new Configuration()); result = getCapabilities(reader); } catch (Exception e) { return EnumSet.noneOf(Capability.class); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } return result; }

Target:
protected abstract Set<Capability> getCapabilities( AzkabanSequenceFileReader.Reader reader) throws Exception; protected abstract void displaySequenceFile( AzkabanSequenceFileReader.Reader reader, PrintWriter output, int startLine, int endLine) throws IOException; public Set<Capability> getCapabilites(FileSystem fs, Path file) { Set<Capability> result = EnumSet.noneOf(Capability.class); AzkabanSequenceFileReader.Reader reader = null; try { reader = new AzkabanSequenceFileReader.Reader(fs, file, new Configuration()); result = getCapabilities(reader); } catch (Exception e) { return EnumSet.noneOf(Capability.class); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }