auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void initialize() { choseSortingTypeChoiceBox.setVisible(false); Map<SortingOrder, String> sortingOrderToString = new HashMap<>(); Arrays.stream(SortingOrder.values()) .forEach(sortingOrder -> sortingOrderToString.put(sortingOrder, i18n.get(sortingOrder.getDisplayNameKey()))); choseSortingTypeChoiceBox.setConverter(new StringConverter<SortingOrder>() { @Override public String toString(SortingOrder sortingOrder) { return sortingOrderToString.get(sortingOrder); } @Override public SortingOrder fromString(String string) { return sortingOrderToString.entrySet().stream().filter(sortingOrderStringEntry -> sortingOrderStringEntry.getValue().equals(string)).findFirst().get().getKey(); } }); ObservableList<Game> games = gameService.getGames(); filteredItems = new FilteredList<>(games); filteredItems.setPredicate(OPEN_CUSTOM_GAMES_PREDICATE); if (tilesButton.getId().equals(preferencesService.getPreferences().getGamesViewMode())) { viewToggleGroup.selectToggle(tilesButton); tilesButton.getOnAction().handle(null); } else { viewToggleGroup.selectToggle(tableButton); tableButton.getOnAction().handle(null); } viewToggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> { if (newValue == null) { if (oldValue != null) { viewToggleGroup.selectToggle(oldValue); } else { viewToggleGroup.selectToggle(viewToggleGroup.getToggles().get(0)); } return; } preferencesService.getPreferences().setGamesViewMode(((ToggleButton) newValue).getId()); preferencesService.storeInBackground(); }); setSelectedGame(null); eventBus.register(this); }

Target:
public void initialize() { chooseSortingTypeChoiceBox.setVisible(false); chooseSortingTypeChoiceBox.setConverter(new StringConverter<TilesSortingOrder>() { @Override public String toString(TilesSortingOrder tilesSortingOrder) { return i18n.get(tilesSortingOrder.getDisplayNameKey()); } @Override public TilesSortingOrder fromString(String string) { throw new UnsupportedOperationException("Not supported"); } }); ObservableList<Game> games = gameService.getGames(); filteredItems = new FilteredList<>(games); filteredItems.setPredicate(OPEN_CUSTOM_GAMES_PREDICATE); if (tilesButton.getId().equals(preferencesService.getPreferences().getGamesViewMode())) { viewToggleGroup.selectToggle(tilesButton); tilesButton.getOnAction().handle(null); } else { viewToggleGroup.selectToggle(tableButton); tableButton.getOnAction().handle(null); } viewToggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> { if (newValue == null) { if (oldValue != null) { viewToggleGroup.selectToggle(oldValue); } else { viewToggleGroup.selectToggle(viewToggleGroup.getToggles().get(0)); } return; } preferencesService.getPreferences().setGamesViewMode(((ToggleButton) newValue).getId()); preferencesService.storeInBackground(); }); setSelectedGame(null); eventBus.register(this); }
Source:
public void getRequestUrlTest() { String path = "this is a path ${variable} ${empty}"; expect(request.getPath()).andReturn(path); Map<String, Object> pathParams = new TreeMap<>(); pathParams.put("variable", "variable"); pathParams.put("empty", null); expect(request.getPathParams()).andReturn(pathParams); replay(request); assertThat(ramlRequestAdapter.getRequestUrl(path, false), equalTo("this is a path variable ")); }

Target:
public void getRequestUrlTest() { String path = "this is a path ${variable} ${empty}"; expect(request.getPath()).andReturn(path); Map<String, Object> pathParams = new TreeMap<>(); pathParams.put("variable", "variable"); pathParams.put("empty", null); expect(request.getPathParams()).andReturn(pathParams); replay(request); assertThat(ramlRequestAdapter.getRequestUrl(path, false), equalTo("this is a path variable ")); verify(request); }
Source:
public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_segments.clear(); m_closed = true; }

Target:
public synchronized void close() throws IOException { if (m_closed) { return; } m_readCursors.clear(); for (PBDSegment segment : m_segments.values()) { segment.close(); } m_closed = true; }
Source:
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) { checkNotNull(pred, "predicate cannot be null"); checkNotNull(columns, "columns cannot be null"); return pred.accept(new StatisticsFilter(columns)); }

Target:
public static boolean canDrop(FilterPredicate pred, List<ColumnChunkMetaData> columns) { checkNotNull(pred, "pred"); checkNotNull(columns, "columns"); return pred.accept(new StatisticsFilter(columns)); }
Source:
private String getRolloverTarget(Index index, ClusterState currentState) { IndexAbstraction indexAbstraction = currentState.metadata().getIndicesLookup().get(index.getName()); final String rolloverTarget; if (indexAbstraction.getParentDataStream() != null) { rolloverTarget = indexAbstraction.getParentDataStream().getDataStream().getName(); } else { IndexMetadata indexMetadata = currentState.metadata().index(index); String rolloverAlias = RolloverAction.LIFECYCLE_ROLLOVER_ALIAS_SETTING.get(indexMetadata.getSettings()); if (Strings.isNullOrEmpty(rolloverAlias)) { throw new IllegalStateException("setting [" + RolloverAction.LIFECYCLE_ROLLOVER_ALIAS + "] is not set on index [" + indexMetadata.getIndex().getName() + "]"); } rolloverTarget = rolloverAlias; } return rolloverTarget; }

Target:
private static String getRolloverTarget(Index index, ClusterState currentState) { IndexAbstraction indexAbstraction = currentState.metadata().getIndicesLookup().get(index.getName()); final String rolloverTarget; if (indexAbstraction.getParentDataStream() != null) { rolloverTarget = indexAbstraction.getParentDataStream().getName(); } else { IndexMetadata indexMetadata = currentState.metadata().index(index); String rolloverAlias = RolloverAction.LIFECYCLE_ROLLOVER_ALIAS_SETTING.get(indexMetadata.getSettings()); if (Strings.isNullOrEmpty(rolloverAlias)) { throw new IllegalStateException("setting [" + RolloverAction.LIFECYCLE_ROLLOVER_ALIAS + "] is not set on index [" + indexMetadata.getIndex().getName() + "]"); } rolloverTarget = rolloverAlias; } return rolloverTarget; }
Source:
public static Long getValueAsLong(final byte[] key, final Map<byte[], byte[]> taskValues) { byte[] value = taskValues.get(key); if (value != null) { try { long retValue = Bytes.toLong(value); return retValue; } catch (NumberFormatException nfe) { LOG.error("Caught NFE while converting to long " + nfe.getMessage()); nfe.printStackTrace(); return 0L; } catch (IllegalArgumentException iae ) { LOG.error("Caught IAE while converting to long " + iae.getMessage()); iae.printStackTrace(); return 0L; } } else { return 0L; } }

Target:
public static long getValueAsLong(final byte[] key, final Map<byte[], byte[]> taskValues) { byte[] value = taskValues.get(key); if (value != null) { try { long retValue = Bytes.toLong(value); return retValue; } catch (NumberFormatException nfe) { LOG.error("Caught NFE while converting to long ", nfe); return 0L; } catch (IllegalArgumentException iae ) { LOG.error("Caught IAE while converting to long ", iae); return 0L; } } else { return 0L; } }
Source:
public int createApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) throws IdentityApplicationManagementException { try { startTenantFlow(tenantDomain, userName); List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners(); for (ApplicationMgtListener listener : listeners) { if(!listener.doPreCreateApplication(serviceProvider)){ return 0; } } ApplicationMgtUtil.createAppRole(serviceProvider.getApplicationName()); ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO(); ApplicationMgtUtil.storePermission(serviceProvider.getApplicationName(), serviceProvider.getPermissionAndRoleConfig()); int applicationId = appDAO.createApplication(serviceProvider, tenantDomain); for (ApplicationMgtListener listener : listeners) { if(!listener.doPostCreateApplication(serviceProvider)){ return 0; } } return applicationId; } catch (Exception e) { try { ApplicationMgtUtil.deleteAppRole(serviceProvider.getApplicationName()); ApplicationMgtUtil.deletePermissions(serviceProvider.getApplicationName()); } catch (Exception ignored) { if (log.isDebugEnabled()) { log.debug("Ignored the exception occurred while trying to delete the role : ", e); } } String error = "Error occurred while creating the application : " + serviceProvider.getApplicationName(); log.error(error, e); throw new IdentityApplicationManagementException(error, e); } finally { endTenantFlow(); } }

Target:
public void createApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) throws IdentityApplicationManagementException { List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners(); for (ApplicationMgtListener listener : listeners) { if (!listener.doPreCreateApplication(serviceProvider,tenantDomain, userName )) { return; } } startTenantFlow(tenantDomain, userName); try { ApplicationMgtUtil.createAppRole(serviceProvider.getApplicationName()); ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO(); ApplicationMgtUtil.storePermission(serviceProvider.getApplicationName(), serviceProvider.getPermissionAndRoleConfig()); appDAO.createApplication(serviceProvider, tenantDomain); } catch (Exception e) { try { ApplicationMgtUtil.deleteAppRole(serviceProvider.getApplicationName()); ApplicationMgtUtil.deletePermissions(serviceProvider.getApplicationName()); } catch (Exception ignored) { if (log.isDebugEnabled()) { log.debug("Ignored the exception occurred while trying to delete the role : ", e); } } String error = "Error occurred while creating the application : " + serviceProvider.getApplicationName(); log.error(error, e); throw new IdentityApplicationManagementException(error, e); } finally { endTenantFlow(); } for (ApplicationMgtListener listener : listeners) { if (!listener.doPostCreateApplication(serviceProvider, tenantDomain, userName)) { return; } } }
Source:
Mono<PartitionPublishingState> getPartitionPublishingState(String partitionId) { PartitionPublishingState publishingState = getClientPartitionPublishingState(partitionId); if (publishingState.isFromLink()) { return Mono.just(publishingState); } else { return withRetry(this.getSendLink(partitionId).flatMap(amqpSendLink -> Mono.just(this.getClientPartitionPublishingState(partitionId))), retryOptions.getTryTimeout(), retryPolicy); } }

Target:
Mono<PartitionPublishingState> getPartitionPublishingState(String partitionId) { PartitionPublishingState publishingState = getClientPartitionPublishingState(partitionId); if (publishingState.isFromLink()) { return Mono.defer(() -> Mono.just(publishingState)); } else { return withRetry(getSendLink(partitionId).flatMap(amqpSendLink -> Mono.just(getClientPartitionPublishingState(partitionId))), retryOptions.getTryTimeout(), retryPolicy); } }
Source:
public void onEvent(ActivitiEvent event) { CommandContext currentCommandContext = Context.getCommandContext(); ProcessEngineEvent newEvent = converterContext.from(event); if (newEvent == null) { return; } @SuppressWarnings("unchecked") List<ProcessEngineEvent> events = (List<ProcessEngineEvent>) currentCommandContext .getAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS); if (events != null) { events.add(newEvent); } else { events = new ArrayList<ProcessEngineEvent>(); events.add(newEvent); currentCommandContext.addAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS, events); } List<CommandContextCloseListener> listeners = currentCommandContext.getCloseListeners(); if (listeners.size() != 0) { for (CommandContextCloseListener listener : listeners) { if (listener instanceof MessageProducerCommandContextCloseListener) { return; } } } MessageProducerCommandContextCloseListener messageListener = new MessageProducerCommandContextCloseListener( producer); currentCommandContext.addCloseListener(messageListener); }

Target:
public void onEvent(ActivitiEvent event) { CommandContext currentCommandContext = Context.getCommandContext(); ProcessEngineEvent newEvent = converterContext.from(event); if (newEvent == null) { return; } List<ProcessEngineEvent> events = currentCommandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS); if (events != null) { events.add(newEvent); } else { events = new ArrayList<>(); events.add(newEvent); currentCommandContext.addAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS, events); } if (!currentCommandContext.hasCloseListener(MessageProducerCommandContextCloseListener.class)) { currentCommandContext.addCloseListener(messageListener); } }
Source:
static void moveExeFileToSeLionHomeAndDeleteExtras() { File source = new File(SeLionConstants.SELION_HOME_DIR + File.separator + "Microsoft Web Driver" + File.separator + "MicrosoftWebDriver.exe"); File dest = new File(SeLionConstants.SELION_HOME_DIR); try { FileUtils.copyFileToDirectory(source, dest, true); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error while moving MicrosoftWebDriver.exe file from '" + source.getAbsolutePath() + "' to '" + dest.getAbsolutePath() + "'", e); } try { FileUtils.deleteDirectory(new File(SeLionConstants.SELION_HOME_DIR + File.separator + "Microsoft Web Driver")); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Exception while deleting 'Microsoft Web Driver' folder", e); } File extraMsiFileCreatedByMsiexec = new File(SeLionConstants.SELION_HOME_DIR + "MicrosoftWebDriver.msi"); if (extraMsiFileCreatedByMsiexec.exists()) { FileUtils.deleteQuietly(extraMsiFileCreatedByMsiexec); } }

Target:
static void moveExeFileToSeLionHomeAndDeleteExtras() { File source = new File(SeLionConstants.SELION_HOME_DIR + File.separator + "Microsoft Web Driver" + File.separator + SeLionConstants.EDGE_DRIVER); File dest = new File(SeLionConstants.SELION_HOME_DIR); try { FileUtils.copyFileToDirectory(source, dest, true); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error while moving MicrosoftWebDriver.exe file from '" + source.getAbsolutePath() + "' to '" + dest.getAbsolutePath() + "'", e); } try { FileUtils.deleteDirectory(new File(SeLionConstants.SELION_HOME_DIR + File.separator + "Microsoft Web Driver")); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Exception while deleting 'Microsoft Web Driver' folder", e); } File extraMsiFileCreatedByMsiexec = new File(SeLionConstants.SELION_HOME_DIR + "MicrosoftWebDriver.msi"); if (extraMsiFileCreatedByMsiexec.exists()) { FileUtils.deleteQuietly(extraMsiFileCreatedByMsiexec); } }
Source:
public void testGetKeyForStudent() throws Exception { restoreTypicalDataInDatastore(); ______TS("null parameters"); try { studentsLogic.getKeyForStudent("valid.course.id", null); Assert.fail(); } catch (AssertionError a) { assertEquals("Supplied parameter was null\n", a.getMessage()); } ______TS("non-existent student"); StudentAttributes student = dataBundle.students.get("student1InCourse1"); assertEquals(null, studentsLogic.getKeyForStudent(student.course, "non@existent")); }

Target:
public void testGetKeyForStudent() throws Exception { ______TS("null parameters"); try { studentsLogic.getKeyForStudent("valid.course.id", null); signalFailureToDetectException(); } catch (AssertionError a) { assertEquals(Const.StatusCodes.DBLEVEL_NULL_INPUT, a.getMessage()); } ______TS("non-existent student"); StudentAttributes student1InCourse1 = dataBundle.students.get("student1InCourse1"); String nonExistStudentEmail = "non@existent"; try { studentsLogic.getKeyForStudent(student1InCourse1.course, nonExistStudentEmail); signalFailureToDetectException(); } catch (EntityDoesNotExistException e) { String expectedErrorMsg = "Student does not exist: [" + student1InCourse1.course + "/" + nonExistStudentEmail + "]"; assertEquals(expectedErrorMsg, e.getMessage()); } ______TS("typical case"); String course1Id = dataBundle.courses.get("typicalCourse1").id; String actualKey = studentsLogic.getKeyForStudent(course1Id, student1InCourse1.email); String expectedKey = studentsLogic.getStudentForCourseIdAndGoogleId(course1Id, student1InCourse1.googleId).key; assertEquals(expectedKey, actualKey); }
Source:
private void onServiceStateChange(SyncthingService.State currentState) { mServiceState = currentState; switch (mServiceState) { case ERROR: case INIT: case STARTING: dismissDisabledDialog(); showLoadingDialog(); break; case ACTIVE: dismissDisabledDialog(); dismissLoadingDialog(); break; case DISABLED: if (!mIsPaused) { showDisabledDialog(); } break; default: break; } }

Target:
private void onServiceStateChange(SyncthingService.State currentState) { mServiceState = currentState; switch (mServiceState) { case INIT: case STARTING: dismissDisabledDialog(); showLoadingDialog(); break; case ACTIVE: dismissDisabledDialog(); dismissLoadingDialog(); break; case DISABLED: if (!mIsPaused) { showDisabledDialog(); } break; case ERROR: default: break; } }
Source:
public void testCreateWebhooksFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_webhooks_create_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); WebhookApi api = autoscaleApi.getWebhookApiForZoneAndGroupAndPolicy("DFW", "1234567890", "321456"); FluentIterable<WebhookResponse> webhooks = api.create(ImmutableList.of( Webhook.builder().name("PagerDuty").metadata(ImmutableMap.<String, Object>of("notes", "PagerDuty will fire this webhook")).build(), Webhook.builder().name("Nagios").metadata(ImmutableMap.<String, Object>of()).build() )); assertAuthentication(server); assertRequest(server.takeRequest(), "POST", "/v1.0/888888/groups/1234567890/policies/321456/webhooks", "/autoscale_webhooks_create_request.json"); assertTrue(webhooks.isEmpty()); } finally { server.shutdown(); } }

Target:
public void testCreateWebhooksFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_webhooks_create_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); WebhookApi api = autoscaleApi.getWebhookApiForZoneAndGroupAndPolicy("DFW", "1234567890", "321456"); FluentIterable<WebhookResponse> webhooks = api.create(ImmutableList.of( Webhook.builder().name("PagerDuty").metadata(ImmutableMap.<String, Object>of("notes", "PagerDuty will fire this webhook")).build(), Webhook.builder().name("Nagios").metadata(ImmutableMap.<String, Object>of()).build() )); assertAuthentication(server); assertRequest(server.takeRequest(), "POST", "/v1.0/888888/groups/1234567890/policies/321456/webhooks", "/autoscale_webhooks_create_request.json"); assertTrue(webhooks.isEmpty(), "Expected no webhooks, but was: " + webhooks); } finally { server.shutdown(); } }
Source:
public static Tech[] getAll() { return allTech.toArray(new Tech[] {}); }

Target:
public static Set<Tech> getAll() { return Collections.unmodifiableSet(allTech); }
Source:
public String generateCommonPart(String subscriptionId, String resourceGroup) { StringBuilder sb = new StringBuilder(); sb.append("/subscriptions/"); sb.append(subscriptionId); sb.append("/resourceGroups/"); sb.append(resourceGroup); return sb.toString(); }

Target:
private String generateCommonPart(String subscriptionId, String resourceGroup) { return String.format("/subscriptions/%s/resourceGroups/%s", subscriptionId, resourceGroup); }
Source:
public int hashCode() { return Objects.hash(endpoint, secureEndpoint, keyStorePath, keyStorePassword, virtualHost, servicePath, v4MaxNonChunkedRequestSize, ignoreUnknownHeaders, corsRules.hashCode()); }

Target:
public int hashCode() { return Objects.hash(endpoint, secureEndpoint, keyStorePath, keyStorePassword, virtualHost, servicePath, v4MaxNonChunkedRequestSize, ignoreUnknownHeaders, corsRules); }
Source:
public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; messageListener.interrupt(); try { if (connector != null) { connector.disconnect(); } } catch (OpenEnergyMonitorException e) { logger.error("Error occured when closing connection", e); } }

Target:
public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; messageListener.interrupt(); try { if (connector != null) { connector.disconnect(); } } catch (OpenEnergyMonitorException e) { logger.warn("Error occurred when closing connection. ", e); } }
Source:
public static boolean renameProject(File xmlFile, String dstName) throws IOException { if (!xmlFile.exists()) { throw new FileNotFoundException(xmlFile + " does not exist."); } String currentXml = Files.toString(xmlFile, Charsets.UTF_8); StringFinder stringFinder = new StringFinder(); if (!stringFinder.findBetween(currentXml, PROGRAM_NAME_START_TAG, PROGRAM_NAME_END_TAG)) { return false; } String srcName = stringFinder.getResult(); dstName = new XStream().toXML(dstName); dstName = dstName.replace("<string>", ""); dstName = dstName.replace("</string>", ""); if (srcName.equals(dstName)) { return true; } String srcProjectNameTag = PROGRAM_NAME_START_TAG + srcName + PROGRAM_NAME_END_TAG; String dstProjectNameTag = PROGRAM_NAME_START_TAG + dstName + PROGRAM_NAME_END_TAG; String newXml = currentXml.replace(srcProjectNameTag, dstProjectNameTag); if (currentXml.equals(newXml)) { Log.e(TAG, "Cannot find projectNameTag in code.xml"); return false; } StorageOperations.writeToFile(xmlFile, newXml); return true; }

Target:
public static boolean renameProject(File xmlFile, String dstName) throws IOException { if (!xmlFile.exists()) { throw new FileNotFoundException(xmlFile + " does not exist."); } String currentXml = Files.toString(xmlFile, Charsets.UTF_8); StringFinder stringFinder = new StringFinder(); if (!stringFinder.findBetween(currentXml, PROGRAM_NAME_START_TAG, PROGRAM_NAME_END_TAG)) { return false; } String srcName = stringFinder.getResult(); dstName = getXMLEncodedString(dstName); if (srcName.equals(dstName)) { return true; } String srcProjectNameTag = PROGRAM_NAME_START_TAG + srcName + PROGRAM_NAME_END_TAG; String dstProjectNameTag = PROGRAM_NAME_START_TAG + dstName + PROGRAM_NAME_END_TAG; String newXml = currentXml.replace(srcProjectNameTag, dstProjectNameTag); if (currentXml.equals(newXml)) { Log.e(TAG, "Cannot find projectNameTag in code.xml"); return false; } StorageOperations.writeToFile(xmlFile, newXml); return true; }
Source:
public void addProcess(String processName, String authKey, String[] cmd, String workingDir, Map<String, String> env) throws IOException { if (processName == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("processName"); } if (authKey == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("authKey"); } if (cmd == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("cmd"); } if (workingDir == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("workingDir"); } if (env == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("env"); } if (cmd.length < 1) { throw ProcessLogger.ROOT_LOGGER.invalidCommandLen(); } if (authKey.length() != ProcessController.AUTH_BYTES_ENCODED_LENGTH) { throw ProcessLogger.ROOT_LOGGER.invalidAuthKeyLen(); } final OutputStream os = connection.writeMessage(); try { os.write(Protocol.ADD_PROCESS); writeUTFZBytes(os, processName); os.write(authKey.getBytes()); writeInt(os, cmd.length); for (String c : cmd) { writeUTFZBytes(os, c); } writeInt(os, env.size()); for (String key : env.keySet()) { final String value = env.get(key); writeUTFZBytes(os, key); if (value != null) { writeUTFZBytes(os, value); } else { writeUTFZBytes(os, ""); } } writeUTFZBytes(os, workingDir); os.close(); } finally { safeClose(os); } }

Target:
public void addProcess(String processName, String authKey, String[] cmd, String workingDir, Map<String, String> env) throws IOException { if (processName == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("processName"); } if (authKey == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("authKey"); } if (cmd == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("cmd"); } if (workingDir == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("workingDir"); } if (env == null) { throw ProcessLogger.ROOT_LOGGER.nullVar("env"); } if (cmd.length < 1) { throw ProcessLogger.ROOT_LOGGER.invalidCommandLen(); } if (authKey.length() != ProcessController.AUTH_BYTES_ENCODED_LENGTH) { throw ProcessLogger.ROOT_LOGGER.invalidAuthKeyLen(); } final OutputStream os = connection.writeMessage(); try { os.write(Protocol.ADD_PROCESS); writeUTFZBytes(os, processName); os.write(authKey.getBytes(Charset.forName("US-ASCII"))); writeInt(os, cmd.length); for (String c : cmd) { writeUTFZBytes(os, c); } writeInt(os, env.size()); for (String key : env.keySet()) { final String value = env.get(key); writeUTFZBytes(os, key); if (value != null) { writeUTFZBytes(os, value); } else { writeUTFZBytes(os, ""); } } writeUTFZBytes(os, workingDir); os.close(); } finally { safeClose(os); } }
Source:
public String getServerVersion() { if (getStorageState() != State.UPDATED) { return NEED_UPDATE; } String version = updateStatus.getServerVersion(); return version == null ? "Unknown" : version; }

Target:
public String getServerVersion() { if (getStorageState() != State.UPDATED) { return NEED_UPDATE; } return updateStatus.getServerVersion(); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new ForceClose(this)); setupTheme(); setupLanguage(); mFragmentManager = getSupportFragmentManager(); mAuthorizationManager = new AuthorizationManager(); locationList = new ArrayList<>(); Bundle extras = getIntent().getExtras(); if (extras != null) { Boolean flag = extras.getBoolean(getString(R.string.boolean_flag)); String errorReport = extras.getString(getString(R.string.error_report)); if (flag) { showAppCrashDialog(errorReport); } } mIntentFilter = new IntentFilter(); mIntentFilter.addAction(ApplicationConstants.BroadcastActions.AUTHENTICATION_CHECK_BROADCAST_ACTION); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new ForceClose(this)); setupTheme(); setupLanguage(); mFragmentManager = getSupportFragmentManager(); mAuthorizationManager = new AuthorizationManager(); locationList = new ArrayList<>(); Bundle extras = getIntent().getExtras(); if (extras != null) { Boolean flag = extras.getBoolean(ApplicationConstants.FLAG); String errorReport = extras.getString(ApplicationConstants.ERROR); if (flag) { showAppCrashDialog(errorReport); } } mIntentFilter = new IntentFilter(); mIntentFilter.addAction(ApplicationConstants.BroadcastActions.AUTHENTICATION_CHECK_BROADCAST_ACTION); }
Source:
public void testExceptionNestedOnStartConfigError() throws Exception { Throwable cause = new RuntimeException("Exception cause"); Throwable exception = new MembershipConfigurationException("Test exception", cause); doThrow(exception).when(membership).start(); try { distribution.start(); fail("expected start to throw an exception"); } catch (GemFireConfigException e) { assertEquals(e.getCause(), cause); } }

Target:
public void testExceptionNestedOnStartConfigError() throws Exception { Throwable exception = new MembershipConfigurationException("Test exception"); doThrow(exception).when(membership).start(); assertThatThrownBy(() -> distribution.start()) .isInstanceOf(GemFireConfigException.class) .hasCause(exception); }
Source:
private void runConcurrencyTest(List<DiskSpaceRequirements> requirementsList, final boolean allocate, final boolean free) throws Exception { List<Callable<Void>> tasks = new ArrayList<>(); final String filenamePrefix = "conc-test-"; int fileCount = 0; for (final DiskSpaceRequirements requirements : requirementsList) { for (int i = 0; i < requirements.getSegmentsNeeded(); i++, fileCount++) { final String filename = filenamePrefix + fileCount; tasks.add(() -> { if (allocate) { allocateAndVerify(filename, requirements.getSegmentSizeInBytes()); } if (free) { freeAndVerify(new File(allocatedFileDir, filename), requirements.getSegmentSizeInBytes()); } return null; }); fileCount++; } } for (Future<Void> future : exec.invokeAll(tasks)) { future.get(10, TimeUnit.SECONDS); } }

Target:
private void runConcurrencyTest(List<DiskSpaceRequirements> requirementsList, final boolean allocate, final boolean free) throws Exception { List<Callable<Void>> tasks = new ArrayList<>(); final String filenamePrefix = "conc-test-"; int fileCount = 0; for (final DiskSpaceRequirements requirements : requirementsList) { for (int i = 0; i < requirements.getSegmentsNeeded(); i++, fileCount++) { final String filename = filenamePrefix + fileCount; tasks.add(() -> { if (allocate) { allocateAndVerify(filename, requirements.getSegmentSizeInBytes()); } if (free) { freeAndVerify(new File(allocatedFileDir, filename), requirements.getSegmentSizeInBytes()); } return null; }); } } for (Future<Void> future : exec.invokeAll(tasks)) { future.get(10, TimeUnit.SECONDS); } }
Source:
private void checkName(String name) { if (names.contains(name)) { throw new IllegalArgumentException("Duplicate name : " + name); } names.add(name); }

Target:
private void checkName(String name) { if (!names.add(name)) { throw new IllegalArgumentException("Duplicate name : " + name); } }
Source:
public void updatePhysics(GlowBlock me) { Block below = me.getRelative(BlockFace.DOWN); switch (below.getType()) { case AIR: FIRE: WATER: LAVA: transformToFallingEntity(me); } }

Target:
public void updatePhysics(GlowBlock me) { Block below = me.getRelative(BlockFace.DOWN); switch (below.getType()) { case AIR: case FIRE: case WATER: case LAVA: transformToFallingEntity(me); } }
Source:
private static Mono<Void> writeBodyToFile(BlobDownloadAsyncResponse response, AsynchronousFileChannel file, long chunkNum, ParallelTransferOptions finalParallelTransferOptions, Lock progressLock, AtomicLong totalProgress) { Flux<ByteBuffer> data = StorageImplUtils.deepCloneStreamBuffers(response.getValue()); data = ProgressReporter.addParallelProgressReporting(data, finalParallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); return FluxUtil.writeFile(data, file, chunkNum * finalParallelTransferOptions.getBlockSize()); }

Target:
private static Mono<Void> writeBodyToFile(BlobDownloadAsyncResponse response, AsynchronousFileChannel file, long chunkNum, ParallelTransferOptions finalParallelTransferOptions, Lock progressLock, AtomicLong totalProgress) { Flux<ByteBuffer> data = response.getValue(); data = ProgressReporter.addParallelProgressReporting(data, finalParallelTransferOptions.getProgressReceiver(), progressLock, totalProgress); return FluxUtil.writeFile(data, file, chunkNum * finalParallelTransferOptions.getBlockSize()); }
Source:
public void updateUseHostCpuAvailability() { boolean clusterSupportsHostCpu = getCompatibilityVersion() != null; boolean vmIsHp = getModel().getVmType().getSelectedItem() == VmType.HighPerformance; boolean vmIsNonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem(); if (clusterSupportsHostCpu && !clusterHasPpcArchitecture() && (vmIsNonMigratable || vmIsHp)) { getModel().getHostCpu().setIsChangeable(true); } else { getModel().getHostCpu().setEntity(false); getModel().getHostCpu().setIsChangeable(false); getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable()); } }

Target:
public void updateUseHostCpuAvailability() { boolean clusterSupportsHostCpu = getCompatibilityVersion() != null; boolean vmIsNonMigratable = MigrationSupport.PINNED_TO_HOST == getModel().getMigrationMode().getSelectedItem(); if (clusterSupportsHostCpu && !clusterHasPpcArchitecture() && vmIsNonMigratable) { getModel().getHostCpu().setIsChangeable(true); } else { getModel().getHostCpu().setEntity(false); getModel().getHostCpu().setIsChangeable(false); getModel().getHostCpu().setChangeProhibitionReason(constants.hosCPUUnavailable()); } }
Source:
public void deserialize() throws Exception { final InputStream stream = getClass().getResourceAsStream("/dataset/datasetLinks.json"); final DatasetLinks datasetLinkss = new ObjectMapper().readValue(stream, DatasetLinks.class); assertThat(datasetLinkss, is(notNullValue())); assertThat(datasetLinkss.getCategory(), is("singleloadinterface")); assertThat(datasetLinkss.getInstance(), is("MD::LDM::SingleLoadInterface")); assertThat(datasetLinkss.getSummary(), is("single loading interfaces")); final Collection<AboutLinks.Link> links = datasetLinkss.getLinks(); assertThat(links, is(notNullValue())); assertThat(links, hasSize(1)); final AboutLinks.Link link = links.iterator().next(); assertThat(link, is(notNullValue())); assertThat(link.getIdentifier(), is("dataset.person")); assertThat(link.getUri(), is("/gdc/md/PROJECT_ID/ldm/singleloadinterface/dataset.person")); assertThat(link.getCategory(), is("dataset-singleloadinterface")); assertThat(link.getTitle(), is("Person")); assertThat(link.getSummary(), is("dataset single data loading interface specifications")); }

Target:
public void deserialize() throws Exception { final InputStream stream = getClass().getResourceAsStream("/dataset/datasetLinks.json"); final DatasetLinks datasetLinks = new ObjectMapper().readValue(stream, DatasetLinks.class); assertThat(datasetLinks, is(notNullValue())); assertThat(datasetLinks.getCategory(), is("singleloadinterface")); assertThat(datasetLinks.getInstance(), is("MD::LDM::SingleLoadInterface")); assertThat(datasetLinks.getSummary(), is("single loading interfaces")); final Collection<AboutLinks.Link> links = datasetLinks.getLinks(); assertThat(links, is(notNullValue())); assertThat(links, hasSize(1)); final AboutLinks.Link link = links.iterator().next(); assertThat(link, is(notNullValue())); assertThat(link.getIdentifier(), is("dataset.person")); assertThat(link.getUri(), is("/gdc/md/PROJECT_ID/ldm/singleloadinterface/dataset.person")); assertThat(link.getCategory(), is("dataset-singleloadinterface")); assertThat(link.getTitle(), is("Person")); assertThat(link.getSummary(), is("dataset single data loading interface specifications")); }
Source:
private void sendNotification() { try { Role cmsAdminRole = APILocator.getRoleAPI().loadCMSAdminRole(); APILocator.getNotificationAPI().generateNotification( new I18NMessage("NO DEFUALT HOST"), new I18NMessage("THERE IS NO DEFAULT HOST " ), null, NotificationLevel.INFO, NotificationType.GENERIC, Visibility.ROLE, cmsAdminRole.getId(), APILocator.systemUser().getUserId(), APILocator.systemUser().getLocale()); throw new DotStateException("NO DEFUALT HOST, creating a fake one"); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } }

Target:
private void sendNotification() { try { Role cmsAdminRole = APILocator.getRoleAPI().loadCMSAdminRole(); APILocator.getNotificationAPI().generateNotification( new I18NMessage("NO DEFAULT HOST"), new I18NMessage("THERE IS NO DEFAULT HOST " ), null, NotificationLevel.INFO, NotificationType.GENERIC, Visibility.ROLE, cmsAdminRole.getId(), APILocator.systemUser().getUserId(), APILocator.systemUser().getLocale()); throw new DotStateException("NO DEFAULT HOST, creating a fake one"); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } }
Source:
private void updateActionAvailability() { VDS vds = getEntity(); getSyncStorageDevicesCommand().setIsExecutionAllowed(VDSStatus.Up.equals(vds.getStatus())); }

Target:
private void updateActionAvailability() { VDS vds = getEntity(); getSyncStorageDevicesCommand().setIsExecutionAllowed(vds.getStatus() == VDSStatus.Up); }
Source:
private void setEntityArmorWithChance(Random random, EntityLivingBase entity, ToolsItem sword, ToolsItem helmet, ToolsItem chestplate, ToolsItem leggings, ToolsItem boots) { setStackIfCaseAndEmpty(entity, EntityEquipmentSlot.MAINHAND, sword.getItemStack(), entity instanceof EntityZombie && random.nextInt(100) < 50); setStackIfCaseAndEmpty(entity, EntityEquipmentSlot.HEAD, helmet.getItemStack(), random.nextInt(100) < 50); setStackIfCaseAndEmpty(entity, EntityEquipmentSlot.CHEST, chestplate.getItemStack(), random.nextInt(100) < 50); setStackIfCaseAndEmpty(entity, EntityEquipmentSlot.LEGS, leggings.getItemStack(), random.nextInt(100) < 50); setStackIfCaseAndEmpty(entity, EntityEquipmentSlot.FEET, boots.getItemStack(), random.nextInt(100) < 50); }

Target:
private void setEntityArmorWithChance(Random random, EntityLivingBase entity, ToolsItem sword, ToolsItem helmet, ToolsItem chestplate, ToolsItem leggings, ToolsItem boots) { if (entity instanceof EntityZombie && random.nextInt(100) < 50) { setStackIfEmpty(entity, EntityEquipmentSlot.MAINHAND, sword.getItemStack()); } if (random.nextInt(100) < 50) { setStackIfEmpty(entity, EntityEquipmentSlot.HEAD, helmet.getItemStack()); } if (random.nextInt(100) < 50) { setStackIfEmpty(entity, EntityEquipmentSlot.CHEST, chestplate.getItemStack()); } if (random.nextInt(100) < 50) { setStackIfEmpty(entity, EntityEquipmentSlot.LEGS, leggings.getItemStack()); } if (random.nextInt(100) < 50) { setStackIfEmpty(entity, EntityEquipmentSlot.FEET, boots.getItemStack()); } }
Source:
public boolean createOvfStoreDisks(int missingDiskCount) { boolean AllOvfStoreDisksCreated = true; for (int i = 0; i < missingDiskCount; i++) { CreateOvfVolumeForStorageDomainCommandParameters parameters = createCreateOvfVolumeForStorageDomainParams(); ActionReturnValue returnValue = runInternalAction(ActionType.CreateOvfVolumeForStorageDomain, parameters, getContext().clone().withoutLock()); if (!returnValue.getSucceeded()) { AllOvfStoreDisksCreated = false; } } return AllOvfStoreDisksCreated; }

Target:
public boolean createOvfStoreDisks(int missingDiskCount) { boolean allOvfStoreDisksCreated = true; for (int i = 0; i < missingDiskCount; i++) { CreateOvfVolumeForStorageDomainCommandParameters parameters = createCreateOvfVolumeForStorageDomainParams(); ActionReturnValue returnValue = runInternalAction(ActionType.CreateOvfVolumeForStorageDomain, parameters, getContext().clone().withoutLock()); if (!returnValue.getSucceeded()) { allOvfStoreDisksCreated = false; } } return allOvfStoreDisksCreated; }
Source:
private GatewayOrder buildAuthoriseOrder(CardAuthorisationGatewayRequest request, String frontendUrl) { EpdqTemplateData templateData = new EpdqTemplateData(); templateData.setOrderId(request.getChargeExternalId()); templateData.setPassword(request.getGatewayAccount().getCredentials().get(CREDENTIALS_PASSWORD)); templateData.setShaInPassphrase(request.getGatewayAccount().getCredentials().get(CREDENTIALS_SHA_IN_PASSPHRASE)); templateData.setUserId(request.getGatewayAccount().getCredentials().get(CREDENTIALS_USERNAME)); templateData.setMerchantCode(request.getGatewayAccount().getCredentials().get(CREDENTIALS_MERCHANT_ID)); templateData.setDescription(request.getDescription()); templateData.setAmount(request.getAmount()); templateData.setAuthCardDetails(request.getAuthCardDetails()); EpdqPayloadDefinition epdqPayloadDefinition; if (request.getGatewayAccount().isRequires3ds()) { if (request.getGatewayAccount().getIntegrationVersion3ds() == 2) { epdqPayloadDefinition = new EpdqPayloadDefinitionForNew3ds2Order(frontendUrl, request.getCharge().getLanguage(), Clock.systemUTC()); } else { epdqPayloadDefinition = new EpdqPayloadDefinitionForNew3dsOrder(frontendUrl); } } else { epdqPayloadDefinition = epdqPayloadDefinitionForNewOrder; } return epdqPayloadDefinition.createGatewayOrder(templateData); }

Target:
private GatewayOrder buildAuthoriseOrder(CardAuthorisationGatewayRequest request, String frontendUrl) { EpdqTemplateData templateData = new EpdqTemplateData(); templateData.setOrderId(request.getChargeExternalId()); templateData.setPassword(request.getGatewayAccount().getCredentials().get(CREDENTIALS_PASSWORD)); templateData.setShaInPassphrase(request.getGatewayAccount().getCredentials().get(CREDENTIALS_SHA_IN_PASSPHRASE)); templateData.setUserId(request.getGatewayAccount().getCredentials().get(CREDENTIALS_USERNAME)); templateData.setMerchantCode(request.getGatewayAccount().getCredentials().get(CREDENTIALS_MERCHANT_ID)); templateData.setDescription(request.getDescription()); templateData.setAmount(request.getAmount()); templateData.setAuthCardDetails(request.getAuthCardDetails()); EpdqPayloadDefinition epdqPayloadDefinition; if (request.getGatewayAccount().isRequires3ds()) { if (request.getGatewayAccount().getIntegrationVersion3ds() == 2) { epdqPayloadDefinition = new EpdqPayloadDefinitionForNew3ds2Order(frontendUrl, request.getCharge().getLanguage(), clock); } else { epdqPayloadDefinition = new EpdqPayloadDefinitionForNew3dsOrder(frontendUrl); } } else { epdqPayloadDefinition = epdqPayloadDefinitionForNewOrder; } return epdqPayloadDefinition.createGatewayOrder(templateData); }
Source:
private List<Folder> findContainersAssetsByHost(final Host host, final User user) { List<Contentlet> containers = null; final List<Folder> folders = new ArrayList<>(); try{ final String query = builder("+structureType:", Structure.STRUCTURE_TYPE_FILEASSET, " +path:", Constants.CONTAINER_FOLDER_PATH, " container.vtl", " +conhost:", host.getIdentifier()).toString(); containers = this.permissionAPI.filterCollection( this.contentletAPI.search(query,-1, 0, null , user, false), PermissionAPI.PERMISSION_READ, false, user); for(final Contentlet container : containers) { folders.add(this.folderAPI.find(container.getFolder(), user, false)); } } catch (Exception e) { Logger.error(this.getClass(), e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } return folders; }

Target:
private List<Folder> findContainersAssetsByHost(final Host host, final User user) { List<Contentlet> containers = null; final List<Folder> folders = new ArrayList<>(); try{ final String query = builder("+structureType:", Structure.STRUCTURE_TYPE_FILEASSET, " +path:", Constants.CONTAINER_FOLDER_PATH, " container.vtl", " +conhost:", host.getIdentifier(), " +working:true +deleted:false").toString(); containers = this.permissionAPI.filterCollection( this.contentletAPI.search(query,-1, 0, null , user, false), PermissionAPI.PERMISSION_READ, false, user); for(final Contentlet container : containers) { folders.add(this.folderAPI.find(container.getFolder(), user, false)); } } catch (Exception e) { Logger.error(this.getClass(), e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } return folders; }
Source:
private void persistEngineSession(String sessionId) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo != null) { EngineSession engineSession = new EngineSession(getUser(sessionId, false)); engineSession.setEngineSessionId(sessionId); sessionInfo.contentOfSession.put(ENGINE_SESSION_SEQ_ID, getDbFacade().getEngineSessionDao().save(engineSession)); } }

Target:
private void persistEngineSession(String sessionId) { SessionInfo sessionInfo = getSessionInfo(sessionId); if (sessionInfo != null) { sessionInfo.contentOfSession.put(ENGINE_SESSION_SEQ_ID, getDbFacade().getEngineSessionDao().save(new EngineSession(getUser(sessionId, false), sessionId))); } }
Source:
public void assertShadowVariablesAreNotStale(Score expectedWorkingScore, Object completedAction) { Map<ShadowVariableDescriptor, List<String>> shadowVariableDescriptorListMap = calculateShadowVariableViolationListMap(); if (!shadowVariableDescriptorListMap.isEmpty()) { StringBuilder message = new StringBuilder(); message.append(VariableListener.class.getSimpleName()).append(" corruption after completedAction (") .append(completedAction).append("):\n"); shadowVariableDescriptorListMap.forEach((shadowVariableDescriptor, violationList) -> { message.append(violationList.get(0)); if (violationList.size() > 1) { message.append(" ...\n"); } }); throw new IllegalStateException(message.toString()); } Score workingScore = calculateScore(); if (!expectedWorkingScore.equals(workingScore)) { assertWorkingScoreFromScratch(workingScore, "assertShadowVariablesAreNotStale(" + expectedWorkingScore + ", " + completedAction + ")"); throw new IllegalStateException("Impossible " + VariableListener.class.getSimpleName() + " corruption (" + expectedWorkingScore.subtract(workingScore).toShortString() + "):" + " the expectedWorkingScore (" + expectedWorkingScore + ") is not the workingScore (" + workingScore + ") after all " + VariableListener.class.getSimpleName() + "s were triggered without changes to the genuine variables" + " after completedAction (" + completedAction + ").\n" + "But all the shadow variable values are still the same, so this is impossible.\n" + "Maybe run with " + EnvironmentMode.FULL_ASSERT + " if you aren't already, to fail earlier."); } }

Target:
public void assertShadowVariablesAreNotStale(Score expectedWorkingScore, Object completedAction) { String violationMessage = createShadowVariablesViolationMessage(); if (violationMessage != null) { throw new IllegalStateException( VariableListener.class.getSimpleName() + " corruption after completedAction (" + completedAction + "):\n" + violationMessage); } Score workingScore = calculateScore(); if (!expectedWorkingScore.equals(workingScore)) { assertWorkingScoreFromScratch(workingScore, "assertShadowVariablesAreNotStale(" + expectedWorkingScore + ", " + completedAction + ")"); throw new IllegalStateException("Impossible " + VariableListener.class.getSimpleName() + " corruption (" + expectedWorkingScore.subtract(workingScore).toShortString() + "):" + " the expectedWorkingScore (" + expectedWorkingScore + ") is not the workingScore (" + workingScore + ") after all " + VariableListener.class.getSimpleName() + "s were triggered without changes to the genuine variables" + " after completedAction (" + completedAction + ").\n" + "But all the shadow variable values are still the same, so this is impossible.\n" + "Maybe run with " + EnvironmentMode.FULL_ASSERT + " if you aren't already, to fail earlier."); } }
Source:
protected <T> T parseResponseStreamAndClose(InputStream inputStream, Class<T> clazz) throws IOException { try (InputStreamReader reader = new InputStreamReader(inputStream)) { T objectFromJson = GSON.fromJson(reader, clazz); if (objectFromJson == null) { LOG.error( "Response doesn't contain any data, though it was expected to contain some."); throw new IOException( "Internal server error. Unexpected response body received."); } return objectFromJson; } catch (JsonParseException e) { throw new IOException(e.getLocalizedMessage(), e); } }

Target:
protected <T> T parseResponseStreamAndClose(InputStream inputStream, Class<T> clazz) throws IOException { try (InputStreamReader reader = new InputStreamReader(inputStream)) { T objectFromJson = GSON.fromJson(reader, clazz); if (objectFromJson == null) { throw new IOException( "Internal server error. Unexpected response body received from Feature API."); } return objectFromJson; } catch (JsonParseException e) { throw new IOException(e.getLocalizedMessage(), e); } }
Source:
public static Set<Flag> addFlag(Set<Flag> flags, Flag newFlag) { if (flags == null) { return EnumSet.of(newFlag); } if (flags.contains(newFlag)) { return flags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.add(newFlag); return copy; }

Target:
public static Set<Flag> addFlag(Set<Flag> flags, Flag newFlag) { if (flags == null || flags.isEmpty()) { return EnumSet.of(newFlag); } if (flags.contains(newFlag)) { return flags; } EnumSet<Flag> copy = EnumSet.copyOf(flags); copy.add(newFlag); return copy; }