auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testIpSubnetMin() { assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/24')", IPADDRESS, "1.2.3.0"); assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/32')", IPADDRESS, "1.2.3.4"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/127')", IPADDRESS, "64:ff9b::16"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/128')", IPADDRESS, "64:ff9b::17"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/0')", IPADDRESS, "::"); <START> assertInvalidCast("IP_SUBNET_MIN(IPPREFIX '64::ff9b::10/48')", "Cannot cast value to IPPREFIX: 64::ff9b::10/48"); assertInvalidCast("IP_SUBNET_MIN(IPPREFIX '123.456.789.012/24')", "Cannot cast value to IPPREFIX: 123.456.789.012/24"); <END> }</code><technical_language>2 test cases do belong this test method. IP_PREFIX, VARCHAR input, 2 test cases testing behavior of IP_SUBNET_MIN, behavior of casting VARCHAR IPPREFIX</technical_language>

Target:
public void testIpSubnetMin() { assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/24')", IPADDRESS, "1.2.3.0"); assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/32')", IPADDRESS, "1.2.3.4"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/127')", IPADDRESS, "64:ff9b::16"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/128')", IPADDRESS, "64:ff9b::17"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/0')", IPADDRESS, "::"); }
Source:
<code>public Optional<PostEntity> getPostById(String postId) { <START> return Optional.ofNullable( <END> getPost() .getPosts() .stream() .peek(postEntity -> scrollTo(postEntity.getWebElement())) .filter(postEntity -> postEntity.findId().equals(postId)) .findFirst() .orElseThrow(() -> new RuntimeException(String.format("Post with id [%s] not found on page", postId)))); }</code><technical_language>This outer optional shouldnt needed</technical_language>

Target:
public PostEntity getPostById(String postId) { return getPost() .getPosts() .stream() .peek(postEntity -> scrollTo(postEntity.getWebElement())) .filter(postEntity -> postEntity.findId().equals(postId)) .findFirst() .orElseThrow( () -> new RuntimeException(String.format("Post with id [%s] not found on page", postId))); }
Source:
<code><START> public Court GetCourtById(Long courtId) throws NotFoundException { <END> return courtDAO.getByCourtId(courtId); }</code><technical_language>able remove changes change aforementioned</technical_language>

Target:
public Court GetCourtById(Long courtId){ return courtDAO.getByCourtId(courtId); }
Source:
<code>protected void terminate() throws ResourceManagerException { try { resourceManagerDriver.terminate().get(); <START> } catch (Throwable t) { <END> throw new ResourceManagerException("Cannot terminate resource provider.", t); } }</code><technical_language>Throwable</technical_language>

Target:
protected void terminate() throws ResourceManagerException { try { resourceManagerDriver.terminate().get(); } catch (Exception e) { throw new ResourceManagerException("Cannot terminate resource provider.", e); } }
Source:
<code>private void setupConfForPySpark(SparkConf conf) { String pysparkBasePath = new InterpreterProperty("SPARK_HOME", null, null, null).getValue(); File pysparkPath; if (null == pysparkBasePath) { pysparkBasePath = new InterpreterProperty("ZEPPELIN_HOME", "zeppelin.home", "../", null).getValue(); pysparkPath = new File(pysparkBasePath, "interpreter" + File.separator + "spark" + File.separator + "pyspark"); } else { pysparkPath = new File(pysparkBasePath, "python" + File.separator + "lib"); } String[] pythonLibs = new String[]{"pyspark.zip", "py4j-0.9-src.zip", "py4j-0.8.2.1-src.zip", <START> "py4j-0.10.3-src.zip"}; <END> ArrayList<String> pythonLibUris = new ArrayList<>(); for (String lib : pythonLibs) { File libFile = new File(pysparkPath, lib); if (libFile.exists()) { pythonLibUris.add(libFile.toURI().toString()); } } pythonLibUris.trimToSize(); if (pythonLibUris.size() == 2) { try { String confValue = conf.get("spark.yarn.dist.files"); conf.set("spark.yarn.dist.files", confValue + "," + Joiner.on(",").join(pythonLibUris)); } catch (NoSuchElementException e) { conf.set("spark.yarn.dist.files", Joiner.on(",").join(pythonLibUris)); } if (!useSparkSubmit()) { conf.set("spark.files", conf.get("spark.yarn.dist.files")); } conf.set("spark.submit.pyArchives", Joiner.on(":").join(pythonLibs)); } if (getProperty("master").equals("yarn-client")) { conf.set("spark.yarn.isPython", "true"); } }</code><technical_language>"py4j-0.10.1-src.zip" need in array for in case of spark 2.0.0</technical_language>

Target:
private void setupConfForPySpark(SparkConf conf) { String pysparkBasePath = new InterpreterProperty("SPARK_HOME", null, null, null).getValue(); File pysparkPath; if (null == pysparkBasePath) { pysparkBasePath = new InterpreterProperty("ZEPPELIN_HOME", "zeppelin.home", "../", null).getValue(); pysparkPath = new File(pysparkBasePath, "interpreter" + File.separator + "spark" + File.separator + "pyspark"); } else { pysparkPath = new File(pysparkBasePath, "python" + File.separator + "lib"); } String[] pythonLibs = new String[]{"pyspark.zip", "py4j-0.9-src.zip", "py4j-0.8.2.1-src.zip", "py4j-0.10.1-src.zip", "py4j-0.10.3-src.zip"}; ArrayList<String> pythonLibUris = new ArrayList<>(); for (String lib : pythonLibs) { File libFile = new File(pysparkPath, lib); if (libFile.exists()) { pythonLibUris.add(libFile.toURI().toString()); } } pythonLibUris.trimToSize(); if (pythonLibUris.size() == 2) { try { String confValue = conf.get("spark.yarn.dist.files"); conf.set("spark.yarn.dist.files", confValue + "," + Joiner.on(",").join(pythonLibUris)); } catch (NoSuchElementException e) { conf.set("spark.yarn.dist.files", Joiner.on(",").join(pythonLibUris)); } if (!useSparkSubmit()) { conf.set("spark.files", conf.get("spark.yarn.dist.files")); } conf.set("spark.submit.pyArchives", Joiner.on(":").join(pythonLibs)); } if (getProperty("master").equals("yarn-client")) { conf.set("spark.yarn.isPython", "true"); } }
Source:
<code>public void seek(long desired) throws IOException { <START> inStream.skip(desired); <END> }</code><technical_language>right ;-)</technical_language>

Target:
public void seek(long desired) throws IOException { throw new UnsupportedOperationException("Compressed streams do not support the seek operation"); }
Source:
<code>public void testCreateTableWithPrimaryKey() { final String sql = "CREATE TABLE tbl1 (\n" + " a bigint,\n" + " b varchar, \n" + " c int, \n" + " d varchar, \n" + " constraint ct1 primary key(a, b) not enforced\n" + ") with (\n" + " 'connector' = 'kafka', \n" + " 'kafka.topic' = 'log.test'\n" + ")\n"; FlinkPlannerImpl planner = getPlannerBySqlDialect(SqlDialect.DEFAULT); final CalciteParser parser = getParserBySqlDialect(SqlDialect.DEFAULT); Operation operation = parse(sql, planner, parser); assert operation instanceof CreateTableOperation; CreateTableOperation op = (CreateTableOperation) operation; CatalogTable catalogTable = op.getCatalogTable(); TableSchema tableSchema = catalogTable.getSchema(); assertThat( tableSchema .getPrimaryKey() .map(UniqueConstraint::asSummaryString) .orElse("fakeVal"), is("CONSTRAINT ct1 PRIMARY KEY (a, b)")); <START> assertArrayEquals(tableSchema.getFieldNames(), new String[] {"a", "b", "c", "d"}); <END> assertArrayEquals(tableSchema.getFieldDataTypes(), new DataType[]{ DataTypes.BIGINT().notNull(), DataTypes.STRING().notNull(), DataTypes.INT(), DataTypes.STRING()}); }</code><technical_language>Swap 2 parameters, parameter expected , actual. assertArrayEquals(new String[] {"a", "b", "c", "d"}, tableSchema.getFieldNames());</technical_language>

Target:
public void testCreateTableWithPrimaryKey() { final String sql = "CREATE TABLE tbl1 (\n" + " a bigint,\n" + " b varchar, \n" + " c int, \n" + " d varchar, \n" + " constraint ct1 primary key(a, b) not enforced\n" + ") with (\n" + " 'connector' = 'kafka', \n" + " 'kafka.topic' = 'log.test'\n" + ")\n"; FlinkPlannerImpl planner = getPlannerBySqlDialect(SqlDialect.DEFAULT); final CalciteParser parser = getParserBySqlDialect(SqlDialect.DEFAULT); Operation operation = parse(sql, planner, parser); assert operation instanceof CreateTableOperation; CreateTableOperation op = (CreateTableOperation) operation; CatalogTable catalogTable = op.getCatalogTable(); TableSchema tableSchema = catalogTable.getSchema(); assertThat( tableSchema .getPrimaryKey() .map(UniqueConstraint::asSummaryString) .orElse("fakeVal"), is("CONSTRAINT ct1 PRIMARY KEY (a, b)")); assertArrayEquals( new String[] {"a", "b", "c", "d"}, tableSchema.getFieldNames()); assertArrayEquals( new DataType[]{ DataTypes.BIGINT().notNull(), DataTypes.STRING().notNull(), DataTypes.INT(), DataTypes.STRING()}, tableSchema.getFieldDataTypes()); }
Source:
<code>public SimpleFeature next() { SimpleFeature next = super.next(); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); for (Property property : next.getProperties()) { if (property instanceof GeometryAttribute) { builder.set(featureType.getGeometryDescriptor().getName(), property.getValue()); } else { builder.set(property.getName().getLocalPart(), property.getValue()); } } Map<Object, Object> userData = next.getUserData(); for (Entry<Object, Object> entry : userData.entrySet()) { builder.featureUserData(entry.getKey(), entry.getValue()); <START> } <END> String oldFeatureId = next.getIdentifier().getID(); String featureId; if (fidMappings.containsKey(oldFeatureId)) { featureId = fidMappings.get(oldFeatureId); } else { featureId = SimpleFeatureBuilder.createDefaultFeatureId(); } return builder.buildFeature(featureId); }</code><technical_language>lines 80 90 replaced a simple builder.init(next)</technical_language>

Target:
public SimpleFeature next() { SimpleFeature next = super.next(); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); builder.init(next); String oldFeatureId = next.getIdentifier().getID(); String featureId; if (fidMappings.containsKey(oldFeatureId)) { featureId = fidMappings.get(oldFeatureId); } else { featureId = SimpleFeatureBuilder.createDefaultFeatureId(); } return builder.buildFeature(featureId); }
Source:
<code><START> public Paint getPaint() { <END> return paint; }</code><technical_language>Is this paintColor for Coordinate? I guess internally a Color object return Color well. I generall I prefer members name is for, ig. paintColor named getters setters (like for lineStyle ;))</technical_language>

Target:
public Color getPaint() { return paint; }
Source:
<code>public static void main(String[] args) { System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "INFO"); System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, "System.err"); Logger LOG = LoggerFactory.getLogger(SystemInfoTest.class); LOG.info("Initializing System..."); SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); <START> printSoundCards(hal.getSoundCards()); <END> }</code><technical_language>left debugging, deleted else. :)</technical_language>

Target:
public static void main(String[] args) { System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "INFO"); System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, "System.err"); Logger LOG = LoggerFactory.getLogger(SystemInfoTest.class); LOG.info("Initializing System..."); SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); System.out.println(os); LOG.info("Checking computer system..."); printComputerSystem(hal.getComputerSystem()); LOG.info("Checking Processor..."); printProcessor(hal.getProcessor()); LOG.info("Checking Memory..."); printMemory(hal.getMemory()); LOG.info("Checking CPU..."); printCpu(hal.getProcessor()); LOG.info("Checking Processes..."); printProcesses(os, hal.getMemory()); LOG.info("Checking Sensors..."); printSensors(hal.getSensors()); LOG.info("Checking Power sources..."); printPowerSources(hal.getPowerSources()); LOG.info("Checking Disks..."); printDisks(hal.getDiskStores()); LOG.info("Checking File System..."); printFileSystem(os.getFileSystem()); LOG.info("Checking Network interfaces..."); printNetworkInterfaces(hal.getNetworkIFs()); LOG.info("Checking Network parameterss..."); printNetworkParameters(os.getNetworkParams()); LOG.info("Checking Displays..."); printDisplays(hal.getDisplays()); LOG.info("Checking USB Devices..."); printUsbDevices(hal.getUsbDevices(true)); LOG.info("Checking Sound Cards..."); printSoundCards(hal.getSoundCards()); }
Source:
<code>public void testPITRow() throws Exception { final int NROWS = 1; String schemaName = generateUniqueName(); String dataTableName = generateUniqueName(); String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName); String indexTableName = generateUniqueName(); String indexTableFullName = SchemaUtil.getTableName(schemaName, indexTableName); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { initTablesAndAddExtraRowsToIndex(conn, schemaName, dataTableName, indexTableName, NROWS); IndexToolIT.runIndexTool(false, false, schemaName, dataTableName, indexTableName, null, 0, IndexVerifyType.ONLY, "-fi"); Cell cell = IndexToolIT.getErrorMessageFromIndexToolOutputTable(conn, dataTableFullName, indexTableFullName); try { String expectedErrorMsg = IndexRepairRegionScanner.ERROR_MESSAGE_EXTRA_INDEX_ROW; String actualErrorMsg = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); <START> assertTrue(expectedErrorMsg.equals(actualErrorMsg)); <END> } catch(Exception ex) { Assert.fail("Fail to parsing the error message from IndexToolOutputTable"); } } }</code><technical_language>I recommend a contains equals here. enhance error messages</technical_language>

Target:
public void testPITRow() throws Exception { final int NROWS = 1; String schemaName = generateUniqueName(); String dataTableName = generateUniqueName(); String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName); String indexTableName = generateUniqueName(); String indexTableFullName = SchemaUtil.getTableName(schemaName, indexTableName); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { initTablesAndAddExtraRowsToIndex(conn, schemaName, dataTableName, indexTableName, NROWS); IndexToolIT.runIndexTool(false, false, schemaName, dataTableName, indexTableName, null, 0, IndexVerifyType.ONLY, "-fi"); Cell cell = IndexToolIT.getErrorMessageFromIndexToolOutputTable(conn, dataTableFullName, indexTableFullName); String expectedErrorMsg = IndexRepairRegionScanner.ERROR_MESSAGE_EXTRA_INDEX_ROW; String actualErrorMsg = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); assertTrue(actualErrorMsg.contains(expectedErrorMsg)); } }
Source:
<code>public static Object convertField(String type, String fieldValue) { if (fieldValue == null) { return null; } try { if (type.equals(SupportedFieldType.BOOLEAN.toString())) { return Boolean.parseBoolean(fieldValue); } else if (type.equals(SupportedFieldType.DATE.toString())) { <START> try { <END> return FormatUtil.getTimeZoneFormat().parse(fieldValue); } catch (ParseException e) { return FormatUtil.getDateFormat().parse(fieldValue); } } else if (type.equals(SupportedFieldType.INTEGER.toString())) { return Integer.parseInt(fieldValue); } else if (type.equals(SupportedFieldType.MONEY.toString()) || type.equals(SupportedFieldType.DECIMAL.toString())) { return new BigDecimal(fieldValue); } } catch (ParseException e) { throw new RuntimeException(e); } throw new IllegalArgumentException("Unrecognized type(" + type + ") for map field conversion."); }</code><technical_language>Change a length check instead of a ... getTimeZoneFormat().length() instead of relying exception. Need try remove recreate add length check</technical_language>

Target:
public static Object convertField(String type, String fieldValue) { if (fieldValue == null) { return null; } try { if (type.equals(SupportedFieldType.BOOLEAN.toString())) { return Boolean.parseBoolean(fieldValue); } else if (type.equals(SupportedFieldType.DATE.toString())) { if (fieldValue.length() == 19) { return FormatUtil.getDateFormat().parse(fieldValue); } else { return FormatUtil.getTimeZoneFormat().parse(fieldValue); } } else if (type.equals(SupportedFieldType.INTEGER.toString())) { return Integer.parseInt(fieldValue); } else if (type.equals(SupportedFieldType.MONEY.toString()) || type.equals(SupportedFieldType.DECIMAL.toString())) { return new BigDecimal(fieldValue); } } catch (ParseException e) { throw new RuntimeException(e); } throw new IllegalArgumentException("Unrecognized type(" + type + ") for map field conversion."); }
Source:
<code>public boolean addNewUser(AccountRequest request) throws QuadrigaStorageException, UsernameExistsException { QuadrigaUserDTO userDTO = usermanagerDAO.getUserDTO(request.getUsername()); if (userDTO != null) throw new UsernameExistsException("Username already in use."); QuadrigaUserRequestsDTO userRequest = usermanagerDAO.getUserRequestDTO(request.getUsername()); if (userRequest != null) throw new UsernameExistsException("Username already in use."); String plainPassword = request.getPassword(); boolean success = false; if(request.isSocialSignIn()){ success = usermanagerDAO.addNewUserAccountRequest(request.getUsername(), null, request.getName(), request.getEmail(), request.getProvider(), request.getUserIdOfProvider()); } else{ success = usermanagerDAO.addNewUserAccountRequest(request.getUsername(), encryptPassword(plainPassword), request.getName(), request.getEmail(), null, null); <START> } <END> if (success) { IQuadrigaRole role = rolemanager.getQuadrigaRoleById(IQuadrigaRoleManager.MAIN_ROLES, RoleNames.ROLE_QUADRIGA_ADMIN); List<QuadrigaUserDTO> admins = usermanagerDAO.getUserDTOList(role.getDBid()); for (QuadrigaUserDTO admin : admins) { try { emailManager.sendAccountCreatedEmail(request.getName(), request.getUsername(), admin.getFullname(), admin.getEmail()); } catch (QuadrigaNotificationException e) { logger.error("Email to " + admin.getUsername() + " could not be sent.", e); } } } return success; }</code><technical_language>please reread style guide</technical_language>

Target:
public void addNewUser(AccountRequest request) throws QuadrigaStorageException, UsernameExistsException, UserRequestExistsException{ if (usermanagerDAO.getUserDTO(request.getUsername()) != null){ throw new UsernameExistsException("Username already in use."); } QuadrigaUserRequestsDTO userRequest = usermanagerDAO.getUserRequestDTO(request.getUsername()); if (userRequest != null){ throw new UserRequestExistsException("User request already exists."); } String password = (request.getPassword() != null) ? encryptPassword(request.getPassword()) : null ; boolean success = usermanagerDAO.addNewUserAccountRequest(request.getUsername(), password, request.getName(), request.getEmail(), request.getProvider() , request.getUserIdOfProvider()); if (success) { IQuadrigaRole role = rolemanager.getQuadrigaRoleById(IQuadrigaRoleManager.MAIN_ROLES, RoleNames.ROLE_QUADRIGA_ADMIN); List<QuadrigaUserDTO> admins = usermanagerDAO.getUserDTOList(role.getDBid()); for (QuadrigaUserDTO admin : admins) { try { emailManager.sendAccountCreatedEmail(request.getName(), request.getUsername(), admin.getFullname(), admin.getEmail()); } catch (QuadrigaNotificationException e) { logger.error("Email to " + admin.getUsername() + " could not be sent.", e); } } } }
Source:
<code>private void sendQualityImpl(XMLStreamWriter serializer) throws XMLStreamException { if ( qualityModified == false ) return; serializer.writeStartElement("rapi", "quality", REST_API_NS); if(String.valueOf(getQuality()) != null) <START> serializer.writeCharacters(String.valueOf(getQuality())); <END> serializer.writeEndElement(); }</code><technical_language>If quality is int, need check</technical_language>

Target:
private void sendQualityImpl(XMLStreamWriter serializer) throws XMLStreamException { if ( qualityModified == false ) return; serializer.writeStartElement("rapi", "quality", REST_API_NS); serializer.writeCharacters(String.valueOf(getQuality())); serializer.writeEndElement(); }
Source:
<code>private void doSetChannelMappings(Map<String, String> newChannelMappings) { Map<String, String> oldChannelMappings = new HashMap<String, String>(this.channelMappings); <START> synchronized (this.channelMappings) { <END> this.channelMappings.clear(); this.channelMappings.putAll(newChannelMappings); } if (logger.isDebugEnabled()) { logger.debug("Channel mappings: " + oldChannelMappings + " replaced with: " + newChannelMappings); } }</code><technical_language>While getChannelMappings() is accessed RouterMetrics, I needs get a copy a hard reference - map change while caller a reference</technical_language>

Target:
private void doSetChannelMappings(Map<String, String> newChannelMappings) { Map<String, String> oldChannelMappings = this.channelMappings; this.channelMappings = newChannelMappings; if (logger.isDebugEnabled()) { logger.debug("Channel mappings: " + oldChannelMappings + " replaced with: " + newChannelMappings); } }
Source:
<code>public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); String entity = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); List<StudentAttributes> students; if (userInfo.isInstructor && entity.equals(Const.EntityType.INSTRUCTOR)) { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } else if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { throw new InvalidHttpParameterException("Invalid entity type for search"); } List<StudentData> studentDataList = new ArrayList<>(); for (StudentAttributes s : students) { StudentData studentData = new StudentData(s); if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { studentData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(s.getKey()), getInstituteFromCourseId(s.getCourse()), s.getGoogleId()); } else { <START> studentData.hideInformationForSearch(); <END> } studentData.hideLastName(); studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); return new JsonResult(studentsData); }</code><technical_language>this is necessary. This is hiding anything</technical_language>

Target:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); String entity = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); List<StudentAttributes> students; if (userInfo.isInstructor && entity.equals(Const.EntityType.INSTRUCTOR)) { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } else if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { throw new InvalidHttpParameterException("Invalid entity type for search"); } List<StudentData> studentDataList = new ArrayList<>(); for (StudentAttributes s : students) { StudentData studentData = new StudentData(s); if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { studentData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(s.getKey()), getInstituteFromCourseId(s.getCourse()), s.getGoogleId() ); } studentData.hideLastName(); studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); return new JsonResult(studentsData); }
Source:
<code>Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } <START> if (!checkKeyPermissions(this.key.get().getKeyOps(), KeyOperation.WRAP_KEY)) { <END> return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed " + "for key with id %s", this.key.get().getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key.get()); }); }</code><technical_language>asserting UNWRAP_KEY permission</technical_language>

Target:
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed " + "for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); }
Source:
<code>private ArgumentParseException createValueError() { <START> return createError(t("Short setFlags that are not at the end of a group cannot have a value.")); <END> }</code><technical_language>flags, setFlags</technical_language>

Target:
private ArgumentParseException createValueError() { return createError(t("Short flags that are not at the end of a group cannot have a value.")); }
Source:
<code>public void deleteSelectedApi(String[] apiNames) throws APIException{ final Lock lock = getLock(); try { lock.lock(); CAppArtifactDataService cAppArtifactDataService = ConfigHolder.getInstance(). getcAppArtifactDataService(); for (String apiName :apiNames ) { assertNameNotEmpty(apiName); apiName = apiName.trim(); <START> if (!cAppArtifactDataService.isArtifactDeployedFromCApp(getTenantId(), ServiceBusConstants.API_TYPE + File.separator + apiName)) { <END> if (log.isDebugEnabled()) { log.debug("Deleting API : " + apiName + " from the configuration"); } SynapseConfiguration synapseConfiguration = getSynapseConfiguration(); API api = synapseConfiguration.getAPI(apiName); api.destroy(); synapseConfiguration.removeAPI(apiName); MediationPersistenceManager pm = getMediationPersistenceManager(); String fileName = api.getFileName(); pm.deleteItem(apiName, fileName, ServiceBusConstants.ITEM_TYPE_REST_API); if (log.isDebugEnabled()) { log.debug("Api : " + apiName + " removed from the configuration"); } } } } finally { lock.unlock(); } }</code><technical_language>formatted correctly</technical_language>

Target:
public void deleteSelectedApi(String[] apiNames) throws APIException { final Lock lock = getLock(); try { lock.lock(); CAppArtifactDataService cAppArtifactDataService = ConfigHolder.getInstance().getcAppArtifactDataService(); for (String apiName : apiNames) { assertNameNotEmpty(apiName); apiName = apiName.trim(); if (!cAppArtifactDataService.isArtifactDeployedFromCApp(getTenantId(), getArtifactName(artifactType, apiName))) { if (log.isDebugEnabled()) { log.debug("Deleting API : " + apiName + " from the configuration"); } SynapseConfiguration synapseConfiguration = getSynapseConfiguration(); API api = synapseConfiguration.getAPI(apiName); api.destroy(); synapseConfiguration.removeAPI(apiName); MediationPersistenceManager pm = getMediationPersistenceManager(); String fileName = api.getFileName(); pm.deleteItem(apiName, fileName, ServiceBusConstants.ITEM_TYPE_REST_API); if (log.isDebugEnabled()) { log.debug("Api : " + apiName + " removed from the configuration"); } } } } finally { lock.unlock(); } }
Source:
<code>private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; try { Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); return EnvInjectPlugin.canViewInjectedVars(run); } finally { if (initialContext != null) { SecurityContextHolder.setContext(initialContext); } <START> } <END> }</code><technical_language>BTW written more concisely effectively final variable: java Authentication auth = user.impersonate(); SecurityContext initialContext = ACL.impersonate(auth); try { return EnvInjectPlugin.canViewInjectedVars(run); } finally { SecurityContextHolder.setContext(initialContext); } (There newer overloads closures, suitable for Java 8 lambdas.)</technical_language>

Target:
private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); try { return EnvInjectPlugin.canViewInjectedVars(run); } finally { SecurityContextHolder.setContext(initialContext); } }
Source:
<code>protected int run() throws Exception { if (doImport) { store.checkPermission(CredentialsProvider.UPDATE); List<DomainCredentials> replacement = (List<DomainCredentials>) Items.XSTREAM.unmarshal(safeXmlStreamReader(stdin)); for (DomainCredentials domain : replacement) { for (Credentials credentials : domain.getCredentials()) { <START> store.addDomain(domain.getDomain(), credentials); <END> } } return 0; } else { store.checkPermission(CredentialsProvider.VIEW); List<DomainCredentials> existing = new ArrayList<>(); List<Domain> domains = store.getDomains(); for (Domain domain : domains) { existing.add(new DomainCredentials(domain, store.getCredentials(domain))); } CredentialsStoreAction.SECRETS_REDACTED.toXML(existing, new OutputStreamWriter(stdout, "UTF-8")); return 0; } }</code><technical_language>conflicts? if a credential is defined I hope import overwrite existing (as loose a secret) error (or skip warning)</technical_language>

Target:
protected int run() throws Exception { store.checkPermission(CredentialsProvider.UPDATE); List<DomainCredentials> existing = new ArrayList<>(); List<Domain> domains = store.getDomains(); for (Domain domain : domains) { existing.add(new DomainCredentials(domain, store.getCredentials(domain))); } CredentialsStoreAction.SECRETS_REDACTED.toXML(existing, new OutputStreamWriter(stdout, "UTF-8")); return 0; }
Source:
<code>public void stop(String handle, String reason) { <START> <END> Map<String, String> params = new HashMap<String, String>(); addParam(params, "reason", reason); this.transport.stop(handle, params); }</code><technical_language>rm</technical_language>

Target:
public void stop(String handle, String reason) { Map<String, String> params = buildParams("reason", reason); this.transport.stop(handle, params); }
Source:
<code>private List<String> resultToList(TupleQueryResult result, String valueBinding, Function<String, String> transform) { ImmutableList.Builder<String> values = ImmutableList.builder(); try { while (result.hasNext()) { BindingSet bindings = result.next(); Binding value = bindings.getBinding(valueBinding); if (value == null) { continue; } String strValue = value.getValue().stringValue(); if <START> (transform != null) { <END> strValue = transform.apply(strValue); } values.add(strValue); } } catch (QueryEvaluationException e) { throw new FatalException("Can't load results: " + e, e); } return values.build(); }</code><technical_language>a nullable parameter, Function.identity(). more this is null</technical_language>

Target:
private List<String> resultToList(TupleQueryResult result, String valueBinding, Function<String, String> transform) { ImmutableList.Builder<String> values = ImmutableList.builder(); try { while (result.hasNext()) { BindingSet bindings = result.next(); Binding value = bindings.getBinding(valueBinding); if (value == null) { continue; } values.add(transform.apply(value.getValue().stringValue())); } } catch (QueryEvaluationException e) { throw new FatalException("Can't load results: " + e, e); } return values.build(); }
Source:
<code>private List<VM> checkVmsStatusChanged() { List<VM> running = new ArrayList<VM>(); if (!_vdsManager.getRefreshStatistics()) { List<VmDynamic> tempRunningList = new ArrayList<VmDynamic>(); for (Entry<VmDynamic, VmStatistics> runningVm : _runningVms.values()) { tempRunningList.add(runningVm.getKey()); } for (VmDynamic runningVm : tempRunningList) { VM vmToUpdate = null; vmToUpdate = _vmDict.get(runningVm.getId()); if (vmToUpdate == null || (vmToUpdate.getstatus() != runningVm.getstatus() && !(vmToUpdate.getstatus() == VMStatus.SavingState && runningVm .getstatus() == VMStatus.Up))) { GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters> command = new GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters>(new GetVmStatsVDSCommandParameters( _vds, runningVm.getId())); command.Execute(); if (command.getVDSReturnValue().getSucceeded()) { _runningVms.put(runningVm.getId(), (Entry<VmDynamic, VmStatistics>) command.getReturnValue()); } else { _runningVms.remove(runningVm.getId()); } } else { running.add(vmToUpdate); _runningVms.remove(vmToUpdate.getId()); } } } <START> for (VM vm : running) { <END> ResourceManager.getInstance().updateQuota(vm); } return running; }</code><technical_language>right list. Please verify list is needed. Also, please add existing loop, avoid new loops</technical_language>

Target:
private List<VM> checkVmsStatusChanged() { List<VM> running = new ArrayList<VM>(); if (!_vdsManager.getRefreshStatistics()) { List<VmDynamic> tempRunningList = new ArrayList<VmDynamic>(); for (Entry<VmDynamic, VmStatistics> runningVm : _runningVms.values()) { tempRunningList.add(runningVm.getKey()); } for (VmDynamic runningVm : tempRunningList) { VM vmToUpdate = null; vmToUpdate = _vmDict.get(runningVm.getId()); if (vmToUpdate == null || (vmToUpdate.getstatus() != runningVm.getstatus() && !(vmToUpdate.getstatus() == VMStatus.SavingState && runningVm .getstatus() == VMStatus.Up))) { GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters> command = new GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters>(new GetVmStatsVDSCommandParameters( _vds, runningVm.getId())); command.Execute(); if (command.getVDSReturnValue().getSucceeded()) { _runningVms.put(runningVm.getId(), (Entry<VmDynamic, VmStatistics>) command.getReturnValue()); } else { _runningVms.remove(runningVm.getId()); } } else { running.add(vmToUpdate); _runningVms.remove(vmToUpdate.getId()); } } } return running; }
Source:
<code><START> public BulkImportOptions setTempDir(Path tempDir) { <END> this.tempDir = tempDir; return this; }</code><technical_language>null check</technical_language>

Target:
public BulkImportOptions setTempDir(Path tempDir) { Objects.requireNonNull(tempDir); this.tempDir = tempDir; return this; }
Source:
<code>protected void delete(Context context, UUID id) throws AuthorizeException { Collection collection = null; try { collection = cs.find(context, id); if (collection == null) { throw new ResourceNotFoundException( CollectionRest.CATEGORY + "." + CollectionRest.NAME + " with id: " + id + " not found"); } } catch (SQLException e) { <START> throw new RuntimeException(e.getMessage(), e); <END> } try { cs.delete(context, collection); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }</code><technical_language>More useful error message please</technical_language>

Target:
protected void delete(Context context, UUID id) throws AuthorizeException { Collection collection = null; try { collection = cs.find(context, id); if (collection == null) { throw new ResourceNotFoundException( CollectionRest.CATEGORY + "." + CollectionRest.NAME + " with id: " + id + " not found"); } } catch (SQLException e) { throw new RuntimeException("Unable to find Collection with id = " + id, e); } try { cs.delete(context, collection); } catch (SQLException e) { throw new RuntimeException("Unable to delete Collection with id = " + id, e); } catch (IOException e) { throw new RuntimeException("Unable to delete collection because the logo couldn't be deleted", e); } }
Source:
<code>public void recreate() throws BuildException { try { if (fileSets.isEmpty()) { handleError( "File set identifying link file(s) required for action recreate"); return; } final Properties links = loadLinks(fileSets); for (final String lnk : links.stringPropertyNames()) { final String res = links.getProperty(lnk); try { if (Files.isSymbolicLink(Paths.get(lnk)) && Paths.get(lnk).toFile().getCanonicalPath().equals(Paths.get(res).toFile().getCanonicalPath())) { continue; } } catch (IOException e) { if (failonerror) { throw new BuildException("Failed to recreate symlink " + lnk + " to target " + res, e); } log("Failed to recreate symlink " + lnk + " to target " + res, Project.MSG_INFO); continue; } this.doLink(res, lnk); <START> } <END> } finally { setDefaults(); } }</code><technical_language>I this of try block</technical_language>

Target:
public void recreate() throws BuildException { try { if (fileSets.isEmpty()) { handleError( "File set identifying link file(s) required for action recreate"); return; } final Properties links = loadLinks(fileSets); for (final String lnk : links.stringPropertyNames()) { final String res = links.getProperty(lnk); try { if (Files.isSymbolicLink(Paths.get(lnk)) && new File(lnk).getCanonicalPath().equals(new File(res).getCanonicalPath())) { continue; } } catch (IOException e) { final String errMessage = "Failed to check if path " + lnk + " is a symbolic link, linking to " + res; if (failonerror) { throw new BuildException(errMessage, e); } log(errMessage, Project.MSG_INFO); continue; } this.doLink(res, lnk); } } finally { setDefaults(); } }
Source:
<code>public String getSuggestedSchema(String separator) { <START> String s = ExternalTableUtils.getSuggestedSchema(schema, partition_schema, separator); <END> if(foundFiles != null && foundFiles.length > 0) s = s + separator + " STORED AS " + ExternalTableUtils.getExternalTableTypeFromPath(foundFiles[0]); if( rootPath != null ) s = s + " LOCATION '" + rootPath + "';"; return s; }</code><technical_language>I a StringBuilder for this (probably IntelliJ automatically do for you)</technical_language>

Target:
public String getSuggestedSchema(String separator) { StringBuilder sb = new StringBuilder(); ExternalTableUtils.getSuggestedSchema(sb, schema, partition_schema, separator); if(foundFiles != null && foundFiles.length > 0) { sb.append(separator); sb.append(" STORED AS "); sb.append(ExternalTableUtils.getExternalTableTypeFromPath(foundFiles[0])); } if( rootPath != null ) { sb.append(" LOCATION '"); sb.append(rootPath); sb.append("';"); } return sb.toString(); }
Source:
<code>public void removeAllApps() throws Exception { ApplicationListDTO getAllAppResponse = restAPIStore.getAllApps(); <START> List<ApplicationInfoDTO> array = getAllAppResponse.getList(); <END> for (int app = 0; array.size() > app; app++) { restAPIStore.deleteApplication(array.get(app).getApplicationId()); } }</code><technical_language>rename this applicationDTOList similar</technical_language>

Target:
public void removeAllApps() throws Exception { ApplicationListDTO getAllAppResponse = restAPIStore.getAllApps(); List<ApplicationInfoDTO> applicationInfoDTOs = getAllAppResponse.getList(); for (ApplicationInfoDTO applicationInfoDTO : applicationInfoDTOs) { restAPIStore.deleteApplication(applicationInfoDTO.getApplicationId()); } }
Source:
<code>protected Events executeStateAction(final ExecutionContext executionContext) { log.info("Cleaning up job..."); final String claimedJobId = executionContext.getClaimedJobId(); final JobStatus finalJobStatus = executionContext.getFinalJobStatus(); final ExecutionContext.KillProvenance killProvenance = executionContext.getJobKillProvenance(); final JobStatus lastJobStatus = executionContext.getCurrentJobStatus(); if (lastJobStatus != null && claimedJobId != null) { if (finalJobStatus == null) { if (killProvenance != null) { try { agentJobService.changeJobStatus( claimedJobId, lastJobStatus, JobStatus.KILLED, "Terminated by user via " + killProvenance.name() ); } catch (final ChangeJobStatusException e) { throw new RuntimeException("Failed to update server status", e); } executionContext.setFinalJobStatus(JobStatus.KILLED); } else { throw new IllegalStateException( "Reached cleanup state and finalJobState is null. Last job state: " + lastJobStatus ); } } else { log.debug("Job final status already updated server-side: {}", finalJobStatus); } } else { <START> log.debug("Job never claimed an ID, skipping server-side status update"); <END> } final List<StateAction> cleanupActions = executionContext.getCleanupActions(); for (final StateAction cleanupAction : cleanupActions) { if (cleanupAction == this) { continue; } try { cleanupAction.cleanup(); } catch (final Exception e) { log.warn( "Exception during action cleanup", cleanupAction.getClass().getSimpleName(), e ); } } return Events.CLEANUP_JOB_COMPLETE; }</code><technical_language>This happen if lastJobStatus == null. log statement represent</technical_language>

Target:
protected Events executeStateAction(final ExecutionContext executionContext) { log.info("Cleaning up job..."); final String claimedJobId = executionContext.getClaimedJobId(); final JobStatus finalJobStatus = executionContext.getFinalJobStatus(); final ExecutionContext.KillSource killSource = executionContext.getJobKillSource(); final JobStatus lastJobStatus = executionContext.getCurrentJobStatus(); if (lastJobStatus != null && claimedJobId != null) { if (finalJobStatus == null) { if (killSource != null) { try { agentJobService.changeJobStatus( claimedJobId, lastJobStatus, JobStatus.KILLED, "Terminated by user via " + killSource.name() ); } catch (final ChangeJobStatusException e) { throw new RuntimeException("Failed to update server status", e); } executionContext.setFinalJobStatus(JobStatus.KILLED); } else { throw new IllegalStateException( "Reached cleanup state and finalJobState is null. Last job state: " + lastJobStatus ); } } else { log.debug("Job final status already updated server-side: {}", finalJobStatus); } } else { log.debug("Job never claimed an ID, skipping server-side status update"); } final List<StateAction> cleanupActions = executionContext.getCleanupActions(); for (final StateAction cleanupAction : cleanupActions) { if (cleanupAction == this) { continue; } try { cleanupAction.cleanup(); } catch (final Exception e) { log.warn( "Exception during action cleanup", cleanupAction.getClass().getSimpleName(), e ); } } return Events.CLEANUP_JOB_COMPLETE; }
Source:
<code>public Collection<PackFile> repack(ProgressMonitor pm) throws IOException { PackConfig packConfig = new PackConfig(repo); if (packConfig.getIndexVersion() != 2) throw new IllegalStateException("Only index version 2"); Map<String, Ref> refsBefore = repo.getAllRefs(); HashSet<ObjectId> allHeads = new HashSet<ObjectId>(); HashSet<ObjectId> nonHeads = new HashSet<ObjectId>(); HashSet<ObjectId> tagTargets = new HashSet<ObjectId>(); HashSet<ObjectId> indexObjects = listNonHEADIndexObjects(); for (Ref ref : refsBefore.values()) { if (ref.isSymbolic() || ref.getObjectId() == null) continue; if (isHead(ref)) allHeads.add(ref.getObjectId()); else nonHeads.add(ref.getObjectId()); if (ref.getPeeledObjectId() != null) tagTargets.add(ref.getPeeledObjectId()); } tagTargets.addAll(allHeads); nonHeads.addAll(indexObjects); <START> <END> List<PackFile> ret = new ArrayList<PackFile>(2); ret.add(packHeads(pm, allHeads)); if (!nonHeads.isEmpty()) ret.add(packRest(pm, nonHeads, allHeads)); return ret; }</code><technical_language>Do need care of id's in FETCHHEAD</technical_language>

Target:
public Collection<PackFile> repack(ProgressMonitor pm) throws IOException { PackConfig packConfig = new PackConfig(repo); if (packConfig.getIndexVersion() != 2) throw new IllegalStateException("Only index version 2"); Map<String, Ref> refsBefore = repo.getAllRefs(); for (Ref ref : repo.getRefDatabase().getAdditionalRefs()) refsBefore.put(ref.getName(), ref); HashSet<ObjectId> allHeads = new HashSet<ObjectId>(); HashSet<ObjectId> nonHeads = new HashSet<ObjectId>(); HashSet<ObjectId> tagTargets = new HashSet<ObjectId>(); HashSet<ObjectId> indexObjects = listNonHEADIndexObjects(); for (Ref ref : refsBefore.values()) { if (ref.isSymbolic() || ref.getObjectId() == null) continue; if (isHead(ref)) allHeads.add(ref.getObjectId()); else nonHeads.add(ref.getObjectId()); if (ref.getPeeledObjectId() != null) tagTargets.add(ref.getPeeledObjectId()); } tagTargets.addAll(allHeads); nonHeads.addAll(indexObjects); List<PackFile> ret = new ArrayList<PackFile>(2); ret.add(packHeads(pm, allHeads)); if (!nonHeads.isEmpty()) { PackFile rest = packRest(pm, nonHeads, allHeads); if (rest!=null) ret.add(rest); } return ret; }
Source:
<code>private void loadPageFromCache() { app.getPageCache() .get(model.getTitleOriginal(), currentSequenceNum, new PageCache.CacheGetListener() { @Override public void onGetComplete(Page page, int sequence) { if (sequence != currentSequenceNum) { return; } if (page != null) { Log.d(TAG, "Using page from cache: " + model.getTitleOriginal().getDisplayText()); Log.v(TAG, "ETag of cached page: " + page.getPageProperties().getEtag()); model.setPage(page); model.setTitle(page.getTitle()); final HistoryEntry curEntry = model.getCurEntry(); model.setCurEntry( new HistoryEntry(model.getTitle(), curEntry.getSource())); updateThumbnail(PageImage.PERSISTENCE_HELPER.getImageUrlForTitle(app, model.getTitle())); new SaveHistoryTask(model.getCurEntry(), app).execute(); cacheOnComplete = false; state = STATE_COMPLETE_FETCH; setState(state); performActionForState(state); if (fragment.isAdded()) { fragment.onPageLoadComplete(); } } else { <START> Log.d(TAG, "Could not page in cache, loading from network"); <END> loadPageFromNetwork(); } } @Override public void onGetError(Throwable e, int sequence) { Log.e(TAG, "Failed to get page from cache.", e); if (sequence != currentSequenceNum) { return; } loadPageFromNetwork(); } }); }</code><technical_language>Incomplete sentence. "Page in cache, loading network"</technical_language>

Target:
private void loadPageFromCache() { app.getPageCache() .get(model.getTitleOriginal(), currentSequenceNum, new PageCache.CacheGetListener() { @Override public void onGetComplete(Page page, int sequence) { if (sequence != currentSequenceNum) { return; } if (page != null) { Log.d(TAG, "Using page from cache: " + model.getTitleOriginal().getDisplayText()); Log.v(TAG, "ETag of cached page: " + page.getPageProperties().getEtag()); model.setPage(page); model.setTitle(page.getTitle()); final HistoryEntry curEntry = model.getCurEntry(); model.setCurEntry( new HistoryEntry(model.getTitle(), curEntry.getSource())); updateThumbnail(PageImage.PERSISTENCE_HELPER.getImageUrlForTitle(app, model.getTitle())); new SaveHistoryTask(model.getCurEntry(), app).execute(); cacheOnComplete = false; state = STATE_COMPLETE_FETCH; setState(state); performActionForState(state); if (fragment.isAdded()) { fragment.onPageLoadComplete(); } } else { Log.d(TAG, "Page not in cache, loading from network"); loadPageFromNetwork(); } } @Override public void onGetError(Throwable e, int sequence) { Log.e(TAG, "Failed to get page from cache.", e); if (sequence != currentSequenceNum) { return; } loadPageFromNetwork(); } }); }