auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onUpdate(JsonElement data) { if (active && !(data.isJsonNull())) { state = new LightData(data); updateStatus(state.getReachabilityStatus() ? ThingStatus.ONLINE : ThingStatus.OFFLINE); if (!state.getOnOffState()) { logger.debug("Setting state to OFF"); updateState(CHANNEL_BRIGHTNESS, PercentType.ZERO); return; } PercentType dimmer = state.getBrightness(); if (dimmer != null) { updateState(CHANNEL_BRIGHTNESS, dimmer); } PercentType colorTemp = state.getColorTemperature(); if (colorTemp != null) { updateState(CHANNEL_COLOR_TEMPERATURE, colorTemp); } String devicefirmware = state.getFirmwareVersion(); if (devicefirmware != null) { getThing().setProperty("firmwareVersion", devicefirmware); } String modelId = state.getModelId(); if (devicefirmware != null) { getThing().setProperty("modelId", modelId); } String vendor = state.getVendor(); if (devicefirmware != null) { getThing().setProperty("vendor", vendor); } logger.debug("Updating thing for lightId to state {dimmer: {}, colorTemp: {}, devicefirmware: {}, modelId: {}, vendor: {}}" , state.getLightId(), dimmer, colorTemp, devicefirmware, modelId, vendor); } }

Target:
public void onUpdate(JsonElement data) { if (active && !(data.isJsonNull())) { state = new LightData(data); updateStatus(state.getReachabilityStatus() ? ThingStatus.ONLINE : ThingStatus.OFFLINE); if (!state.getOnOffState()) { logger.debug("Setting state to OFF"); updateState(CHANNEL_BRIGHTNESS, PercentType.ZERO); return; } PercentType dimmer = state.getBrightness(); if (dimmer != null) { updateState(CHANNEL_BRIGHTNESS, dimmer); } PercentType colorTemp = state.getColorTemperature(); if (colorTemp != null) { updateState(CHANNEL_COLOR_TEMPERATURE, colorTemp); } String devicefirmware = state.getFirmwareVersion(); if (devicefirmware != null) { getThing().setProperty(Thing.PROPERTY_FIRMWARE_VERSION, devicefirmware); } String modelId = state.getModelId(); if (modelId != null) { getThing().setProperty(Thing.PROPERTY_MODEL_ID, modelId); } String vendor = state.getVendor(); if (vendor != null) { getThing().setProperty(Thing.PROPERTY_VENDOR, vendor); } logger.debug("Updating thing for lightId to state {dimmer: {}, colorTemp: {}, devicefirmware: {}, modelId: {}, vendor: {}}" , state.getLightId(), dimmer, colorTemp, devicefirmware, modelId, vendor); } }
Source:
public boolean isSessionAllStop(String sessionId) { DsfServicesTracker servicesTracker = new DsfServicesTracker(MulticoreVisualizerUIPlugin.getBundleContext(), sessionId); IMIRunControl runCtrlService = servicesTracker.getService(IMIRunControl.class); servicesTracker.dispose(); if (runCtrlService != null && runCtrlService.getRunMode() == MIRunMode.ALL_STOP ) { return true; } return false; }

Target:
private boolean isSessionAllStop(String sessionId) { DsfServicesTracker servicesTracker = new DsfServicesTracker(MulticoreVisualizerUIPlugin.getBundleContext(), sessionId); IMIRunControl runCtrlService = servicesTracker.getService(IMIRunControl.class); servicesTracker.dispose(); if (runCtrlService != null && runCtrlService.getRunMode() == MIRunMode.ALL_STOP ) { return true; } return false; }
Source:
protected boolean isGhost(EntityModel<String> value) { String text = value.getEntity(); return text == null || text.isEmpty(); }

Target:
protected boolean isGhost(EntityModel<String> value) { return StringUtils.isEmpty(value.getEntity()); }
Source:
static org.ovirt.engine.core.common.businessentities.Disk setUpStatisticalEntityExpectations(DiskImage entity) { entity.setReadRate(1); entity.setReadRate(2); entity.setReadLatency(3.0); entity.setWriteLatency(4.0); entity.setFlushLatency(5.0); return entity; }

Target:
static org.ovirt.engine.core.common.businessentities.Disk setUpStatisticalEntityExpectations(DiskImage entity) { entity.setReadRate(1); entity.setWriteRate(2); entity.setReadLatency(3.0); entity.setWriteLatency(4.0); entity.setFlushLatency(5.0); return entity; }
Source:
public QuotaConsumptionParametersWrapper clone() { QuotaConsumptionParametersWrapper cloneWrapper = new QuotaConsumptionParametersWrapper(getAuditLogable(), canDoActionMessages); cloneWrapper.setParameters(new ArrayList<QuotaConsumptionParameter>()); for (QuotaConsumptionParameter parameter : getParameters()) { QuotaConsumptionParameter clone = parameter instanceof QuotaStorageConsumptionParameter ? ((QuotaStorageConsumptionParameter)parameter).clone(): ((QuotaVdsGroupConsumptionParameter)parameter).clone(); cloneWrapper.getParameters().add(clone); } return cloneWrapper; }

Target:
public QuotaConsumptionParametersWrapper clone() { QuotaConsumptionParametersWrapper cloneWrapper = new QuotaConsumptionParametersWrapper(getAuditLogable(), canDoActionMessages); cloneWrapper.setParameters(new ArrayList<QuotaConsumptionParameter>()); for (QuotaConsumptionParameter parameter : getParameters()) { cloneWrapper.getParameters().add(parameter.clone()); } return cloneWrapper; }
Source:
public void initialize(URL location, ResourceBundle resources) { try { XMLSettingsLoader loader = new XMLSettingsLoader(DesignerUtil.getSettingsFile()); loadSettings(loader.getSettings()); } catch (IOException ioe) { } initializeLanguageVersionMenu(); initializeViewAnimation(); xpathPanelController.initialiseVersionChoiceBox(xpathVersionChoiceBox); sourceEditorController.languageVersionProperty().bind(languageChoiceBox.getSelectionModel().selectedItemProperty()); xpathPanelController.xpathVersionProperty().bind(xpathVersionChoiceBox.getSelectionModel().selectedItemProperty()); refreshASTButton.setOnAction(e -> onRefreshASTClicked()); licenseMenuItem.setOnAction(this::showLicensePopup); openFileMenuItem.setOnAction(this::onOpenFileClicked); openRecentMenu.setOnAction(e -> updateRecentFilesMenu()); openRecentMenu.setOnShowing(e -> updateRecentFilesMenu()); exportXPathMenuItem.setOnAction(event -> { try { onExportXPathToRuleClicked(event); } catch (IOException e) { } }); fileMenu.setOnShowing(this::onFileMenuShowing); sourceEditorController.refreshAST(); Platform.runLater(() -> sourceEditorController.moveCaret(0, 0)); }

Target:
public void initialize(URL location, ResourceBundle resources) { try { XMLSettingsLoader loader = new XMLSettingsLoader(DesignerUtil.getSettingsFile()); loadSettings(loader.getSettings()); } catch (IOException ioe) { } initializeLanguageVersionMenu(); initializeViewAnimation(); xpathPanelController.initialiseVersionChoiceBox(xpathVersionChoiceBox); sourceEditorController.languageVersionProperty().bind(languageChoiceBox.getSelectionModel().selectedItemProperty()); xpathPanelController.xpathVersionProperty().bind(xpathVersionChoiceBox.getSelectionModel().selectedItemProperty()); refreshASTButton.setOnAction(e -> onRefreshASTClicked()); licenseMenuItem.setOnAction(e -> showLicensePopup()); openFileMenuItem.setOnAction(e -> onOpenFileClicked()); openRecentMenu.setOnAction(e -> updateRecentFilesMenu()); openRecentMenu.setOnShowing(e -> updateRecentFilesMenu()); fileMenu.setOnShowing(e -> onFileMenuShowing()); exportXPathMenuItem.setOnAction(e -> { try { onExportXPathToRuleClicked(); } catch (IOException ex) { ex.printStackTrace(); } }); sourceEditorController.refreshAST(); Platform.runLater(() -> sourceEditorController.moveCaret(0, 0)); }
Source:
private ImageTicket getTestTicket() { ImageTicket ticket = new ImageTicket(); ticket.setId(Guid.createGuidFromString("799030aa-97c3-4354-871e-0adf0556fcbf")); ticket.setSize(1073741824L); ticket.setUrl("https://server:port/imageio/799030aa-97c3-4354-871e-0adf0556fcbf"); ticket.setTimeout(300); ticket.setOps(new String[]{"read", "write"}); return ticket; }

Target:
private ImageTicket getTestTicket() { ImageTicket ticket = new ImageTicket(); ticket.setId(Guid.createGuidFromString("799030aa-97c3-4354-871e-0adf0556fcbf")); ticket.setSize(1073741824L); ticket.setUrl("https://server:port/images/799030aa-97c3-4354-871e-0adf0556fcbf"); ticket.setTimeout(300); ticket.setOps(new String[]{"read", "write"}); return ticket; }
Source:
private static void validateRecord(SpecificRecord record, Properties recordFieldExpectations) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Iterator<Entry<Object,Object>> expectationPropertiesIterator = recordFieldExpectations.entrySet().iterator(); while (expectationPropertiesIterator.hasNext()) { Entry<Object,Object> fieldExpectation = expectationPropertiesIterator.next(); Object currentValue = PropertyUtils.getNestedProperty(record, (String)fieldExpectation.getKey()); if ((currentValue != null && !fieldExpectation.getValue().equals(currentValue.toString())) || (currentValue == null && !NULL_VALUE_INDICATOR.equals(fieldExpectation.getValue()))) { throw new RuntimeException( "invalid field value for path: " + fieldExpectation.getKey() + ", expected: '" + fieldExpectation.getValue() + "', " + "got: '" + currentValue + "' Full object content: " + JsonUtils.toPrettyJSON(record.toString())); } } }

Target:
private static void validateRecord(SpecificRecord record, Properties recordFieldExpectations) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { for (Entry<Object, Object> fieldExpectation : recordFieldExpectations.entrySet()) { Object currentValue = PropertyUtils.getNestedProperty(record, (String)fieldExpectation.getKey()); if ((currentValue != null && !fieldExpectation.getValue().equals(currentValue.toString())) || (currentValue == null && !NULL_VALUE_INDICATOR.equals(fieldExpectation.getValue()))) { throw new RuntimeException( "invalid field value for path: " + fieldExpectation.getKey() + ", expected: '" + fieldExpectation.getValue() + "', " + "got: '" + currentValue + "' Full object content: " + JsonUtils.toPrettyJSON(record.toString())); } } }
Source:
private boolean executeIndicator(Indicator indicator, Connection connection) { String catalogName = getCatalogOrSchemaName(indicator.getAnalyzedElement()); if (needChangeCatalog(connection)) { if (catalogName != null) { changeCatalog(catalogName, connection); } } Expression query = dbms().getInstantiatedExpression(indicator); if (query == null) { traceError("Query not executed for indicator: \"" + AnalysisExecutorHelper.getIndicatorName(indicator) + "\" " + "query is null"); return Boolean.FALSE; } else { try { List<Object[]> myResultSet = executeQuery(catalogName, connection, query.getBody()); Boolean isExecSuccess = indicator.storeSqlResults(myResultSet); if (!isExecSuccess) { traceError("Query not executed for indicator: \"" + AnalysisExecutorHelper.getIndicatorName(indicator) + "\" " + "SQL query: " + query.getBody()); return Boolean.FALSE; } } catch (Exception e) { traceError("Query not executed for indicator: \"" + AnalysisExecutorHelper.getIndicatorName(indicator) + "\" " + "SQL query: " + query.getBody() + ". Exception: " + e.getMessage()); return Boolean.FALSE; } } indicator.setComputed(true); return Boolean.TRUE; }

Target:
private boolean executeIndicator(Indicator indicator, Connection connection) { String catalogName = getCatalogOrSchemaName(indicator.getAnalyzedElement()); if (catalogName != null && needChangeCatalog(connection)) { changeCatalog(catalogName, connection); } Expression query = dbms().getInstantiatedExpression(indicator); if (query == null) { traceError("Query not executed for indicator: \"" + AnalysisExecutorHelper.getIndicatorName(indicator) + "\" " + "query is null"); return Boolean.FALSE; } else { try { List<Object[]> myResultSet = executeQuery(catalogName, connection, query.getBody()); Boolean isExecSuccess = indicator.storeSqlResults(myResultSet); if (!isExecSuccess) { traceError("Query not executed for indicator: \"" + AnalysisExecutorHelper.getIndicatorName(indicator) + "\" " + "SQL query: " + query.getBody()); return Boolean.FALSE; } } catch (Exception e) { traceError("Query not executed for indicator: \"" + AnalysisExecutorHelper.getIndicatorName(indicator) + "\" " + "SQL query: " + query.getBody() + ". Exception: " + e.getMessage()); return Boolean.FALSE; } } indicator.setComputed(true); return Boolean.TRUE; }
Source:
private List<ResponseOutput> buildResponses(List<FeedbackResponseAttributes> responses, FeedbackResponseCommentSearchResultBundle bundle) { List<ResponseOutput> output = new ArrayList<>(); for (FeedbackResponseAttributes response : responses) { output.add(new ResponseOutput(response.getId(), response.giver, null, null, null, response.giverSection, response.recipient, null, null, response.recipientSection, response.responseDetails, getStudentComment(bundle.comments.get(response.getId()), bundle), buildComments(bundle.comments.get(response.getId()), bundle))); } return output; }

Target:
private List<ResponseOutput> buildResponses(List<FeedbackResponseAttributes> responses, FeedbackResponseCommentSearchResultBundle bundle) { List<ResponseOutput> output = new ArrayList<>(); for (FeedbackResponseAttributes response : responses) { output.add(ResponseOutput.builder() .withResponseId(response.getId()) .withGiver(bundle.responseGiverTable.get(response.giver)) .withGiverEmail(response.giver) .withGiverSection(response.giverSection) .withRecipient(bundle.responseRecipientTable.get(response.recipient)) .withRecipientEmail(response.recipient) .withRecipientSection(response.recipientSection) .withResponseDetails(response.responseDetails) .withParticipantComment(getParticipantComment(bundle.comments.get(response.getId()), bundle)) .withInstructorComments(getInstructorComments(bundle.comments.get(response.getId()), bundle)) .build()); } return output; }
Source:
public synchronized void start(ServiceProvider serviceProvider) { timeSource = serviceProvider.getService(TimeSourceService.class).getTimeSource(); managementRegistry = serviceProvider.getService(ManagementRegistryService.class); configuration = managementRegistry.getConfiguration(); cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); scheduledExecutorService = serviceProvider.getService(ExecutionService.class).getScheduledExecutor(configuration.getCollectorExecutorAlias()); if (cacheManager instanceof ObservableCacheManager) { ((ObservableCacheManager)cacheManager).registerListener(this); } }

Target:
public synchronized void start(ServiceProvider serviceProvider) { timeSource = serviceProvider.getService(TimeSourceService.class).getTimeSource(); managementRegistry = serviceProvider.getService(ManagementRegistryService.class); configuration = managementRegistry.getConfiguration(); cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); scheduledExecutorService = serviceProvider.getService(ExecutionService.class).getScheduledExecutor(configuration.getCollectorExecutorAlias()); cacheManager.registerListener(this); }
Source:
private void hideSplashScreen() { try { Class splashScreenClass = Class.forName("com.install4j.api.launcher.SplashScreen"); Method hideMethod = splashScreenClass.getDeclaredMethod("hide"); hideMethod.invoke(null); } catch (ClassNotFoundException e) { log.debug("No install4j splash screen found to close."); } catch (NoSuchMethodException | IllegalAccessException e) { log.warn("Couldn't close install4j splash screen.", e); } catch (InvocationTargetException e) { log.error("Couldn't close install4j splash screen.", e.getCause()); } }

Target:
private static void hideSplashScreen() { try { final Class splashScreenClass = Class.forName("com.install4j.api.launcher.SplashScreen"); final Method hideMethod = splashScreenClass.getDeclaredMethod("hide"); hideMethod.invoke(null); } catch (ClassNotFoundException e) { log.debug("No install4j splash screen found to close."); } catch (NoSuchMethodException | IllegalAccessException e) { log.error("Couldn't close install4j splash screen.", e); } catch (InvocationTargetException e) { log.error("Couldn't close install4j splash screen.", e.getCause()); } }
Source:
public Iterator<PropertyContainer> iterator() { return new Iterator<PropertyContainer>() { private final int size = 2 * value.size() + 1; private int index = 0; private final NodeValue[] nodes = value.nodes(); private final RelationshipValue[] relationships = value.relationships(); @Override public boolean hasNext() { return index < size; } @Override public PropertyContainer next() { PropertyContainer propertyContainer; if ( index % 2 == 0 ) { propertyContainer = mapNode( nodes[index / 2] ); } else { propertyContainer = mapRelationship( relationships[index / 2] ); } index++; return propertyContainer; } }; }

Target:
public Iterator<PropertyContainer> iterator() { return new Iterator<PropertyContainer>() { private final int size = 2 * value.size() + 1; private int index; private final NodeValue[] nodes = value.nodes(); private final RelationshipValue[] relationships = value.relationships(); @Override public boolean hasNext() { return index < size; } @Override public PropertyContainer next() { PropertyContainer propertyContainer; if ( (index & 1) == 0 ) { propertyContainer = mapNode( nodes[index >> 1] ); } else { propertyContainer = mapRelationship( relationships[index >> 1] ); } index++; return propertyContainer; } }; }
Source:
protected ExprEval eval(ExprEval x, ExprEval y) { String castTo = y.stringValue(); if ("string".equals(castTo)) { return ExprEval.of(x.value() == null ? null : String.valueOf(x.value())); } if ("long".equals(castTo)) { return ExprEval.of(x.type() == ExprType.STRING ? Long.valueOf(x.stringValue()) : x.longValue()); } if ("double".equals(castTo)) { return ExprEval.of(x.type() == ExprType.STRING ? Double.valueOf(x.stringValue()) : x.doubleValue()); } throw new IllegalArgumentException("invalid type " + castTo); }

Target:
protected ExprEval eval(ExprEval x, ExprEval y) { ExprType castTo; try { castTo = ExprType.valueOf(y.asString().toUpperCase()); } catch (IllegalArgumentException e) { throw new IAE("invalid type '%s'", y.asString()); } return x.castTo(castTo); }
Source:
private List<BaseReport<V>> constructReport(int iTypeOfReport) { logger.entering(iTypeOfReport); List<BaseReport<V>> lb = new ArrayList<BaseReport<V>>(); BaseReport b; for (String indReport : this.reportData.keySet()) { if (iTypeOfReport == 0) { b = new SummaryReport(indReport); } else if (1 == iTypeOfReport) { b = new DetailsReport(indReport); } else { b = new TestOutputReport(indReport); } b.setLstEntities(this.reportData.get(indReport)); lb.add(b); } logger.exiting(lb); return lb; }

Target:
private List<BaseReport<V>> constructReport(int iTypeOfReport) { logger.entering(iTypeOfReport); List<BaseReport<V>> lb = new ArrayList<BaseReport<V>>(); @SuppressWarnings("rawtypes") BaseReport b; for (String indReport : this.reportData.keySet()) { if (iTypeOfReport == 0) { b = new SummaryReport(indReport); } else if (1 == iTypeOfReport) { b = new DetailsReport(indReport); } else { b = new TestOutputReport(indReport); } b.setLstEntities(this.reportData.get(indReport)); lb.add(b); } logger.exiting(lb); return lb; }
Source:
private void registerToHub(boolean checkPresenceFirst) { if (!checkPresenceFirst || !isAlreadyRegistered(nodeConfig)) { String tmp = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/register"; HttpClient client = httpClientFactory.getHttpClient(); try { URL registration = new URL(tmp); LOG.info("Registering the node to the hub: " + registration); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", registration.toExternalForm()); int port = Integer.parseInt(nodeConfig.getConfigAsString(RegistrationRequest.PORT)); if (port == 0) { port = server.getRealPort(); Map<String, Object> config = nodeConfig.getConfiguration(); config.put(RegistrationRequest.PORT,server.getRealPort()); URL url = new URL(nodeConfig.getConfigAsString(RegistrationRequest.REMOTE_HOST)); String newUrl = "http://" + url.getHost() + ":" + port; config.put(RegistrationRequest.REMOTE_HOST, newUrl); } String json = nodeConfig.toJSON(); r.setEntity(new StringEntity(json,"UTF-8")); HttpHost host = new HttpHost(registration.getHost(), registration.getPort()); HttpResponse response = client.execute(host, r); if (response.getStatusLine().getStatusCode() != 200) { throw new GridException(String.format("The hub responded with %s:%s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } LOG.info("The node is registered to the hub and ready to use"); } catch (Exception e) { throw new GridException("Error sending the registration request: " + e.getMessage()); } } else { LOG.fine("The node is already present on the hub. Skipping registration."); } }

Target:
private void registerToHub(boolean checkPresenceFirst) { if (!checkPresenceFirst || !isAlreadyRegistered(nodeConfig)) { String tmp = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/register"; HttpClient client = httpClientFactory.getHttpClient(); try { URL registration = new URL(tmp); LOG.info("Registering the node to the hub: " + registration); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", registration.toExternalForm()); updateConfigWithRealPort(); String json = nodeConfig.toJSON(); r.setEntity(new StringEntity(json,"UTF-8")); HttpHost host = new HttpHost(registration.getHost(), registration.getPort()); HttpResponse response = client.execute(host, r); if (response.getStatusLine().getStatusCode() != 200) { throw new GridException(String.format("The hub responded with %s:%s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } LOG.info("The node is registered to the hub and ready to use"); } catch (Exception e) { throw new GridException("Error sending the registration request: " + e.getMessage()); } } else { LOG.fine("The node is already present on the hub. Skipping registration."); } }
Source:
public void endElement(String uri, String localName, String qName) { if (version.equals("2") && localName.equals(TaskRepositoriesExternalizer.ELEMENT_TASK_REPOSITORY) && currentRepository != null) { taskRepositories.add(currentRepository); currentRepository = null; } }

Target:
public void endElement(String uri, String localName, String qName) { if (currentV2Repository != null && localName.equals(TaskRepositoriesExternalizer.ELEMENT_TASK_REPOSITORYV2)) { taskRepositoriesV2.add(currentV2Repository); currentV2Repository = null; } }
Source:
public boolean test( Object value ) { assert false : "StringPrefixPredicate.test() has not been tested yet... Add tests and remove assert"; return value != null && value instanceof String && ((String)value).startsWith( prefix ); }

Target:
public boolean test( Object value ) { return value != null && value instanceof String && ((String)value).startsWith( prefix ); }
Source:
public static VirtualMachineInstance create(final String platformUpdateDomain, final String platformFaultDomain, final List<VirtualMachineStatus> statuses) { return new AutoValue_VirtualMachineInstance(platformUpdateDomain, platformFaultDomain, statuses); }

Target:
public static VirtualMachineInstance create(final String platformUpdateDomain, final String platformFaultDomain, final List<VirtualMachineStatus> statuses) { return new AutoValue_VirtualMachineInstance(platformUpdateDomain, platformFaultDomain, statuses == null ? null : ImmutableList.copyOf(statuses)); }
Source:
public static Optional<DispatchQueueFactory> getDispatchQueueFactory() { if (dispatchQueueFactory != null) { return Optional.of(dispatchQueueFactory); } if (context != null) { try { dispatchQueueFactory = context.getService(context.getServiceReference(DispatchQueueFactory.class)); return Optional.of(dispatchQueueFactory); } catch (Exception e) { LOG.error("Exception while retrieving DispatchQueueFactory Service from registry", e); throw e; } } return Optional.empty(); }

Target:
public static Optional<DispatchQueueFactory> getDispatchQueueFactory() { if (dispatchQueueFactory != null) { return Optional.of(dispatchQueueFactory); } if (context != null) { try { ServiceReference<DispatchQueueFactory> serviceReference = context.getServiceReference(DispatchQueueFactory.class); return serviceReference == null ? Optional.empty() : Optional.of(context.getService(serviceReference)); } catch (Exception e) { LOG.error("Exception while retrieving DispatchQueueFactory Service from registry", e); throw e; } } return Optional.empty(); }
Source:
public String toString() { return String.format("long@0x%x=0x%x (%d)", Pointer.nativeValue(getPointer()), getValue(), getValue()); }

Target:
public String toString() { return String.format("long@0x%1$x=0x%2$x (%2$d)", Pointer.nativeValue(getPointer()), getValue()); }
Source:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); m_closeAllExecutor = CoreUtils.getSingleThreadExecutor("HttpClientInterface-closeAll"); m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); }

Target:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); }
Source:
public Map<String, Arg> getArguments() { return ImmutableBiMap.copyOf(this.arguments); }

Target:
public Map<String, Arg> getArguments() { return this.arguments; }
Source:
private Estimate calculateDataSize( Map<String, PartitionStatistics> statisticsSample, String columnName, Estimate rowCount, Estimate nullsFraction, OptionalDouble rowsPerPartition) { if (rowCount.isValueUnknown() || !rowsPerPartition.isPresent()) { return Estimate.unknownValue(); } double knownNonNullRowCount = 0; double knownDataSize = 0; for (PartitionStatistics statistics : statisticsSample.values()) { double partitionRowCount = orElse(statistics.getBasicStatistics().getRowCount(), rowsPerPartition.getAsDouble()); HiveColumnStatistics partitionColumnStatistics = statistics.getColumnStatistics().get(columnName); if (partitionColumnStatistics == null || !partitionColumnStatistics.getAverageColumnLength().isPresent()) { continue; } double partitionNonNullCount = partitionRowCount - partitionColumnStatistics.getNullsCount().orElse(0); if (partitionNonNullCount < 0) { log.debug("null count bigger than row count in partition stats"); continue; } knownNonNullRowCount += partitionNonNullCount; knownDataSize += partitionColumnStatistics.getAverageColumnLength().getAsDouble() * partitionNonNullCount; } if (knownNonNullRowCount <= 0) { return Estimate.unknownValue(); } double nonNullCount = rowCount.getValue() * (1 - (nullsFraction.isValueUnknown() ? nullsFraction.getValue() : 0)); return new Estimate(knownDataSize / knownNonNullRowCount * nonNullCount); }

Target:
private Estimate calculateDataSize( Map<String, PartitionStatistics> statisticsSample, String columnName, Estimate rowCount, Estimate nullsFraction, OptionalDouble rowsPerPartition) { if (rowCount.isValueUnknown() || !rowsPerPartition.isPresent()) { return Estimate.unknownValue(); } double knownNonNullRowCount = 0; double knownDataSize = 0; for (PartitionStatistics statistics : statisticsSample.values()) { double partitionRowCount = orElse(statistics.getBasicStatistics().getRowCount(), rowsPerPartition.getAsDouble()); HiveColumnStatistics partitionColumnStatistics = statistics.getColumnStatistics().get(columnName); if (partitionColumnStatistics == null || !partitionColumnStatistics.getAverageColumnLength().isPresent()) { continue; } double partitionNonNullCount = partitionRowCount - partitionColumnStatistics.getNullsCount().orElse(0); if (partitionNonNullCount < 0) { log.debug("null count bigger than row count in partition stats"); continue; } knownNonNullRowCount += partitionNonNullCount; knownDataSize += partitionColumnStatistics.getAverageColumnLength().getAsDouble() * partitionNonNullCount; } if (knownNonNullRowCount == 0) { return Estimate.unknownValue(); } double nonNullCount = rowCount.getValue() * (1 - (nullsFraction.isValueUnknown() ? 0 : nullsFraction.getValue())); return new Estimate(knownDataSize / knownNonNullRowCount * nonNullCount); }
Source:
public void contextRefreshed() { setDispositionConfig(config); setMetadataSharingResolvers(); CloseStaleVisitsSetup.setupCloseStaleVisitsTask(); NameSupport nameSupport = Context.getRegisteredComponent("nameSupport", NameSupport.class); NameTemplateSetup.configureNameTemplate(nameSupport); NameTemplateSetup.configureNameTemplate(NameSupport.getInstance()); }

Target:
public void contextRefreshed() { setDispositionConfig(config); MetadataSharingSetup.setMetadataSharingResolvers(); CloseStaleVisitsSetup.setupCloseStaleVisitsTask(); NameSupport nameSupport = Context.getRegisteredComponent("nameSupport", NameSupport.class); NameTemplateSetup.configureNameTemplate(nameSupport); NameTemplateSetup.configureNameTemplate(NameSupport.getInstance()); }
Source:
public AbfsPerfTracker getAbfsPerfTracker() { return abfsPerfTracker; }

Target:
protected AbfsPerfTracker getAbfsPerfTracker() { return abfsPerfTracker; }
Source:
public MessageProducer getMessageProducer(Session session, Destination destination) throws JMSConnectorException { MessageProducer messageProducer; if (cachedMessageConsumer == null) { messageProducer = createMessageProducer(session, destination); } else { messageProducer = cachedMessageProducer; } return messageProducer; }

Target:
public MessageProducer getMessageProducer(Session session, Destination destination) throws JMSConnectorException { MessageProducer messageProducer; if (cachedMessageProducer == null) { messageProducer = createMessageProducer(session, destination); } else { messageProducer = cachedMessageProducer; } return messageProducer; }
Source:
public Status delete(String table, String key) { try { PreparedStatement stmt = deleteStmt.get(); if (stmt == null) { stmt = session.prepare(QueryBuilder.delete().from(table) .where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker()))); stmt.setConsistencyLevel(writeConsistencyLevel); if (trace) { stmt.enableTracing(); } PreparedStatement prevStmt = deleteStmt.getAndSet(stmt); if (prevStmt != null) { stmt = prevStmt; } } logger.debug(stmt.getQueryString()); logger.debug("key = {}", key); session.execute(stmt.bind(key)); return Status.OK; } catch (Exception e) { e.printStackTrace(); logger.error("Error deleting key: {}", key); } return Status.ERROR; }

Target:
public Status delete(String table, String key) { try { PreparedStatement stmt = deleteStmt.get(); if (stmt == null) { stmt = session.prepare(QueryBuilder.delete().from(table) .where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker()))); stmt.setConsistencyLevel(writeConsistencyLevel); if (trace) { stmt.enableTracing(); } PreparedStatement prevStmt = deleteStmt.getAndSet(stmt); if (prevStmt != null) { stmt = prevStmt; } } logger.debug(stmt.getQueryString()); logger.debug("key = {}", key); session.execute(stmt.bind(key)); return Status.OK; } catch (Exception e) { logger.error(MessageFormatter.format("Error deleting key: {}", key).getMessage(), e); } return Status.ERROR; }
Source:
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { RefactoringStatus refactoringStatus = RefactoringStatus.create(Resources.checkInSync(fResource)); if (refactoringStatus != null && !refactoringStatus.isOK()) { boolean autoRefresh= Platform.getPreferencesService().getBoolean(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH, false, null); if (autoRefresh) { fResource.refreshLocal(IResource.DEPTH_INFINITE, pm); refactoringStatus= RefactoringStatus.create(Resources.checkInSync(fResource)); } } return refactoringStatus; }

Target:
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { IStatus status= Resources.checkInSync(fResource); if (!status.isOK()) { boolean autoRefresh= Platform.getPreferencesService().getBoolean(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH, false, null); if (autoRefresh) { fResource.refreshLocal(IResource.DEPTH_INFINITE, pm); status= Resources.checkInSync(fResource); } } return RefactoringStatus.create(status); }
Source:
public void loadConfig() { Map<String, Object> ret = readConfigFromFile(configFilename); for (String id : TypeUtils.getListOfStrings(ret.get(POLICY_CONF.HEALTH_POLICIES.key))) { configs.put(id, (Map<String, String>) ret.get(id)); } }

Target:
public void loadConfig() { Map<String, Object> ret = readConfigFromFile(configFilename); for (String id : TypeUtils.getListOfStrings(ret.get(PolicyConfigKey.HEALTH_POLICIES.key))) { configs.put(id, (Map<String, Object>) ret.get(id)); } }
Source:
public Observable<Boolean> progressObservable() { return ResponseOrError.combineProgressObservable(ImmutableList.of( ResponseOrError.transform(postsDao.postSuccesObserver()))) .lift(OperatorSampleWithLastWithObservable.<Boolean>create(showProgress)); }

Target:
public Observable<Boolean> progressObservable() { return showProgress; }
Source:
public NonLinearLeastSquareWithPenalty(final Decomposition<?> decomposition, final MatrixAlgebra algebra, final double eps) { ArgumentChecker.notNull(decomposition, "decomposition"); ArgumentChecker.notNull(algebra, "algebra"); ArgumentChecker.isTrue(eps > 0, "must have possitive eps"); _decomposition = decomposition; _algebra = algebra; _eps = eps; }

Target:
public NonLinearLeastSquareWithPenalty(final Decomposition<?> decomposition, final MatrixAlgebra algebra, final double eps) { ArgumentChecker.notNull(decomposition, "decomposition"); ArgumentChecker.notNull(algebra, "algebra"); ArgumentChecker.isTrue(eps > 0, "must have positive eps"); _decomposition = decomposition; _algebra = algebra; _eps = eps; }
Source:
private synchronized void handleProcessTerminatedEvent(ProcessTerminatedDebugListener listener) { if( listener.myProcess != null && !listener.myProcess.equals(getProcess())) return; System.out.println(getProcess()); if( getServer().getServerState() != IServer.STATE_STOPPED) { stopPolling(); addProcessTerminatedEvent(); getActualBehavior().setServerStopped(); } DebugPlugin.getDefault().removeDebugEventListener(listener); processListener = null; process = null; nextStopRequiresForce = false; }

Target:
private synchronized void handleProcessTerminatedEvent(ProcessTerminatedDebugListener listener) { if( listener.myProcess != null && !listener.myProcess.equals(getProcess())) return; if( getServer().getServerState() != IServer.STATE_STOPPED) { stopPolling(); addProcessTerminatedEvent(); getActualBehavior().setServerStopped(); } DebugPlugin.getDefault().removeDebugEventListener(listener); processListener = null; process = null; nextStopRequiresForce = false; }
Source:
public void postBegin() { super.postBegin(); airBlock = blockManager.getBlock(BlockManager.AIR_ID); }

Target:
public void postBegin() { blockItemFactory = new BlockItemFactory(entityManager); airBlock = blockManager.getBlock(BlockManager.AIR_ID); }
Source:
public PropertyParameter(String name, String... values) { m_name = name.toUpperCase(); addValues(values); }

Target:
public PropertyParameter(String name, String... values) { Assertions.assertNotNull(name); m_name = name.toUpperCase(); addValues(values); }
Source:
public static String maskMessage(String message, Pattern maskPattern, String maskString) { Matcher matcher = maskPattern.matcher(message); if (matcher.find()) { StringBuilder maskedMessage = new StringBuilder(""); for (int i = 0; i <= matcher.groupCount(); i++) { int start; int end; if (i == 0) { start = 0; } else { start = matcher.end(i); maskedMessage.append(maskString); } if (i == matcher.groupCount()) { end = message.length() - 1; } else { end = matcher.start(i + 1) - 1; } if (start > end || end >= message.length()) { continue; } for (int j = start; j <= end; j++) { maskedMessage.append(message.charAt(j)); } } return String.valueOf(maskedMessage); } return message; }

Target:
public static String maskMessage(String message, Pattern maskPattern, String maskString) { Matcher matcher = maskPattern.matcher(message); List<Pair<Integer, Integer>> groups = new ArrayList<>(); while (matcher.find()) { for (int i = 1; i <= matcher.groupCount(); i++) { groups.add(new Pair<>(matcher.start(i), matcher.end(i))); } } if (groups.size() == 0) { return message; } StringBuilder maskedMessage = new StringBuilder(""); for (int i = 0; i <= groups.size(); i++) { int start; int end; if (i == 0) { start = 0; } else { start = groups.get(i-1).getSecond(); maskedMessage.append(maskString); } if (i == groups.size()) { end = message.length() - 1; } else { end = groups.get(i).getFirst() - 1; } maskedMessage.append(message.substring(start, end+1)); } return String.valueOf(maskedMessage); }
Source:
public boolean canFillFluidType(FluidStack fluid) { return true; }

Target:
public boolean canFillFluidType(FluidStack fluid) { return canFill(); }
Source:
public void testSelection() { getTreeViewer().expandToLevel(element_1, AbstractTreeViewer.ALL_LEVELS); getTreeViewer().expandToLevel(element_2, AbstractTreeViewer.ALL_LEVELS); getTreeViewer().setSelection(new StructuredSelection(element_1_3)); ISelection selection = getTreeViewer().getStructuredSelection(); assertTrue(selection instanceof ITreeSelection); ITreeSelection treeSelection = (ITreeSelection) selection; assertEquals(new TreeSelection(new TreePath(new Object[] { element_1, element_1_3 }), null), treeSelection); Widget[] items = getTreeViewer().testFindItems(element_2_1_2); TreeItem[] treeItems = new TreeItem[items.length]; System.arraycopy(items, 0, treeItems, 0, items.length); assertEquals(4, treeItems.length); for (TreeItem treeItem : treeItems) { assertNotNull(treeItem); } getTreeViewer().getTree().setSelection(treeItems); treeSelection = getTreeViewer().getStructuredSelection(); List paths = Arrays.asList(treeSelection.getPaths()); assertEquals(4, paths.size()); assertTrue(paths.contains(treePath_1_2_21_212)); assertTrue(paths.contains(treePath_1_21_212)); assertTrue(paths.contains(treePath_1_212)); assertTrue(paths.contains(treePath_2_21_212)); getTreeViewer().setSelection( new TreeSelection(new TreePath[] { treePath_2_21_212 }, null)); assertEquals(1, getTreeViewer().getTree().getSelectionCount()); assertMatchingPath(treePath_2_21_212, getTreeViewer().getTree() .getSelection()[0]); }

Target:
public void testSelection() { getTreeViewer().expandToLevel(element_1, AbstractTreeViewer.ALL_LEVELS); getTreeViewer().expandToLevel(element_2, AbstractTreeViewer.ALL_LEVELS); getTreeViewer().setSelection(new StructuredSelection(element_1_3)); ITreeSelection treeSelection = getTreeViewer().getStructuredSelection(); assertEquals(new TreeSelection(new TreePath(new Object[] { element_1, element_1_3 }), null), treeSelection); Widget[] items = getTreeViewer().testFindItems(element_2_1_2); TreeItem[] treeItems = new TreeItem[items.length]; System.arraycopy(items, 0, treeItems, 0, items.length); assertEquals(4, treeItems.length); for (TreeItem treeItem : treeItems) { assertNotNull(treeItem); } getTreeViewer().getTree().setSelection(treeItems); treeSelection = getTreeViewer().getStructuredSelection(); List paths = Arrays.asList(treeSelection.getPaths()); assertEquals(4, paths.size()); assertTrue(paths.contains(treePath_1_2_21_212)); assertTrue(paths.contains(treePath_1_21_212)); assertTrue(paths.contains(treePath_1_212)); assertTrue(paths.contains(treePath_2_21_212)); getTreeViewer().setSelection( new TreeSelection(new TreePath[] { treePath_2_21_212 }, null)); assertEquals(1, getTreeViewer().getTree().getSelectionCount()); assertMatchingPath(treePath_2_21_212, getTreeViewer().getTree() .getSelection()[0]); }
Source:
private DispatchedBatchLoader dispatchBatchLoader(DataLoaderRegistry dataLoaderRegistry, String key) { final DataLoader<Object, DataFetcherResult> dataLoader = dataLoaderRegistry.getDataLoader(key); final int dispatchDepth = dataLoader.dispatchDepth(); return new DispatchedBatchLoader<>(key, dispatchDepth, dispatchDepth > 0 ? dataLoader.dispatch() : completedFuture(emptyList())); }

Target:
private DataLoaderDispatchCall dispatchBatchLoader(DataLoaderRegistry dataLoaderRegistry, String key) { final DataLoader<Object, DataFetcherResult> dataLoader = dataLoaderRegistry.getDataLoader(key); return new DataLoaderDispatchCall<>(dataLoader.dispatchDepth(), dataLoader.dispatch()); }
Source:
protected void doExecute() throws Exception { if (skip) { return; } checkServerHomeExists(); checkServerDirectoryExists(); if (appArchive != null && appArtifact != null) { throw new MojoExecutionException(messages.getString("error.app.set.twice")); } if (appArtifact != null) { Artifact artifact = getArtifact(appArtifact); appArchive = artifact.getFile(); log.info(MessageFormat.format(messages.getString("info.variable.set"), "artifact based application", appArtifact)); } else if (appArchive != null) { log.info(MessageFormat.format(messages.getString("info.variable.set"), "non-artifact based application", appArchive)); } else { throw new MojoExecutionException("Nothing to deploy - appArchive or appArtifact must be set."); } if (!appArchive.exists() || appArchive.isDirectory()) { throw new MojoExecutionException("Application file does not exist or is a directory: " + appArchive); } log.info(MessageFormat.format(messages.getString("info.deploy.app"), appArchive.getCanonicalPath())); DeployTask deployTask = (DeployTask) ant.createTask("antlib:net/wasdev/wlp/ant:deploy"); if (deployTask == null) { throw new IllegalStateException("The Liberty deploy Ant task not found. Verify that the required version of the wlp-anttasks.jar is available."); } deployTask.setInstallDir(installDirectory); deployTask.setServerName(serverName); deployTask.setUserDir(userDirectory); deployTask.setOutputDir(outputDirectory); deployTask.setFile(appArchive); deployTask.setDeployName(appDeployName); deployTask.setTimeout(Long.toString(timeout*1000)); deployTask.execute(); }

Target:
protected void doExecute() throws Exception { if (skip) { return; } checkServerHomeExists(); checkServerDirectoryExists(); if (appArchive != null && appArtifact != null) { throw new MojoExecutionException(messages.getString("error.app.set.twice")); } if (appArtifact != null) { Artifact artifact = getArtifact(appArtifact); appArchive = artifact.getFile(); log.info(MessageFormat.format(messages.getString("info.variable.set"), "artifact based application", appArtifact)); } else if (appArchive != null) { log.info(MessageFormat.format(messages.getString("info.variable.set"), "non-artifact based application", appArchive)); } else { throw new MojoExecutionException("Nothing to deploy - appArchive or appArtifact must be set."); } if (!appArchive.exists() || appArchive.isDirectory()) { throw new MojoExecutionException("Application file does not exist or is a directory: " + appArchive); } log.info(MessageFormat.format(messages.getString("info.deploy.app"), appArchive.getCanonicalPath())); DeployTask deployTask = (DeployTask) ant.createTask("antlib:net/wasdev/wlp/ant:deploy"); if (deployTask == null) { throw new IllegalStateException(MessageFormat.format(messages.getString("error.dependencies.not.found"), "deploy")); } deployTask.setInstallDir(installDirectory); deployTask.setServerName(serverName); deployTask.setUserDir(userDirectory); deployTask.setOutputDir(outputDirectory); deployTask.setFile(appArchive); deployTask.setDeployName(appDeployName); deployTask.setTimeout(Long.toString(timeout*1000)); deployTask.execute(); }
Source:
public Workflow findWorkflowByIdAndCheckWorkflowAndUser(Long entryId, User user) { Workflow workflow = workflowDAO.findById(entryId); checkEntry(workflow); checkUser(user, workflow); return workflow; }

Target:
private Workflow findWorkflowByIdAndCheckWorkflowAndUser(Long entryId, User user) { Workflow workflow = workflowDAO.findById(entryId); checkEntry(workflow); checkUser(user, workflow); return workflow; }
Source:
protected void handlePost(HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException { if (GET_ALL_EXECUTIONS_URI.match(req.getRequestURI(), new HashMap<>())) { ExecutionParameters executionParameters = extractExecutionParameters(req, resp, session); if (executionParameters == null) { return; } String executionId; try { executionId = executionService.createExecution(executionParameters); } catch (CloudFlowValidationException e) { sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } catch (CloudFlowException e) { sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DEFAULT_500_ERROR_MESSAGE); return; } logger.info(String.format("New execution of flow %s was successfully queued with id %s", executionParameters.getFlowId(), executionId)); resp.setHeader("Location", GET_SINGLE_EXECUTION_URI.createURI(executionId)); sendResponse(resp, HttpServletResponse.SC_CREATED, new HashMap<>()); } else { sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, DEFAULT_404_ERROR_MESSAGE); } }

Target:
protected void handlePost(HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException { String requestURI = req.getRequestURI(); if (GET_ALL_EXECUTIONS_URI.match(requestURI, new HashMap<>())) { handleCreateExecution(req, resp, session); } else { sendErrorResponse(resp, HttpServletResponse.SC_NOT_FOUND, DEFAULT_404_ERROR_MESSAGE); } }
Source:
public void shouldDeliverMessageWithoutKeepAliveHeaderUsingHttp2() { int httpsPort = Ports.nextAvailable(); String httpsEndpoint = "https://localhost:" + httpsPort; Undertow http2Server = http2Server(httpsPort, exchange -> { if (exchange.getRequestHeaders().contains("keep-alive")) { fail("Keep-Alive header should not be present in HTTP/2 request headers"); } else { exchange.getResponseSender().send(Integer.toString(incomingCounter.incrementAndGet())); } }); http2Server.start(); Topic topic = createTopicAndSubscription(httpsEndpoint); Response response = publisher.publish(topic.getQualifiedName(), MESSAGE_BODY); assertThat(response).hasStatus(CREATED); wait.until(() -> assertThat(incomingCounter.intValue()).isPositive()); http2Server.stop(); }

Target:
public void shouldDeliverMessageWithoutKeepAliveHeaderUsingHttp2() { int httpsPort = Ports.nextAvailable(); HttpString keepAliveHeader = new HttpString("Keep-Alive"); String httpsEndpoint = "https://localhost:" + httpsPort; Undertow http2Server = http2Server(httpsPort, exchange -> { if (!exchange.getProtocol().equals(HTTP_2_0)) { fail("Exchange protocol should be set to HTTP/2"); } if (exchange.getRequestHeaders().contains(keepAliveHeader)) { fail("Keep-Alive header should not be present in HTTP/2 request headers"); } else { exchange.getResponseSender().send(Integer.toString(incomingCounter.incrementAndGet())); } }); http2Server.start(); Topic topic = createTopicAndSubscriptionWithHttp2Enabled(httpsEndpoint); Response response = publisher.publish(topic.getQualifiedName(), MESSAGE_BODY); assertThat(response).hasStatus(CREATED); wait.until(() -> assertThat(incomingCounter.intValue()).isPositive()); http2Server.stop(); }
Source:
public static boolean isValid(String acc) { boolean looksLikeSRA = false; File f = new File(acc); if (f.isFile()) { try { byte[] buffer = new byte[8]; byte[] signature1 = "NCBI.sra".getBytes(); byte[] signature2 = "NCBInenc".getBytes(); InputStream is = new FileInputStream(f); int numRead = is.read(buffer); is.close(); looksLikeSRA = numRead == buffer.length && (Arrays.equals(buffer, signature1) || Arrays.equals(buffer, signature2)); } catch (IOException e) { looksLikeSRA = false; } } else if (f.exists()) { looksLikeSRA = false; } else { looksLikeSRA = acc.toUpperCase().matches ( "^[SED]RR[0-9]{6,9}$" ); } if (!looksLikeSRA) return false; return isSupported() && NGS.isValid(acc); }

Target:
public static boolean isValid(String acc) { boolean looksLikeSRA = false; File f = new File(acc); if (f.isFile()) { byte[] buffer = new byte[8]; byte[] signature1 = "NCBI.sra".getBytes(); byte[] signature2 = "NCBInenc".getBytes(); try (InputStream is = new FileInputStream(f)) { int numRead = is.read(buffer); looksLikeSRA = numRead == buffer.length && (Arrays.equals(buffer, signature1) || Arrays.equals(buffer, signature2)); } catch (IOException e) { looksLikeSRA = false; } } else if (f.exists()) { looksLikeSRA = false; } else { looksLikeSRA = acc.toUpperCase().matches ( "^[SED]RR[0-9]{6,9}$" ); } if (!looksLikeSRA) return false; return isSupported() && NGS.isValid(acc); }