auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AckMsg(String rawMsg) { super(rawMsg); if (this.payload.length == ACK_MSG_PAYLOAD_LEN) { isNack = (this.payload[0] == 0x81); } else logger.error("Got "+this.msgType+" message with incorrect length!"); }

Target:
public AckMsg(String rawMsg) { super(rawMsg); if (this.payload.length == ACK_MSG_PAYLOAD_LEN) { isNack = (this.payload[0] == 0x81); } else { logger.error("Got " + this.msgType + " message with incorrect length!"); } }
Source:
public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); if (records == null || records.size() != 1) { return; } mCidView.setText(String.valueOf(records.get(0).cityID)); }

Target:
public void search(View view) { ArrayList<MKOLSearchRecord> records = mOffline.searchCity(mCityNameView .getText().toString()); if (records == null) { return; } mCidView.setText(String.valueOf(records.get(0).cityID)); }
Source:
public Object get(boolean preferJson, String application, String entityToken, String configKeyName) { EntityLocal entity = brooklyn().getEntity(application, entityToken); ConfigKey<?> ck = entity.getEntityType().getConfigKey(configKeyName); if (ck==null) ck = new BasicConfigKey<Object>(Object.class, configKeyName); return getValueForDisplay(entity.getConfig(ck), preferJson, true); }

Target:
public Object get(boolean preferJson, String application, String entityToken, String configKeyName) { EntityLocal entity = brooklyn().getEntity(application, entityToken); ConfigKey<?> ck = entity.getEntityType().getConfigKey(configKeyName); if (ck==null) ck = new BasicConfigKey<Object>(Object.class, configKeyName); return getValueForDisplay(((EntityInternal)entity).getConfigMap().getRawConfig(ck), preferJson, true); }
Source:
public BufferConsumer createBufferConsumer() { if (buffer == null) { buffer = new NetworkBuffer(memorySegment, recycler); } else { buffer.retainBuffer(); } return new BufferConsumer( buffer, positionMarker, positionMarker.cachedPosition); }

Target:
public BufferConsumer createBufferConsumer() { checkState(!bufferConsumerCreated, "Two BufferConsumer shouldn't exist for one BufferBuilder"); bufferConsumerCreated = true; return new BufferConsumer( memorySegment, recycler, positionMarker, positionMarker.cachedPosition); }
Source:
void startLocationPolling(PollSensorAction action) { synchronized (actions) { actions.add(action); } resetTimeoutTimer(); new Handler(Looper.getMainLooper()).post(() -> { Context context = CommCareApplication.instance(); mLocationController = CommCareLocationControllerFactory.getLocationController(context, this); mLocationController.start(); }); }

Target:
void startLocationPolling(PollSensorAction action) { synchronized (actions) { actions.add(action); } resetTimeoutTimer(); new Handler(Looper.getMainLooper()).post(() -> { Context context = CommCareApplication.instance(); mLocationController = CommCareLocationControllerFactory.getLocationController(context, this); requestLocationUpdates(); }); }
Source:
S3ABlockOutputStream(S3AFileSystem fs, String key, ExecutorService executorService, Progressable progress, long blockSize, S3ADataBlocks.BlockFactory blockFactory, S3AInstrumentation.OutputStreamStatistics statistics, S3AFileSystem.WriteOperationHelper writeOperationHelper) throws IOException { this.fs = fs; this.key = key; this.blockFactory = blockFactory; this.blockSize = (int) blockSize; this.statistics = statistics; this.writeOperationHelper = writeOperationHelper; Preconditions.checkArgument(blockSize >= Constants.MULTIPART_MIN_SIZE, "Block size is too small: %d", blockSize); this.executorService = MoreExecutors.listeningDecorator(executorService); this.multiPartUpload = null; this.progressListener = (progress instanceof ProgressListener) ? (ProgressListener) progress : new ProgressableListener(progress); LOG.debug("Initialized S3ABlockOutputStream for {}" + " output to {}", writeOperationHelper, activeBlock); maybeCreateBlock(); }

Target:
S3ABlockOutputStream(S3AFileSystem fs, String key, ExecutorService executorService, Progressable progress, long blockSize, S3ADataBlocks.BlockFactory blockFactory, S3AInstrumentation.OutputStreamStatistics statistics, S3AFileSystem.WriteOperationHelper writeOperationHelper) throws IOException { this.fs = fs; this.key = key; this.blockFactory = blockFactory; this.blockSize = (int) blockSize; this.statistics = statistics; this.writeOperationHelper = writeOperationHelper; Preconditions.checkArgument(blockSize >= Constants.MULTIPART_MIN_SIZE, "Block size is too small: %d", blockSize); this.executorService = MoreExecutors.listeningDecorator(executorService); this.multiPartUpload = null; this.progressListener = (progress instanceof ProgressListener) ? (ProgressListener) progress : new ProgressableListener(progress); createBlockIfNeeded(); LOG.debug("Initialized S3ABlockOutputStream for {}" + " output to {}", writeOperationHelper, activeBlock); }
Source:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } try { if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } } catch (RuntimeException e1) { throw new RuntimeException(e1); } }

Target:
public void close() { try { for (RFileSource source : opts.in.getSources()) { source.getInputStream().close(); } } catch (IOException e) { throw new RuntimeException(e); } if (this.blockCacheManager != null) { this.blockCacheManager.stop(); } }
Source:
public static boolean areAllUnitsSameType(Vector<Unit> units, int unitType) { double firstUnitWeight = units.get(0).getEntity() != null ? units.get(0).getEntity().getWeight() : 0; boolean light = firstUnitWeight > 0 && firstUnitWeight <= 50; boolean heavy = firstUnitWeight > 50 && firstUnitWeight <= 100; boolean superheavy = firstUnitWeight > 100 && firstUnitWeight <= 200; for (Unit unit : units) { if (unit.getEntity() == null) { continue; } if (unitType == UnitType.TANK || unitType == UnitType.VTOL || unitType == UnitType.NAVAL) { if (light && unit.getEntity().getWeight() > 50) { return false; } if (heavy && (unit.getEntity().getWeight() <= 50 || unit.getEntity().getWeight() > 100)) { return false; } if (superheavy && (unit.getEntity().getWeight() <= 100 || unit.getEntity().getWeight() > 200)) { return false; } } if (unit.getEntity().getUnitType() != unitType) { return false; } } return true; }

Target:
public static boolean areAllUnitsSameType(Vector<Unit> units, int unitType) { if (units.isEmpty()) { return false; } double firstUnitWeight = units.get(0).getEntity() != null ? units.get(0).getEntity().getWeight() : 0; boolean light = firstUnitWeight > 0 && firstUnitWeight <= 50; boolean heavy = firstUnitWeight > 50 && firstUnitWeight <= 100; boolean superheavy = firstUnitWeight > 100 && firstUnitWeight <= 200; for (Unit unit : units) { if (unit.getEntity() == null) { continue; } if (unitType == UnitType.TANK || unitType == UnitType.VTOL || unitType == UnitType.NAVAL) { if (light && unit.getEntity().getWeight() > 50) { return false; } if (heavy && (unit.getEntity().getWeight() <= 50 || unit.getEntity().getWeight() > 100)) { return false; } if (superheavy && (unit.getEntity().getWeight() <= 100 || unit.getEntity().getWeight() > 200)) { return false; } } if (unit.getEntity().getUnitType() != unitType) { return false; } } return true; }
Source:
protected void onExportToCsv() { GWT.log(this.toString() + "onExportToCsv"); scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); }

Target:
protected void onExportToCsv() { scenarioSimulationEditorWrapper.onExportToCsv(getExportCallBack(), new ScenarioSimulationHasBusyIndicatorDefaultErrorCallback(view), context.getStatus().getSimulation()); }
Source:
public void deleteFeedbackResponseComment(String commentIdSuffix) { WebElement commentRow = browser.driver.findElement(By.id("responseCommentRow" + commentIdSuffix)); final WebElement deleteCommentButton = commentRow.findElement(By.tagName("div")).findElement(By.id("commentdelete" + commentIdSuffix)); click(deleteCommentButton); waitForConfirmationModalAndClickOk(); }

Target:
public void deleteFeedbackResponseComment(String commentIdSuffix) { WebElement deleteCommentButton = browser.driver.findElement(By.id("commentdelete" + commentIdSuffix)); click(deleteCommentButton); waitForConfirmationModalAndClickOk(); }
Source:
public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); this.context = context.fork(); }

Target:
public ConstrainedTerm(Term term, ConjunctiveFormula constraint, TermContext context) { this.data = new Data(term, constraint); this.context = context; }
Source:
public final void onChange(ImporterChannelAssignment assignment) { if (m_stopping) return; ImmutableMap<URI, AbstractImporter> oldReference = m_importers.get(); ImmutableMap.Builder<URI, AbstractImporter> builder = new ImmutableMap.Builder<>(); builder.putAll(Maps.filterKeys(oldReference, notUriIn(assignment.getRemoved()))); List<AbstractImporter> toStop = new ArrayList<>(); for (URI removed: assignment.getRemoved()) { try { AbstractImporter importer = oldReference.get(removed); if (importer!=null) { toStop.add(importer); } } catch(Exception e) { s_logger.warn( String.format("Error calling stop on %s in importer %s", removed.toString(), m_factory.getTypeName()), e); } } List<AbstractImporter> newImporters = new ArrayList<>(); for (final URI added: assignment.getAdded()) { try { AbstractImporter importer = m_factory.createImporter(m_configs.get(added)); newImporters.add(importer); builder.put(added, importer); } catch(Exception e) { s_logger.warn("Error adding assignment " + added.toString() + " importer not found."); if (s_logger.isDebugEnabled()) { e.printStackTrace(); } } } ImmutableMap<URI, AbstractImporter> newReference = builder.build(); boolean success = m_importers.compareAndSet(oldReference, newReference); if (!m_stopping && success) { stopImporters(toStop); startImporters(newImporters); } }

Target:
public final void onChange(ImporterChannelAssignment assignment) { if (m_stopping) return; ImmutableMap<URI, AbstractImporter> oldReference = m_importers.get(); ImmutableMap.Builder<URI, AbstractImporter> builder = new ImmutableMap.Builder<>(); builder.putAll(Maps.filterKeys(oldReference, notUriIn(assignment.getRemoved()))); List<AbstractImporter> toStop = new ArrayList<>(); List<String> missingRemovedURLs = new ArrayList<>(); List<String> missingAddedURLs = new ArrayList<>(); for (URI removed: assignment.getRemoved()) { if (m_configs.containsKey(removed)) { try { AbstractImporter importer = oldReference.get(removed); if (importer!=null) { toStop.add(importer); } } catch(Exception e) { s_logger.warn( String.format("Error calling stop on %s in importer %s", removed.toString(), m_factory.getTypeName()), e); } } else { missingRemovedURLs.add(removed.toString()); } } List<AbstractImporter> newImporters = new ArrayList<>(); for (final URI added: assignment.getAdded()) { if (m_configs.containsKey(added)) { AbstractImporter importer = m_factory.createImporter(m_configs.get(added)); newImporters.add(importer); builder.put(added, importer); } else { missingAddedURLs.add(added.toString()); } } if (!missingRemovedURLs.isEmpty() || !missingAddedURLs.isEmpty()) { s_logger.error("The source for Import has changed its configuration. Removed importer URL(s): (" + Joiner.on(", ").join(missingRemovedURLs) + "), added importer URL(s): (" + Joiner.on(", ").join(missingAddedURLs) + "). Pause and Resume the database to refresh the importer."); } ImmutableMap<URI, AbstractImporter> newReference = builder.build(); boolean success = m_importers.compareAndSet(oldReference, newReference); if (!m_stopping && success) { stopImporters(toStop); startImporters(newImporters); } }
Source:
public InMemoryObservationStore(NetworkConfig config) { if (LOGGER.isInfoEnabled()) { int healthStatusInterval = config.getInt(NetworkConfig.Keys.HEALTH_STATUS_INTERVAL, 60); ScheduledExecutorService scheduler = Executors .newSingleThreadScheduledExecutor(new DaemonThreadFactory("ObservationStore")); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (enableStatus) { LOGGER.info("{} observes", map.size()); Iterator<Token> iterator = map.keySet().iterator(); int max = 5; while (iterator.hasNext()) { LOGGER.info(" observe {}", iterator.next()); --max; if (max == 0) { break; } } } } }, healthStatusInterval, healthStatusInterval, TimeUnit.SECONDS); } }

Target:
public InMemoryObservationStore(NetworkConfig config) { int healthStatusInterval = config.getInt(NetworkConfig.Keys.HEALTH_STATUS_INTERVAL, 60); if (healthStatusInterval > 0 && LOGGER.isInfoEnabled()) { ScheduledExecutorService scheduler = Executors .newSingleThreadScheduledExecutor(new DaemonThreadFactory("ObservationStore")); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (enableStatus) { LOGGER.info("{} observes", map.size()); Iterator<Token> iterator = map.keySet().iterator(); int max = 5; while (iterator.hasNext()) { LOGGER.info(" observe {}", iterator.next()); --max; if (max == 0) { break; } } } } }, healthStatusInterval, healthStatusInterval, TimeUnit.SECONDS); } }
Source:
public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? Version.v3_6 : originalClusterVersion; this.oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { this.oldClusterVersionOfSnapshotWithMemory = null; } }

Target:
public void setOldClusterVersionOfSnapshotWithMemory(VM vm) { if (!isVMWithMemoryCompatible(vm)) { Version originalClusterVersion = vm.getClusterCompatibilityVersionOrigin(); originalClusterVersion = (originalClusterVersion == null) ? Version.v3_6 : originalClusterVersion; oldClusterVersionOfSnapshotWithMemory = originalClusterVersion; } else { oldClusterVersionOfSnapshotWithMemory = null; } }
Source:
private String getScoreHolderDrlFileContent( Class<? extends Score> scoreType ) { String lineSeparator = System.lineSeparator(); StringBuilder contentStringBuilder = new StringBuilder(); contentStringBuilder .append( "import " ).append( scoreType.getName() ).append( ";" ).append( lineSeparator ) .append( lineSeparator ) .append( " .append( lineSeparator ) .append( "global " ).append( scoreType.getSimpleName() ).append( "Holder" ).append( " scoreHolder;" ).append( lineSeparator ); return contentStringBuilder.toString(); }

Target:
private String getScoreHolderDrlFileContent( Class<? extends Score> scoreType ) { return String.format( "import %s;%n" + "%n" + " "%n" + "global %sHolder scoreHolder;%n", scoreType.getName(), scoreType.getSimpleName() ); }
Source:
private String HTTPAuthenticate() { HttpPost httpPost; CloseableHttpResponse response; BufferedReader rd; String line; StringEntity stringEntity; String cookie = null; try { httpPost = new HttpPost(baseUrl + "/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/"); httpPost.addHeader("SOAPAction", "urn:login"); httpPost.addHeader("Content-Type", "text/xml"); String payload = "<soapenv:Envelope xmlns:soapenv=\"<LINK_1>\" " + "xmlns:aut=\"<LINK_0>" + ".org\"><soapenv:Header/><soapenv:Body><aut:login><aut:username>admin</aut:username" + "><aut:password>admin</aut:password></aut:login></soapenv:Body></soapenv:Envelope>"; stringEntity = new StringEntity(payload, "UTF-8"); stringEntity.setChunked(true); httpPost.setEntity(stringEntity); response = client.execute(httpPost); rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())); StringBuffer result = new StringBuffer(); while ((line = rd.readLine()) != null) { result.append(line); } int returnStart = result.indexOf("<ns:return>") + "<ns:return>".length(); int returnEnd = result.indexOf("</ns:return>"); String isLoginSuccess = result.substring(returnStart, returnEnd); if (isLoginSuccess.equals("true")) { String str = response.getHeaders("Set-Cookie")[0].toString().split(";")[0]; cookie = str.split(" ")[1]; } } catch (ClientProtocolException e) { log.error("Exception : ", e); } catch (IOException e) { log.error("Exception : ", e); } return cookie; }

Target:
private String HTTPAuthenticate() throws IOException { HttpPost httpPost; String line; StringEntity stringEntity; String cookie = null; try (CloseableHttpResponse response = null; BufferedReader rd = null) { httpPost = new HttpPost(baseUrl + "/services/AuthenticationAdmin.AuthenticationAdminHttpsSoap11Endpoint/"); httpPost.addHeader(Constants.SOAP_ACTION, Constants.SOAP_ACTION_LOGIN); httpPost.addHeader(Constants.CONTENT_TYPE, Constants.XML_CONTENT_TYPE); String payload = "<soapenv:Envelope xmlns:soapenv=\"<LINK_1>\" " + "xmlns:aut=\"<LINK_0>" + ".org\"><soapenv:Header/><soapenv:Body><aut:login><aut:username>admin</aut:username" + "><aut:password>admin</aut:password></aut:login></soapenv:Body></soapenv:Envelope>"; stringEntity = new StringEntity(payload, Constants.UTF_8_ENCODING); stringEntity.setChunked(true); httpPost.setEntity(stringEntity); response = client.execute(httpPost); rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset())); StringBuffer result = new StringBuffer(); while ((line = rd.readLine()) != null) { result.append(line); } int returnStart = result.indexOf("<ns:return>") + "<ns:return>".length(); int returnEnd = result.indexOf("</ns:return>"); String isLoginSuccess = result.substring(returnStart, returnEnd); if (isLoginSuccess.equals("true")) { String str = response.getHeaders("Set-Cookie")[0].toString().split(";")[0]; cookie = str.split(" ")[1]; } } catch (ClientProtocolException e) { log.error(Constants.CLIENT_PROTOCOL_EX, e); } return cookie; }
Source:
public LockServerOptions getLockServerOptions() { LockServerOptions options = new LockServerOptions() { private static final long serialVersionUID = 0x3ffa5b160e838725l; @Override public boolean isStandaloneServer() { return isStandaloneServer; } @Override public TimeDuration getMaxAllowedLockTimeout() { return maxAllowedLockTimeout; } @Override public TimeDuration getMaxAllowedClockDrift() { return maxAllowedClockDrift; } @Override public int getRandomBitCount() { return randomBitCount; } }; if (log.isTraceEnabled()) { log.trace(".getLockServerOptions() returns {}", options); } return options; }

Target:
public LockServerOptions getLockServerOptions() { LockServerOptions options = new LockServerOptions() { private static final long serialVersionUID = 0x3ffa5b160e838725l; @Override public boolean isStandaloneServer() { return isStandaloneServer; } @Override public TimeDuration getMaxAllowedLockTimeout() { return maxAllowedLockTimeout; } @Override public TimeDuration getMaxAllowedClockDrift() { return maxAllowedClockDrift; } @Override public int getRandomBitCount() { return RANDOM_BIT_COUNT; } }; if (log.isTraceEnabled()) { log.trace(".getLockServerOptions() returns {}", options); } return options; }
Source:
private void performCheckOnSpecificClientUnsafe(Client client) { for (int attempt = 1; attempt <= REQUIRED_CONSECUTIVE_VIOLATIONS_BEFORE_FAIL; attempt++) { long numberOfNodesServingTimestamps = timeLockActivityCheckers.stream() .map(timeLockActivityChecker -> timeLockActivityChecker.isThisNodeActivelyServingTimestampsForClient(client.value())) .filter(x -> x) .count(); if (numberOfNodesServingTimestamps <= 1) { log.info("We don't think services were simultaneously serving timestamps for client {}", SafeArg.of("client", client)); return; } if (attempt < REQUIRED_CONSECUTIVE_VIOLATIONS_BEFORE_FAIL) { log.info("We observed on attempt of that multiple services were serving timestamps. We'll try" + " again in ms to see if this remains the case.", SafeArg.of("attemptNumber", attempt), SafeArg.of("maximumAttempts", REQUIRED_CONSECUTIVE_VIOLATIONS_BEFORE_FAIL), SafeArg.of("backoffMillis", BACKOFF.toMillis())); Uninterruptibles.sleepUninterruptibly(BACKOFF.toMillis(), TimeUnit.MILLISECONDS); } else { failureMechanism.accept(client.value()); } } }

Target:
private void performCheckOnSpecificClientUnsafe(Client client) { long timestampBound = Long.MIN_VALUE; for (int attempt = 1; attempt <= REQUIRED_ATTEMPTS_BEFORE_GIVING_UP; attempt++) { List<Long> timestamps = timeLockActivityCheckers.stream() .map(timeLockActivityChecker -> timeLockActivityChecker.getFreshTimestampFromNodeForClient(client.value())) .filter(OptionalLong::isPresent) .map(OptionalLong::getAsLong) .collect(Collectors.toList()); if (timestamps.size() <= 1) { log.info("We don't think services were simultaneously serving timestamps for client {}", SafeArg.of("client", client)); return; } if (!Ordering.natural().isStrictlyOrdered(timestamps) || timestamps.get(0) <= timestampBound) { failureMechanism.accept(client.value()); return; } timestampBound = timestamps.get(timestamps.size() - 1); log.info("We observed on attempt that multiple services were serving timestamps, but the timestamps were" + " served in an increasing order. We'll try again in ms to see if this remains the" + " case.", SafeArg.of("backoffMillis", backoff.toMillis())); Uninterruptibles.sleepUninterruptibly(backoff.toMillis(), TimeUnit.MILLISECONDS); } log.warn("We observed multiple services apparently serving timestamps simultaneously, but the timestamps" + " were consistently served in increasing order."); }
Source:
public UserOptions build() { UserOptions options = new UserOptions(); if ( limit != null ) { options.queryParameters.put("numResults", String.valueOf(limit)); limit = null; } if ( page != null ) { options.queryParameters.put("page", String.valueOf(page)); } return addFilterOptions(options); }

Target:
public UserOptions build() { return addFilterOptions(this.options); }
Source:
public List<ActivationKeyDTO> ownerActivationKeys( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, @QueryParam("name") String keyName) { Owner owner = findOwner(ownerKey); if (keyName == null) { List<ActivationKey> keys = this.activationKeyCurator.listByOwner(owner); List<ActivationKeyDTO> keyDTOs = new ArrayList<ActivationKeyDTO>(); for (ActivationKey key : keys) { keyDTOs.add(translator.translate(key, ActivationKeyDTO.class)); } return keyDTOs; } else { List<ActivationKeyDTO> results = new ArrayList<ActivationKeyDTO>(); results.add(translator.translate( activationKeyCurator.lookupForOwner(keyName, owner), ActivationKeyDTO.class)); return results; } }

Target:
public CandlepinQuery<ActivationKeyDTO> ownerActivationKeys( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, @QueryParam("name") String keyName) { Owner owner = findOwner(ownerKey); CandlepinQuery<ActivationKey> keys = this.activationKeyCurator.listByOwner(owner, keyName); return translator.translateQuery(keys, ActivationKeyDTO.class); }
Source:
public void testInitialNamedDeployments() { final String urlSubPathToWebApp = APP_NAME; final String urlSubPathToPageToQuery = ""; LOG.info("test=testInitialNamedDeployments; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.minutes(2)), new Runnable() { public void run() { String url = Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery); HttpTestUtils.assertHttpStatusCodeEquals(url, 200); }}); }

Target:
public void testInitialNamedDeployments() { final String urlSubPathToWebApp = APP_NAME; final String urlSubPathToPageToQuery = ""; LOG.info("test=testInitialNamedDeployments; entity="+entity+"; app="+entity.getApplication()); Entities.start(entity.getApplication(), ImmutableList.of(loc)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.minutes(1)), new Runnable() { public void run() { String url = Urls.mergePaths(entity.getAttribute(WebAppService.ROOT_URL), urlSubPathToWebApp, urlSubPathToPageToQuery); HttpTestUtils.assertHttpStatusCodeEquals(url, 200); }}); }
Source:
public ResponseEntity<?> readTicketTypes() { Collection<TicketType> ticketTypes = ticketService.getAllTicketTypes(); return createResponseEntity(HttpStatus.OK, "TicketTypes successfully retrieved.", ticketTypes); }

Target:
public Collection<TicketType> readTicketTypes() { return ticketService.getAllTicketTypes(); }
Source:
private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); System.out.println(g0); System.out.println(ug); System.out.println(s); assertTrue(g0.equals(ug)); }

Target:
private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); assertTrue(g0.equals(ug)); }
Source:
public void registerModuleMusic(String shipName) { Set<ResourceUrn> configUrnList = Assets.getAssetHelper().list(Json.class, "[a-zA-Z]*:playerSpawnConfig"); for (ResourceUrn configUrn : configUrnList) { Json json = Assets.getJson(configUrn.toString()); JSONObject rootNode = json.getJsonValue(); if (rootNode.keySet().contains(shipName) && rootNode.get(shipName) instanceof JSONObject) { JSONObject shipNode = rootNode.getJSONObject(shipName); String moduleName = shipNode.getString("hull").split(":")[0]; Json musicJson; try { musicJson = Assets.getJson(moduleName + ":musicConfig"); } catch (RuntimeException e) { logger.warn("Music config not found for module " + moduleName + ":musicConfig"); return; } MusicConfig musicConfig = MusicConfig.load(moduleName, musicJson.getJsonValue()); Map<String, List<String>> musicMap = musicConfig.getMusicMap(); for (String music : musicMap.get(MENU_MUSIC_SET)) { registerMusic(MENU_MUSIC_SET, music); } for (String music : musicMap.get(GAME_MUSIC_SET)) { registerMusic(GAME_MUSIC_SET, music); } } json.dispose(); } }

Target:
public void registerModuleMusic(String shipName) { Set<ResourceUrn> configUrnList = Assets.getAssetHelper().list(Json.class, "[a-zA-Z]*:playerSpawnConfig"); for (ResourceUrn configUrn : configUrnList) { Json json = Assets.getJson(configUrn.toString()); JSONObject rootNode = json.getJsonValue(); if (rootNode.keySet().contains(shipName) && rootNode.get(shipName) instanceof JSONObject) { String moduleName = configUrn.toString().split(":")[0]; Json musicJson; try { musicJson = Assets.getJson(moduleName + ":musicConfig"); } catch (RuntimeException e) { logger.warn("Music config not found for module " + moduleName + ":musicConfig"); return; } MusicConfig musicConfig = MusicConfig.load(moduleName, musicJson.getJsonValue()); Map<String, List<String>> musicMap = musicConfig.getMusicMap(); this.musicMap.remove(MENU_MUSIC_SET); for (String music : musicMap.get(MENU_MUSIC_SET)) { registerMusic(MENU_MUSIC_SET, music); } for (String music : musicMap.get(GAME_MUSIC_SET)) { registerMusic(GAME_MUSIC_SET, music); logger.info("Registered " + music); } } json.dispose(); } registerMusic(GAME_MUSIC_SET, "engine:cimmerianDawn"); registerMusic(GAME_MUSIC_SET, "engine:intoTheDark"); registerMusic(GAME_MUSIC_SET, "engine:spaceTheatre"); }
Source:
public Response add(Command entity) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); }

Target:
public Response add(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); Context.getDeviceManager().sendCommand(entity); return Response.ok(entity).build(); }
Source:
public Stream<EventInformation> loadEventLogFileAsStream(File eventLogFile) throws IOException { List<String> lines = FileUtils.readLines(eventLogFile, ENCODING_UTF_8); return lines.stream().map(line -> { try { return (EventInformation) objectMapper.readValue(line, new TypeReference<EventInformation>() {}); } catch (IOException e) { throw new RuntimeException(e); } }); }

Target:
public Stream<EventInformation> loadEventLogFileAsStream(File eventLogFile) throws IOException { Stream<String> lines = Files.lines(eventLogFile.toPath(), ENCODING_UTF_8); return lines.map(line -> { try { return (EventInformation) objectMapper.readValue(line, new TypeReference<EventInformation>() {}); } catch (IOException e) { throw new RuntimeException(e); } }); }
Source:
public LookupExtractionFn( @JsonProperty("lookup") final LookupExtractor lookup, @JsonProperty("retainMissingValue") final boolean retainMissingValue, @Nullable @JsonProperty("replaceMissingValueWith") final String replaceMissingValueWith, @JsonProperty("injective") final boolean injective ) { super( new Function<String, String>() { @Nullable @Override public String apply(@Nullable String input) { if (Strings.isNullOrEmpty(input)) { return null; } return lookup.apply(input); } }, retainMissingValue, replaceMissingValueWith, injective ); this.lookup = lookup; }

Target:
public LookupExtractionFn( @JsonProperty("lookup") final LookupExtractor lookup, @JsonProperty("retainMissingValue") final boolean retainMissingValue, @Nullable @JsonProperty("replaceMissingValueWith") final String replaceMissingValueWith, @JsonProperty("injective") final boolean injective ) { super( new Function<String, String>() { @Nullable @Override public String apply(String input) { return lookup.apply(Strings.nullToEmpty(input)); } }, retainMissingValue, replaceMissingValueWith, injective ); this.lookup = lookup; }
Source:
public void delete(HttpServletRequest request, HttpServletResponse response) throws ZebedeeException, IOException { Session session = zebedeeCmsService.getSession(request); if (!zebedeeCmsService.getPermissions().canEdit(session)) { logInfo("Forbidden request made to the collection endpoint").log(); response.setStatus(HttpStatus.SC_FORBIDDEN); return; } Path path = Path.newInstance(request); List<String> segments = path.segments(); if (segments.size() < 4 || !segments.get(2).equalsIgnoreCase("instances")) { logInfo("Endpoint for colletions not found").addParameter("path", path).log(); response.setStatus(HttpStatus.SC_NOT_FOUND); return; } String collectionID = segments.get(1); String instanceID = segments.get(3); logInfo("DELETE called on /collections/{collection_id}/instances/{instance_id} endpoint") .addParameter("collectionID", collectionID) .addParameter("instanceID", instanceID) .log(); datasetService.deleteInstanceFromCollection(collectionID, instanceID); }

Target:
public void delete(HttpServletRequest request, HttpServletResponse response) throws ZebedeeException, IOException { Session session = zebedeeCmsService.getSession(request); if (!zebedeeCmsService.getPermissions().canEdit(session)) { logInfo("Forbidden request made to the collection endpoint").log(); response.setStatus(HttpStatus.SC_FORBIDDEN); return; } Path path = Path.newInstance(request); List<String> segments = path.segments(); if (!isValidPath(response, path, segments)) return; String collectionID = segments.get(1); String instanceID = segments.get(3); logInfo("DELETE called on /collections/{collection_id}/instances/{instance_id} endpoint") .addParameter("collectionID", collectionID) .addParameter("instanceID", instanceID) .log(); datasetService.deleteInstanceFromCollection(collectionID, instanceID); }
Source:
public Dataset wrap(String datasourceName, boolean shouldEmitMessage, Dataset dataset) { String datasourceURI = String.format("%s/%s", deltaServerURL, datasourceName); Id dsRef = deltaLink.newDataSource(datasourceName, datasourceURI); deltaClient.attachExternal(dsRef, dataset.asDatasetGraph()); deltaClient.connect(dsRef, SyncPolicy.TXN_W); try (DeltaConnection dConn = deltaClient.get(dsRef)) { if (shouldEmitMessage && jmsMessagingClient != null) { dConn.addListener(new DeltaLinkListener() { @Override public void append(Id dsRef, Version version, RDFPatch patch) { try { jmsMessagingClient.send(RDFPatchOps.str(patch)); } catch (JMSException e) { log.error(e, e); } } }); } else { if (jmsMessagingClient == null) { log.warn("Can not emit messaged without message client"); } } log.info(String.format("Wrapped dataset using datasource %s with reference %s", datasourceName, dsRef)); return dConn.getDataset(); } catch (Exception e) { log.error(e, e); throw e; } }

Target:
public Dataset wrap(String datasourceName, boolean shouldEmitMessage, Dataset dataset) { String datasourceURI = String.format("%s/%s", deltaServerURL, datasourceName); Id dsRef = deltaLink.newDataSource(datasourceName, datasourceURI); deltaClient.attachExternal(dsRef, dataset.asDatasetGraph()); deltaClient.connect(dsRef, SyncPolicy.TXN_W); try (DeltaConnection dConn = deltaClient.get(dsRef)) { if (shouldEmitMessage && jmsMessagingClient != null) { dConn.addListener(new DeltaLinkListener() { @Override public void append(Id dsRef, Version version, RDFPatch patch) { try { jmsMessagingClient.send(RDFPatchOps.str(patch)); } catch (JMSException e) { log.error(e, e); } } }); } else { if (jmsMessagingClient == null) { log.warn("Can not emit message without client"); } } log.info(String.format("Wrapped dataset using datasource %s with reference %s", datasourceName, dsRef)); return dConn.getDataset(); } }
Source:
public void shoudNotSaveItem_withAlreadyExistingUniqueConstraintValueButDifferentCase() { final StubItem stubItem = dataGenerator.randomStubItem(); final StubItem secondItem = dataGenerator.randomStubItem(); final String uniqueConstraintAttributeName = "stringProperty"; final String stubItemIndexAttributeValue = stubItem.getStringProperty(); final ItemConfiguration stubItemConfigurationWithUniqueConstratints = new ItemConfiguration( stubItem.getClass(), "stubTable"); stubItemConfigurationWithUniqueConstratints.registerUniqueConstraints(Arrays.asList(new UniqueConstraint( uniqueConstraintAttributeName))); final DatabaseSchemaHolder databaseSchemaHolderWithUniqueConstraints = databaseSchemaHolderWithItemConfiguration(stubItemConfigurationWithUniqueConstratints); final InMemoryDatabaseTemplate databaseTemplate = new InMemoryDatabaseTemplate( databaseSchemaHolderWithUniqueConstraints); databaseTemplate.create(stubItem); secondItem.setStringProperty(stubItemIndexAttributeValue.toUpperCase()); ItemConstraintViolationException actualException = null; try { databaseTemplate.create(secondItem); } catch (final ItemConstraintViolationException e) { actualException = e; } assertNotNull(actualException); assertEquals(stubItem, databaseTemplate.read(new ItemId(stubItem.getId()), stubItem.getClass())); }

Target:
public void shoudNotSaveItem_withAlreadyExistingUniqueConstraintValueButDifferentCase() { final StubItem stubItem = dataGenerator.randomStubItem(); final StubItem secondItem = dataGenerator.randomStubItem(); final String uniqueConstraintAttributeName = "stringProperty"; final String stubItemIndexAttributeValue = stubItem.getStringProperty(); final ItemConfiguration stubItemConfigurationWithUniqueConstraints = new ItemConfiguration(stubItem.getClass(), "stubTable"); stubItemConfigurationWithUniqueConstraints.registerUniqueConstraints(Arrays.asList(new UniqueConstraint( uniqueConstraintAttributeName))); final DatabaseSchemaHolder databaseSchemaHolderWithUniqueConstraints = databaseSchemaHolderWithItemConfiguration(stubItemConfigurationWithUniqueConstraints); final InMemoryDatabaseTemplate databaseTemplate = new InMemoryDatabaseTemplate( databaseSchemaHolderWithUniqueConstraints); databaseTemplate.create(stubItem); secondItem.setStringProperty(stubItemIndexAttributeValue.toUpperCase()); ItemConstraintViolationException actualException = null; try { databaseTemplate.create(secondItem); } catch (final ItemConstraintViolationException e) { actualException = e; } assertNotNull(actualException); assertEquals(stubItem, databaseTemplate.read(new ItemId(stubItem.getId()), stubItem.getClass())); }
Source:
public String update(Request req, Response res) throws IOException { AdminsConfig adminsConfigFromRequest = getEntityFromRequestBody(req); AdminsConfig adminsConfigFromServer = adminsConfigService.systemAdmins(); if (!isPutRequestFresh(req, adminsConfigFromServer)) { throw haltBecauseEtagDoesNotMatch("system_admins", ""); } HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); adminsConfigService.update(SessionUtils.currentUsername(), adminsConfigFromRequest, etagFor(adminsConfigFromServer), result); return handleCreateOrUpdateResponse(req, res, adminsConfigFromRequest, result); }

Target:
public String update(Request req, Response res) throws IOException { AdminsConfig adminsConfigFromRequest = getEntityFromRequestBody(req); AdminsConfig adminsConfigFromServer = adminsConfigService.systemAdmins(); if (!isPutRequestFresh(req, adminsConfigFromServer)) { throw haltBecauseEtagDoesNotMatch(); } HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); adminsConfigService.update(currentUsername(), adminsConfigFromRequest, etagFor(adminsConfigFromServer), result); return handleCreateOrUpdateResponse(req, res, adminsConfigFromRequest, result); }
Source:
private String handleAggregationFunction(CallExpression aggregation, Map<VariableReferenceExpression, Selection> inputSelections) { String prestoAggregation = aggregation.getDisplayName().toLowerCase(ENGLISH); List<RowExpression> parameters = aggregation.getArguments(); switch (prestoAggregation) { case "count": if (parameters.size() <= 1) { return format("count(%s)", parameters.isEmpty() ? "*" : inputSelections.get(getVariableReference(parameters.get(0)))); } break; default: if (UNARY_AGGREGATION_MAP.containsKey(prestoAggregation) && aggregation.getArguments().size() == 1) { return format("%s(%s)", UNARY_AGGREGATION_MAP.get(prestoAggregation), inputSelections.get(getVariableReference(parameters.get(0)))); } } throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported pushdown for Druid connector. Aggregation function:" + aggregation + " not supported"); }

Target:
private String handleAggregationFunction(CallExpression aggregation, Map<VariableReferenceExpression, Selection> inputSelections) { String prestoAggregation = aggregation.getDisplayName().toLowerCase(ENGLISH); List<RowExpression> parameters = aggregation.getArguments(); if (prestoAggregation.equals("count")) { if (parameters.size() <= 1) { return format("count(%s)", parameters.isEmpty() ? "*" : inputSelections.get(getVariableReference(parameters.get(0)))); } } else if (UNARY_AGGREGATION_MAP.containsKey(prestoAggregation) && aggregation.getArguments().size() == 1) { return format("%s(%s)", UNARY_AGGREGATION_MAP.get(prestoAggregation), inputSelections.get(getVariableReference(parameters.get(0)))); } throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported pushdown for Druid connector. Aggregation function: " + aggregation + " not supported"); }
Source:
public T put(HttpServletRequest request, String apiCategory, String model, ID uuid, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, uuid, jsonNode); context.commit(); } catch (SQLException | AuthorizeException e) { throw new RuntimeException(e.getMessage(), e); } return findOne(uuid); }

Target:
public T put(HttpServletRequest request, String apiCategory, String model, ID uuid, JsonNode jsonNode) { Context context = obtainContext(); try { thisRepository.put(context, request, apiCategory, model, uuid, jsonNode); context.commit(); } catch (SQLException e) { throw new RuntimeException("Unable to update DSpace object " + model + " with id=" + uuid, e); } catch (AuthorizeException e) { throw new RuntimeException("Unable to perform PUT request as the " + "current user does not have sufficient rights", e); } return findOne(uuid); }
Source:
private boolean shouldAddToRunningIntervalList(final long idealSplitLength, final long projectedSize, final double projectedSizeOfRemainingDivisions) { switch (mode) { case INTERVAL_SUBDIVISION: case BALANCING_WITHOUT_INTERVAL_SUBDIVISION: return (projectedSize <= idealSplitLength); case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW: return (projectedSize <= idealSplitLength || idealSplitLength < projectedSizeOfRemainingDivisions); default: throw new PicardException("Unknown mode: " + mode.name()); } }

Target:
private boolean shouldAddToRunningIntervalList(final long idealSplitLength, final long projectedSize, final double projectedSizeOfRemainingDivisions) { switch (mode) { case BALANCING_WITHOUT_INTERVAL_SUBDIVISION_WITH_OVERFLOW: return (projectedSize <= idealSplitLength || idealSplitLength < projectedSizeOfRemainingDivisions); default: return (projectedSize <= idealSplitLength); } }
Source:
public static EndpointContext extractContext(Identity identity) { Principal peerIdentity = null; if (identity != null) { if (identity.isPSK()) { peerIdentity = new PreSharedKeyIdentity(identity.getPskIdentity()); } else if (identity.isRPK()) { peerIdentity = new RawPublicKeyIdentity(identity.getRawPublicKey()); } else if (identity.isX509()) { if (identity.getCertificates() != null) { peerIdentity = new X509CertPath(identity.getCertificates()); } else { peerIdentity = new X500Principal("CN=" + identity.getX509CommonName()); } } } return new AddressEndpointContext(identity.getPeerAddress(), peerIdentity); }

Target:
public static EndpointContext extractContext(Identity identity) { Principal peerIdentity = null; if (identity != null) { if (identity.isPSK()) { peerIdentity = new PreSharedKeyIdentity(identity.getPskIdentity()); } else if (identity.isRPK()) { peerIdentity = new RawPublicKeyIdentity(identity.getRawPublicKey()); } else if (identity.isX509()) { if (identity.getCertificates() != null) { peerIdentity = new X509CertPath(identity.getCertificates()); } else { peerIdentity = new X500Principal(X509Util.createDN(identity.getX509CommonName())); } } } return new AddressEndpointContext(identity.getPeerAddress(), peerIdentity); }
Source:
private void setListeners() { enterPinBox.addTextChangedListener(getPinTextWatcher(continueButton)); enterPinBox.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) { if (enterPinBox.getText().toString().length() != 4) { Toast.makeText(CreatePinActivity.this, Localization.get("pin.length.error"), Toast.LENGTH_LONG).show(); } else { continueButton.performClick(); } return true; } return false; } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); continueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!inConfirmMode) { processInitialPinEntry(); } else { processConfirmPinEntry(); } } }); }

Target:
private void setListeners() { enterPinBox.addTextChangedListener(getPinTextWatcher(continueButton)); enterPinBox.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) { if (pinLengthIsValid(enterPinBox.getText())) { continueButton.performClick(); } else { Toast.makeText(CreatePinActivity.this, Localization.get("pin.length.error"), Toast.LENGTH_LONG).show(); } return true; } return false; } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); continueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!inConfirmMode) { processInitialPinEntry(); } else { processConfirmPinEntry(); } } }); }
Source:
public void init(FilterConfig filterConfig) throws ServletException { String hashPrivateData = firstNonNull(filterConfig.getInitParameter("hash-private-data"), "true"); if (parseBoolean(hashPrivateData)) { this.rewrite = (String s) -> sha256().hashString(s, UTF_8).toString(); } else { this.rewrite = (String s) -> s; } }

Target:
public void init(FilterConfig filterConfig) throws ServletException { }
Source:
public static SQLDatabase createSQLDatabase(String dbFilename, KeyProvider provider) throws IOException { boolean runningOnAndroid = Misc.isRunningOnAndroid(); boolean useSqlCipher = (provider.getEncryptionKey() != null); makeSureFileExists(dbFilename); try { if (runningOnAndroid) { if (useSqlCipher) { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLCipherSQLite") .getMethod("createAndroidSQLite", String.class, KeyProvider.class) .invoke(null, new Object[]{dbFilename, provider}); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLite") .getMethod("createAndroidSQLite", String.class) .invoke(null, dbFilename); } } else { if (useSqlCipher) { throw new IOException("No SQLCipher-based database implementation for Java SE"); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.sqlite4java.SQLiteWrapper") .getMethod("openSQLiteWrapper", String.class) .invoke(null, dbFilename); } } } catch (Exception e) { logger.log(Level.SEVERE, "Failed to load database module", e); return null; } }

Target:
public static SQLDatabase createSQLDatabase(String dbFilename, KeyProvider provider) throws IOException { boolean runningOnAndroid = Misc.isRunningOnAndroid(); boolean useSqlCipher = (provider.getEncryptionKey() != null); makeSureFileExists(dbFilename); try { if (runningOnAndroid) { if (useSqlCipher) { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLCipherSQLite") .getMethod("createAndroidSQLite", String.class, KeyProvider.class) .invoke(null, new Object[]{dbFilename, provider}); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.android.AndroidSQLite") .getMethod("createAndroidSQLite", String.class) .invoke(null, dbFilename); } } else { if (useSqlCipher) { throw new UnsupportedOperationException("No SQLCipher-based database implementation for Java SE"); } else { return (SQLDatabase) Class.forName("com.cloudant.sync.sqlite.sqlite4java.SQLiteWrapper") .getMethod("openSQLiteWrapper", String.class) .invoke(null, dbFilename); } } } catch (Exception e) { logger.log(Level.SEVERE, "Failed to load database module", e); return null; } }
Source:
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return annotationType.equals(ActivateThreadScope.class) ? false : delegate.isAnnotationPresent(annotationType); }

Target:
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return getAnnotation(annotationType) != null; }
Source:
protected Map<String,?> createModel(HttpServletRequest request, HttpServletResponse response) { List<ErrorModel> errors = null; String errorQueryString = request.getQueryString(); boolean requestContainsError = request.getParameter("error") != null || (errorQueryString != null && errorQueryString.contains("error")); if (requestContainsError) { errors = new ArrayList<>(); ErrorModel error = null; HttpSession session = request.getSession(false); if (session != null && session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY) != null) { error = (ErrorModel) session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY); } else { error = ErrorModel.builder() .setStatus(HttpStatus.SC_BAD_REQUEST).setMessage(request.getParameter("error")).build(); } errors.add(error); } return createModel(request, response, null, errors); }

Target:
protected Map<String,?> createModel(HttpServletRequest request, HttpServletResponse response) { List<ErrorModel> errors = null; String queryString = request.getQueryString(); boolean requestContainsError = request.getParameter("error") != null || (queryString != null && queryString.contains("error")); if (requestContainsError) { errors = new ArrayList<>(); ErrorModel error = null; HttpSession session = request.getSession(false); if (session != null && session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY) != null) { error = (ErrorModel) session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY); } else { error = ErrorModel.builder() .setStatus(HttpStatus.SC_BAD_REQUEST).setMessage(request.getParameter("error")).build(); } errors.add(error); } return createModel(request, response, null, errors); }