auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void canNotMatchBinaryBody() { final byte[] body = new byte[]{0}; final MkAnswer query = Mockito.mock(MkAnswer.class); Mockito.doReturn(body).when(query).content(); final byte[] mismatch = new byte[]{1}; MatcherAssert.assertThat( query, Matchers.not( MkAnswerMatchers.hasContent( Matchers.is(mismatch) ) ) ); }

Target:
public void canNotMatchBinaryBody() { final MkAnswer query = Mockito.mock(MkAnswer.class); Mockito.doReturn(new byte[]{0}).when(query).content(); MatcherAssert.assertThat( query, Matchers.not( MkAnswerMatchers.hasContent( Matchers.is(new byte[]{1}) ) ) ); }
Source:
public WsManAssetAdapterConfig getInstance() { m_config.getReadLock().lock(); try { return m_config; } finally { m_config.getReadLock().unlock(); } }

Target:
public WsManAssetAdapterConfig getInstance() { return m_config; }
Source:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName(prependIfDeerInstance("Title Search Generator")); if (Strings.isNullOrEmpty(content.getTitle())) { desc.appendText("subject has no title"); return DefaultScoredCandidates.<T>fromSource(name).build(); } Iterable<? extends T> candidates = searchForCandidates(content, desc); return titleScorer.scoreCandidates(content, candidates, desc, generatorComponent); }

Target:
public ScoredCandidates<T> generate( T content, ResultDescription desc, EquivToTelescopeResult equivToTelescopeResult ) { EquivToTelescopeComponent generatorComponent = EquivToTelescopeComponent.create(); generatorComponent.setComponentName(name); if (Strings.isNullOrEmpty(content.getTitle())) { desc.appendText("subject has no title"); return DefaultScoredCandidates.<T>fromSource(name).build(); } Iterable<? extends T> candidates = searchForCandidates(content, desc); return titleScorer.scoreCandidates(content, candidates, desc, generatorComponent); }
Source:
public void writePoint( CoordinateReferenceSystem crs, double[] coordinate ) throws RuntimeException { append( "{geometry: {type: \"Point\", coordinates: [" ); for ( int i = 0; i < coordinate.length; i++ ) { append( Double.toString( coordinate[i] ) ); if ( i != coordinate.length - 1 ) { append( ", " ); } } append( "], crs: {type: link, properties: {href: \"" ); append( crs.href ); append( "\", code: " ); append( Integer.toString( crs.code ) ); append( "}}}}" ); }

Target:
public void writePoint( CoordinateReferenceSystem crs, double[] coordinate ) throws RuntimeException { append( "{geometry: {type: \"Point\", coordinates: " ); append( Arrays.toString(coordinate) ); append( ", crs: {type: link, properties: {href: \"" ); append( crs.getHref() ); append( "\", code: " ); append( Integer.toString( crs.getCode() ) ); append( "}}}}" ); }
Source:
public void deleteById() throws Exception { Object id1 = roamingRepository.create(new NewRoamingGroup("name1", "description1", RoamingGroupType.REGIONAL)); Object id2 = roamingRepository.create(new NewRoamingGroup("name2", "description2", RoamingGroupType.REGIONAL)); roamingRepository.delete(new ID(id1)); List<RoamingGroup> got = roamingRepository.findAll(); List<RoamingGroup> want = Lists.newArrayList(new RoamingGroup(new ID(id2), "name2", "description2", RoamingGroupType.REGIONAL, Lists.<Operator>newArrayList())); assertThat(got, deepEquals(want)); }

Target:
public void deleteById() throws Exception { Object id = roamingRepository.create(new NewRoamingGroup("name", "description", RoamingGroupType.REGIONAL)); roamingRepository.delete(new ID(id)); List<RoamingGroup> found = roamingRepository.findAll(); assertTrue(found.isEmpty()); }
Source:
public void setOp(boolean value) { throw new UnsupportedOperationException("Cannot change operator status of server console"); }

Target:
public void setOp(boolean value) { throw new UnsupportedOperationException("Cannot change operator status of RCon command sender"); }
Source:
public void validate(DrugOrder order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "dosingInstructions", "DrugOrder.error.dosingInstructionsIsNullForDosingTypeOther"); }

Target:
public void validate(DrugOrder order, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "dosingInstructions", "DrugOrder.error.dosingInstructionsIsNullForDosingTypeFreeText"); }
Source:
public int readData(byte[] buffer, int numBytes) throws IOException { int readBytes = 0; if (getInputStream() != null) readBytes = getInputStream().read(buffer, 0, numBytes); return readBytes; }

Target:
public int readData(byte[] buffer, int numBytes) throws IOException { if (buffer == null) throw new NullPointerException("Buffer cannot be null."); if (numBytes < 1) throw new IllegalArgumentException("Bytes to read cannot be less than 1."); int readBytes = 0; if (getInputStream() != null) readBytes = getInputStream().read(buffer, 0, numBytes); return readBytes; }
Source:
public static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph) { return StreamSupport.stream(graph.nodes().spliterator(), false) .filter(n -> n.getContent().getDefinition() instanceof DMNDiagram) .findFirst() .orElseThrow(() -> new UnsupportedOperationException("TODO")); }

Target:
public static Node<?, ?> findDMNDiagramRoot(final Graph<?, Node<View, ?>> graph) { return StreamSupport.stream(graph.nodes().spliterator(), false) .filter(n -> n.getContent().getDefinition() instanceof DMNDiagram) .findFirst() .orElseThrow(() -> new IllegalStateException("DMNDiagram root not found.")); }
Source:
if (migrationStatus.status() == MigrationStatus.Status.COMPLETE) { File databasePath = getDatabasePath("downloads.db"); if (databasePath.exists()) { SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(databasePath.getAbsolutePath(), null, 0); SqlDatabaseWrapper database = new SqlDatabaseWrapper(sqLiteDatabase); database.deleteDatabase(); } liteDownloadManagerCommands.submitAllStoredDownloads(() -> Log.d(TAG, "Migration completed, submitting all downloads")); }

Target:
if (migrationStatus.status() == MigrationStatus.Status.COMPLETE) { File databasePath = getDatabasePath(V1_DB_PATH); if (databasePath.exists()) { SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(databasePath.getAbsolutePath(), null, 0); SqlDatabaseWrapper database = new SqlDatabaseWrapper(sqLiteDatabase); database.deleteDatabase(); } liteDownloadManagerCommands.submitAllStoredDownloads(() -> Log.d(TAG, "Migration completed, submitting all downloads")); }
Source:
private MapSqlParameterSource getDbUserParameterSource(DbUser user) { return getCustomMapSqlParameterSource() .addValue("department", user.getDepartment()) .addValue("domain", user.getDomain()) .addValue("email", user.getEmail()) .addValue("name", user.getFirstName()) .addValue("note", user.getNote()) .addValue("surname", user.getLastName()) .addValue("user_id", user.getId()) .addValue("username", user.getLoginName()) .addValue("last_admin_check_status", user.isAdmin()) .addValue("external_id", user.getExternalId()) .addValue("namespace", user.getNamespace()) .addValue("options", userOptionsToString(user)); }

Target:
private MapSqlParameterSource getDbUserParameterSource(DbUser user) { return getCustomMapSqlParameterSource() .addValue("department", user.getDepartment()) .addValue("domain", user.getDomain()) .addValue("email", user.getEmail()) .addValue("name", user.getFirstName()) .addValue("note", user.getNote()) .addValue("surname", user.getLastName()) .addValue("user_id", user.getId()) .addValue("username", user.getLoginName()) .addValue("last_admin_check_status", user.isAdmin()) .addValue("external_id", user.getExternalId()) .addValue("namespace", user.getNamespace()) .addValue("options", SerializationFactory.getSerializer().serialize(user.getUserOptions())); }
Source:
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean routed = false; List<PaymentWorksVendorUpdatesDTO> pendingACHUpdates = getPaymentWorksWebService().getPendingAchUpdatesFromPaymentWorks(); LOG.info("execute, number of ACH Updates retrieved: " + pendingACHUpdates.size()); boolean hasErrors = false; routed = getPaymentWorksAchService().processACHUpdates(pendingACHUpdates, hasErrors); if (hasErrors) { throw new RuntimeException("processACHUpdates, there was at least one error processing ACH Updates."); } LOG.debug("execute, were all the changes routed: " + routed); return routed; }

Target:
public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean routed = false; List<PaymentWorksVendorUpdatesDTO> pendingACHUpdates = getPaymentWorksWebService().getPendingAchUpdatesFromPaymentWorks(); LOG.info("execute, number of ACH Updates retrieved: " + pendingACHUpdates.size()); PaymentWorksVendorUpdateResults resultsDTO = new PaymentWorksVendorUpdateResults(); routed = getPaymentWorksAchService().processACHUpdates(pendingACHUpdates, resultsDTO); if (resultsDTO.isHasErrors()) { throw new RuntimeException("processACHUpdates, there was at least one error processing ACH Updates."); } LOG.debug("execute, were all the changes routed: " + routed); return routed; }
Source:
public boolean isHoliday(LocalDate dateToCheck, HolidayType holidayType, ExternalIdBundle regionOrExchangeIds) { Collection<Holiday> holidays = get(holidayType, regionOrExchangeIds); for (Holiday holiday : holidays) { if (holiday.getHolidayDates().contains(dateToCheck)) { return true; } } return false; }

Target:
public boolean isHoliday(LocalDate dateToCheck, HolidayType holidayType, ExternalIdBundle regionOrExchangeIds) { if (isWeekend(dateToCheck)) { return true; } for (ExternalId id : regionOrExchangeIds.getExternalIds()) { if (isHoliday(dateToCheck, holidayType, id)) { return true; } } return false; }
Source:
public void put(Collection<SinkRecord> records) throws CopycatException { String topic; int partition; for (SinkRecord record : records) { topic = record.topic(); partition = record.kafkaPartition(); TopicPartition topicPart = new TopicPartition(topic, partition); if (assignment.contains(topicPart)) { hdfsWriter.writeRecord(topicPart, record); } else { log.warn("Seen record from not assigned TopicPartition {}", record, topicPart); } } }

Target:
public void put(Collection<SinkRecord> records) throws CopycatException { try { hdfsWriter.write(records); } catch (IOException e) { throw new CopycatException(e); } }
Source:
public static synchronized VoltDBInterface instance() { if (singleton == null) { singleton = new RealVoltDB(); } return singleton; }

Target:
public static VoltDBInterface instance() { return singleton; }
Source:
public void set(Position newPosition) throws SQLException { if ( newPosition == null ) return; lastHeartbeatRead = newPosition.getLastHeartbeatRead(); String sql = "INSERT INTO `positions` set " + "server_id = ?, " + "gtid_set = ?, " + "binlog_file = ?, " + "binlog_position = ?, " + "last_heartbeat_read = ?, " + "client_id = ? " + "ON DUPLICATE KEY UPDATE " + "last_heartbeat_read = ?, " + "gtid_set = ?, binlog_file = ?, binlog_position=?"; BinlogPosition binlogPosition = newPosition.getBinlogPosition(); try( Connection c = connectionPool.getConnection() ){ PreparedStatement s = c.prepareStatement(sql); LOGGER.debug("Writing binlog position to " + c.getCatalog() + ".positions: " + newPosition + ", last lastHeartbeatRead read: " + lastHeartbeatRead); s.setLong(1, serverID); s.setString(2, binlogPosition.getGtidSetStr()); s.setString(3, binlogPosition.getFile()); s.setLong(4, binlogPosition.getOffset()); s.setLong(5, lastHeartbeatRead); s.setString(6, clientID); s.setLong(7, lastHeartbeatRead); s.setString(8, binlogPosition.getGtidSetStr()); s.setString(9, binlogPosition.getFile()); s.setLong(10, binlogPosition.getOffset()); s.execute(); } }

Target:
public void set(Position newPosition) throws SQLException { if ( newPosition == null ) return; lastHeartbeatRead = newPosition.getLastHeartbeatRead(); String sql = "INSERT INTO `positions` set " + "server_id = ?, " + "gtid_set = ?, " + "binlog_file = ?, " + "binlog_position = ?, " + "last_heartbeat_read = ?, " + "client_id = ? " + "ON DUPLICATE KEY UPDATE " + "last_heartbeat_read = ?, " + "gtid_set = ?, binlog_file = ?, binlog_position=?"; BinlogPosition binlogPosition = newPosition.getBinlogPosition(); try( Connection c = connectionPool.getConnection() ){ PreparedStatement s = c.prepareStatement(sql); LOGGER.debug("Writing binlog position to " + c.getCatalog() + ".positions: " + newPosition + ", last heartbeat read: " + lastHeartbeatRead); s.setLong(1, serverID); s.setString(2, binlogPosition.getGtidSetStr()); s.setString(3, binlogPosition.getFile()); s.setLong(4, binlogPosition.getOffset()); s.setLong(5, lastHeartbeatRead); s.setString(6, clientID); s.setLong(7, lastHeartbeatRead); s.setString(8, binlogPosition.getGtidSetStr()); s.setString(9, binlogPosition.getFile()); s.setLong(10, binlogPosition.getOffset()); s.execute(); } }
Source:
public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded() || getPageActivity().isSearching()) { return; } MenuItem savePageMenu = menu.findItem(R.id.menu_save_page); if (savePageMenu == null) { return; } if (getTitle() != null) { updateSavePageMenuItem(savePageMenu); } MenuItem shareMenu = menu.findItem(R.id.menu_share_page); MenuItem otherLangMenu = menu.findItem(R.id.menu_other_languages); MenuItem findInPageMenu = menu.findItem(R.id.menu_find_in_page); MenuItem themeChooserMenu = menu.findItem(R.id.menu_themechooser); if (pageLoadStrategy.isLoading()) { savePageMenu.setEnabled(false); shareMenu.setEnabled(false); otherLangMenu.setEnabled(false); findInPageMenu.setEnabled(false); themeChooserMenu.setEnabled(false); } else { shareMenu.setEnabled(true); otherLangMenu.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0); otherLangMenu.setEnabled(true); findInPageMenu.setEnabled(true); themeChooserMenu.setEnabled(true); } }

Target:
public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isAdded() || getPageActivity().isSearching()) { return; } MenuItem savePageItem = menu.findItem(R.id.menu_page_save); if (savePageItem == null) { return; } if (getTitle() != null) { updateSavePageMenuItem(savePageItem); } MenuItem shareItem = menu.findItem(R.id.menu_page_share); MenuItem otherLangItem = menu.findItem(R.id.menu_page_other_languages); MenuItem findInPageItem = menu.findItem(R.id.menu_page_find_in_page); MenuItem themeChooserItem = menu.findItem(R.id.menu_page_font_and_theme); if (pageLoadStrategy.isLoading()) { savePageItem.setEnabled(false); shareItem.setEnabled(false); otherLangItem.setEnabled(false); findInPageItem.setEnabled(false); themeChooserItem.setEnabled(false); } else { shareItem.setEnabled(true); otherLangItem.setVisible(model.getPage() != null && model.getPage().getPageProperties().getLanguageCount() != 0); otherLangItem.setEnabled(true); findInPageItem.setEnabled(true); themeChooserItem.setEnabled(true); } }
Source:
public void getRepo() throws IOException { final Repo repo = this.repo(); MatcherAssert.assertThat(new MkRepoCommit( repo, SHA ).repo(), Matchers.equalTo(repo) ); }

Target:
public void getRepo() throws IOException { final Repo repo = this.repo(); MatcherAssert.assertThat( new MkRepoCommit( repo, "6dcb09b5b57875f334f61aebed695e2e4193db5e" ).repo(), Matchers.equalTo(repo) ); }
Source:
static String resolveArgValueFromStrContainingArgKey(String argString, Map<String, String> args) { Pattern argPattern = Pattern.compile("\\$(?:\\{(.*)\\}|(.*))"); Matcher matcher = argPattern.matcher(argString); if (matcher.find()) { if (matcher.group(1) != null) { return args.get(matcher.group(1)); } else if (matcher.group(2) != null) { return args.get(matcher.group(2)); } } return null; }

Target:
static String resolveArgValueFromStrContainingArgKey(String argString, Map<String, String> args) { Pattern argPattern = Pattern.compile(ARG_PATTERN_REGEX); Matcher matcher = argPattern.matcher(argString); if (matcher.matches()) { if (matcher.group(1) != null) { return args.get(matcher.group(1)); } else if (matcher.group(2) != null) { return args.get(matcher.group(2)); } } return null; }
Source:
public void visit(LwM2mResource resource) { if (resource.isMultiInstances()) { throw new CodecException("Multiple instances resource %s cannot be encoded in text format", path); } LOG.trace("Encoding resource into text", resource); ResourceModel rSpec = model.getResourceModel(path.getObjectId(), resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); Object val = converter.convertValue(resource.getValue(), resource.getType(), expectedType, path); String strValue; switch (expectedType) { case INTEGER: case FLOAT: case STRING: strValue = String.valueOf(val); break; case BOOLEAN: strValue = ((Boolean) val) ? "1" : "0"; break; case TIME: strValue = String.valueOf(((Date) val).getTime() / 1000L); break; case OBJLNK: ObjectLink objlnk = (ObjectLink) val; strValue = String.valueOf(objlnk.getObjectId() + ":" + objlnk.getObjectInstanceId()); break; case OPAQUE: byte[] binaryValue = ((byte[])val); strValue = Base64.encodeBase64String(binaryValue); break; default: throw new CodecException("Cannot encode %s in text format for %s", val, path); } encoded = strValue.getBytes(StandardCharsets.UTF_8); }

Target:
public void visit(LwM2mResource resource) { if (resource.isMultiInstances()) { throw new CodecException("Multiple instances resource %s cannot be encoded in text format", path); } LOG.trace("Encoding resource into text", resource); ResourceModel rSpec = model.getResourceModel(path.getObjectId(), resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); Object val = converter.convertValue(resource.getValue(), resource.getType(), expectedType, path); String strValue; switch (expectedType) { case INTEGER: case FLOAT: case STRING: strValue = String.valueOf(val); break; case BOOLEAN: strValue = ((Boolean) val) ? "1" : "0"; break; case TIME: strValue = String.valueOf(((Date) val).getTime() / 1000L); break; case OBJLNK: ObjectLink objlnk = (ObjectLink) val; strValue = String.valueOf(objlnk.getObjectId() + ":" + objlnk.getObjectInstanceId()); break; case OPAQUE: byte[] binaryValue = (byte[]) val; strValue = Base64.encodeBase64String(binaryValue); break; default: throw new CodecException("Cannot encode %s in text format for %s", val, path); } encoded = strValue.getBytes(StandardCharsets.UTF_8); }
Source:
public boolean isUpgrade(PullRequest pullRequest) { Objects.requireNonNull(pullRequest, "url cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPGRADE.matcher(body); return m.find(); }

Target:
public boolean isUpgrade(PullRequest pullRequest) { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPGRADE.matcher(body); return m.find(); }
Source:
public EntityRef createEntityWithId(long id, Iterable<Component> components) { if (!entityManager.registerId(id)) { return EntityRef.NULL; } for (Component c : components) { componentStore.put(id, c); } EntityRef entity = createEntityRef(id); if (entityManager.getEventSystem() != null) { entityManager.getEventSystem().send(entity, OnActivatedComponent.newInstance()); } for (Component component: components) { entityManager.notifyComponentAdded(entity, component.getClass()); } return entity; }

Target:
public EntityRef createEntityWithId(long id, Iterable<Component> components) { if (!entityManager.registerId(id)) { return EntityRef.NULL; } components = (components == null) ? Collections.EMPTY_LIST : components; for (Component c : components) { componentStore.put(id, c); } EntityRef entity = createEntityRef(id); EventSystem eventSystem = entityManager.getEventSystem(); if (eventSystem != null) { eventSystem.send(entity, OnActivatedComponent.newInstance()); } for (Component component : components) { entityManager.notifyComponentAdded(entity, component.getClass()); } return entity; }
Source:
public static List<GACallSet> create(List<String> variantSetNames, List<List<String>> callSets) { List<GACallSet> sets = new ArrayList<>(); Iterator<String> variantSetNamesIterator = variantSetNames.iterator(); Iterator<List<String>> callSetsIterator = callSets.iterator(); while (variantSetNamesIterator.hasNext() && callSetsIterator.hasNext()) { String fileName = variantSetNamesIterator.next(); List<String> callsInFile = callSetsIterator.next(); for (String callName : callsInFile) { GACallSet callset = new GACallSet(callName, callName, callName, new ArrayList<>(Arrays.asList(fileName)), System.currentTimeMillis(), System.currentTimeMillis(), null); sets.add(callset); } } return sets; }

Target:
public static List<GACallSet> create(List<String> variantSetNames, List<List<String>> callSets) { List<GACallSet> sets = new ArrayList<>(); Iterator<String> variantSetNamesIterator = variantSetNames.iterator(); Iterator<List<String>> callSetsIterator = callSets.iterator(); while (variantSetNamesIterator.hasNext() && callSetsIterator.hasNext()) { String fileName = variantSetNamesIterator.next(); List<String> callsInFile = callSetsIterator.next(); for (String callName : callsInFile) { GACallSet callset = new GACallSet(callName, callName, callName, Collections.singletonList(fileName), System.currentTimeMillis(), System.currentTimeMillis(), null); sets.add(callset); } } return sets; }
Source:
public void testAddDilutions() { PoolPage page1 = PoolPage.getForEdit(getDriver(), getBaseUrl(), 701L); DataTable includedTable = page1.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(0, includedTable.countRows()); DataTable available = page1.getTable(PoolTableWrapperId.AVAILABLE_DILUTIONS); available.searchFor("LDI701"); available.checkBoxForRow(0); page1.clickLinkButtonAndGetUrl("Add"); PoolPage page2 = PoolPage.getForEdit(getDriver(), getBaseUrl(), 701L); DataTable includedTable2 = page2.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(1, includedTable2.countRows()); }

Target:
public void testAddDilutions() { PoolPage page1 = PoolPage.getForEdit(getDriver(), getBaseUrl(), 701L); DataTable includedTable = page1.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(0, includedTable.countRows()); DataTable available = page1.getTable(PoolTableWrapperId.AVAILABLE_DILUTIONS); available.searchFor("LDI701"); available.checkBoxForRow(0); PoolPage page2 = page1.addSelectedDilutions(); DataTable includedTable2 = page2.getTable(PoolTableWrapperId.INCLUDED_DILUTIONS); assertEquals(1, includedTable2.countRows()); }
Source:
public int compareTo(TimestampedInputSplit o) { TimestampedHiveInputSplit split = (TimestampedHiveInputSplit) o; int modTimeComp = Long.compare(this.modificationTime, split.modificationTime); if (modTimeComp != 0L) { return modTimeComp; } int pathComp = this.hiveTablePartition.getStorageDescriptor().compareTo( split.hiveTablePartition.getStorageDescriptor()); return pathComp != 0 ? pathComp : this.getSplitNumber() - o.getSplitNumber(); }

Target:
public int compareTo(TimestampedInputSplit o) { TimestampedHiveInputSplit split = (TimestampedHiveInputSplit) o; int modTimeComp = Long.compare(this.modificationTime, split.modificationTime); if (modTimeComp != 0L) { return modTimeComp; } int sdComp = this.hiveTablePartition.getStorageDescriptor().compareTo( split.hiveTablePartition.getStorageDescriptor()); return sdComp != 0 ? sdComp : this.getSplitNumber() - o.getSplitNumber(); }
Source:
public void init() throws SchematronInitializationException { if (transformerFactory == null) { transformerFactory = XMLUtils.getInstance() .getSecureXmlTransformerFactory( TransformerFactoryImpl.class.getName(), SchematronValidationService.class.getClassLoader()); } Configuration config = ((TransformerFactoryImpl) transformerFactory).getConfiguration(); config.setErrorListener(new SaxonErrorListener(schematronFileNames)); updateValidators(); }

Target:
public void init() throws SchematronInitializationException { if (transformerFactory == null) { transformerFactory = XML_UTILS.getSecureXmlTransformerFactory( TransformerFactoryImpl.class.getName(), SchematronValidationService.class.getClassLoader()); } Configuration config = ((TransformerFactoryImpl) transformerFactory).getConfiguration(); config.setErrorListener(new SaxonErrorListener(schematronFileNames)); updateValidators(); }
Source:
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, response, supportedMediaTypes); if (MediaType.APPLICATION_JSON.equals(mediaType)) { request.getRequestDispatcher(meUri).forward(request, response); } else { request.getSession().setAttribute(FormController.SPRING_SECURITY_AUTHENTICATION_FAILED_KEY, errorModelFactory.toError(request, exception)); String redirectUrl = defaultFailureUrl; String next = request.getParameter("next"); if (redirectUrl.contains("?")) { redirectUrl += "&next=" + URLEncoder.encode(next, "UTF-8"); } else { redirectUrl += "?next=" + URLEncoder.encode(next, "UTF-8"); } redirectStrategy.sendRedirect(request, response, redirectUrl); } } catch (UnresolvedMediaTypeException ex) { log.error("Couldn't resolve media type: {}", ex.getMessage(), ex); } finally { FailedAuthenticationRequestEvent event = createFailureEvent(request, response, exception); publisher.publish(event); } }

Target:
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { try { MediaType mediaType = contentNegotiationResolver.getContentType(request, response, supportedMediaTypes); if (MediaType.APPLICATION_JSON.equals(mediaType)) { request.getRequestDispatcher(meUri).forward(request, response); } else { request.getSession().setAttribute(FormController.SPRING_SECURITY_AUTHENTICATION_FAILED_KEY, errorModelFactory.toError(request, exception)); String redirectUrl = defaultFailureUrl; String next = request.getParameter(NEXT_QUERY_PARAM); if (Strings.hasText(next)) { if (redirectUrl.contains("?")) { redirectUrl += "&" + NEXT_QUERY_PARAM + "=" + URLEncoder.encode(next, "UTF-8"); } else { redirectUrl += "?" + NEXT_QUERY_PARAM + "=" + URLEncoder.encode(next, "UTF-8"); } } redirectStrategy.sendRedirect(request, response, redirectUrl); } } catch (UnresolvedMediaTypeException ex) { log.error("Couldn't resolve media type: {}", ex.getMessage(), ex); } finally { FailedAuthenticationRequestEvent event = createFailureEvent(request, response, exception); publisher.publish(event); } }
Source:
private static void connect( SocketChannel soChannel, BoltServerAddress address, int timeoutMillis ) throws IOException { Socket socket = soChannel.socket(); try { socket.connect( address.toSocketAddress(), timeoutMillis ); } catch ( SocketTimeoutException e ) { throw new ConnectException( "Timeout " + timeoutMillis + "ms expired" + e.getMessage() ); } }

Target:
private static void connect( SocketChannel soChannel, BoltServerAddress address, int timeoutMillis ) throws IOException { Socket socket = soChannel.socket(); try { socket.connect( address.toSocketAddress(), timeoutMillis ); } catch ( SocketTimeoutException e ) { throw new ConnectException( "Timeout " + timeoutMillis + "ms expired" + e ); } }
Source:
private WikiObjectComponentBuilder getAssociatedComponentBuilder(DocumentReference xClassReference) { try { String serializedXClassReference = this.defaultEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance(WikiObjectComponentBuilder.class, serializedXClassReference); } else { serializedXClassReference = this.localEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance( WikiObjectComponentBuilder.class, serializedXClassReference); } else { return null; } } } catch (ComponentLookupException e) { this.logger.warn(String.format( "Unable to find a WikiObjectComponentBuilder associated to the helper [%s]: %s", xClassReference, e.getMessage())); return null; } }

Target:
private WikiObjectComponentBuilder getAssociatedComponentBuilder(DocumentReference xClassReference) { try { String serializedXClassReference = this.defaultEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance(WikiObjectComponentBuilder.class, serializedXClassReference); } else { serializedXClassReference = this.localEntityReferenceSerializer.serialize(xClassReference); if (this.componentManager.hasComponent(WikiObjectComponentBuilder.class, serializedXClassReference)) { return this.componentManager.getInstance( WikiObjectComponentBuilder.class, serializedXClassReference); } else { return null; } } } catch (ComponentLookupException e) { this.logger.error(String.format( "Unable to find a WikiObjectComponentBuilder associated to the helper [%s]: %s", xClassReference, e)); return null; } }
Source:
public E createInstance() { checkConverterInitialized(); I instance = internalSerializer.createInstance(); try { return converter.toExternal(instance); } catch (Throwable t) { return null; } }

Target:
public E createInstance() { checkConverterInitialized(); try { I instance = internalSerializer.createInstance(); return converter.toExternal(instance); } catch (Throwable t) { return null; } }
Source:
public OkapiError(@Nullable JSONObject data) { String localmessage = StringUtils.EMPTY; assert localmessage != null; if (data == null) { state = OkapiErrors.UNSPECIFIED; message = localmessage; return; } if (data.has("error")) { OkapiErrors localstate; try { JSONObject error = data.getJSONObject("error"); if (error.has("reason_stack")) { String reason = error.getString("reason_stack"); if (StringUtils.contains(reason, "invalid_oauth_request")) { if (StringUtils.contains(reason, "invalid_timestamp")) { localstate = OkapiErrors.INVALID_TIMESTAMP; } else if (StringUtils.contains(reason, "invalid_token")) { localstate = OkapiErrors.INVALID_TOKEN; } else { localstate = OkapiErrors.UNSPECIFIED; } } else { localstate = OkapiErrors.UNSPECIFIED; } } else { localstate = OkapiErrors.UNSPECIFIED; } if (error.has("developer_message")) { localmessage = StringUtils.defaultString(error.getString("developer_message")); assert localmessage != null; } } catch (JSONException ex) { Log.d("OkapiError: Failed to parse JSON", ex); localstate = OkapiErrors.UNSPECIFIED; } this.state = localstate; this.message = localmessage; return; } state = OkapiErrors.NO_ERROR; message = localmessage; }

Target:
public OkapiError(@Nullable JSONObject data) { if (data == null) { state = OkapiErrors.UNSPECIFIED; message = StringUtils.EMPTY; return; } if (data.has("error")) { String localmessage = null; OkapiErrors localstate = OkapiErrors.UNSPECIFIED; try { JSONObject error = data.getJSONObject("error"); if (error.has("reason_stack")) { String reason = error.getString("reason_stack"); if (StringUtils.contains(reason, "invalid_oauth_request")) { if (StringUtils.contains(reason, "invalid_timestamp")) { localstate = OkapiErrors.INVALID_TIMESTAMP; } else if (StringUtils.contains(reason, "invalid_token")) { localstate = OkapiErrors.INVALID_TOKEN; } } } if (error.has("developer_message")) { localmessage = error.getString("developer_message"); assert localmessage != null; } } catch (JSONException ex) { Log.d("OkapiError: Failed to parse JSON", ex); localstate = OkapiErrors.UNSPECIFIED; } state = localstate; message = StringUtils.defaultString(localmessage); return; } state = OkapiErrors.NO_ERROR; message = StringUtils.EMPTY; }
Source:
public void testImapAsyncClientExceptionWithSessionIdClientContext() { final ImapAsyncClientException.FailureType failureType = ImapAsyncClientException.FailureType.CHANNEL_DISCONNECTED; final Long sessionId = 5L; final String sessCtx = "T123riceratops123@scar123y.com"; final ImapAsyncClientException ex = new ImapAsyncClientException(failureType, sessionId, sessCtx); Assert.assertEquals(ex.getFaiureType(), failureType, "result mismatched."); Assert.assertNull(ex.getCause(), "cause of exception mismatched."); Assert.assertEquals(ex.getMessage(), "failureType=CHANNEL_DISCONNECTED,sId=5,uId=T123riceratops123@scar123y.com", "result mismatched."); }

Target:
public void testImapAsyncClientExceptionWithSessionIdClientContext() { final ImapAsyncClientException.FailureType failureType = ImapAsyncClientException.FailureType.CHANNEL_DISCONNECTED; final Long sessionId = new Long(5); final String sessCtx = "T123riceratops123@scar123y.com"; final ImapAsyncClientException ex = new ImapAsyncClientException(failureType, sessionId, sessCtx); Assert.assertEquals(ex.getFaiureType(), failureType, "result mismatched."); Assert.assertNull(ex.getCause(), "cause of exception mismatched."); Assert.assertEquals(ex.getMessage(), "failureType=CHANNEL_DISCONNECTED,sId=5,uId=T123riceratops123@scar123y.com", "result mismatched."); }
Source:
public void validate(Application application, ApplicationValidationErrors validationErrors) { if (Strings.isNullOrEmpty(Optional.ofNullable(application.getEmail()).orElse("").trim())) { validationErrors.rejectValue( "email", "application.email.empty", "Application must have a non-empty email"); } }

Target:
public void validate(Application application, ApplicationValidationErrors validationErrors) { if (Optional.ofNullable(application.getEmail()).orElse("").trim().isEmpty()) { validationErrors.rejectValue( "email", "application.email.empty", "Application must have a non-empty email"); } }
Source:
private void setDefaultValues() { fCharsetEditor.loadDefault(); fWideCharsetEditor.loadDefault(); fShowBinarySourceFilesButton.setSelection(DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID) .getBoolean(CCorePreferenceConstants.SHOW_SOURCE_FILES_IN_BINARIES, true)); fShowSourceNotFoundEditor.setSelection(DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID) .getBoolean(CCorePreferenceConstants.SHOW_SOURCE_NOT_FOUND_EDITOR, true)); fShowSourceNotFoundAllTime.setSelection(DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID) .getBoolean(CCorePreferenceConstants.SHOW_SOURCE_NOT_FOUND_EDITOR_ALL_TIME, true)); fShowSourceNotFoundOnlyCaseSourceNotFound.setSelection(!DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID) .getBoolean(CCorePreferenceConstants.SHOW_SOURCE_NOT_FOUND_EDITOR_ALL_TIME, true)); fShowSourceNotFoundAllTime.setEnabled(true); fShowSourceNotFoundOnlyCaseSourceNotFound.setEnabled(true); }

Target:
private void setDefaultValues() { fCharsetEditor.loadDefault(); fWideCharsetEditor.loadDefault(); fShowBinarySourceFilesButton.setSelection(DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID) .getBoolean(CCorePreferenceConstants.SHOW_SOURCE_FILES_IN_BINARIES, true)); fShowSourceNotFoundAllTime.setSelection(true); fShowSourceNotFoundOnlyCaseSourceNotFound.setSelection(false); fShowSourceNotFoundEditor.setSelection(false); }
Source:
public String getPreconditionAnnotation(VariableElement elt, AField f) { AnnotatedTypeMirror declaredType = fromElement(elt); if (!(declaredType.getAnnotations().contains(NULLABLE) || declaredType.getAnnotations().contains(POLYNULL) || declaredType.getAnnotations().contains(MONOTONIC_NONNULL))) { return null; } for (scenelib.annotations.Annotation a : f.type.tlAnnotationsHere) { if (a.def.name.equals("org.checkerframework.checker.nullness.qual.NonNull")) { return requiresNonNullAnno(elt); } } return null; }

Target:
public String getPreconditionAnnotation(VariableElement elt, AField f) { AnnotatedTypeMirror declaredType = fromElement(elt); if (!(declaredType.hasAnnotation(NULLABLE) || declaredType.hasAnnotation(POLYNULL) || declaredType.hasAnnotation(MONOTONIC_NONNULL))) { return null; } for (scenelib.annotations.Annotation a : f.type.tlAnnotationsHere) { if (a.def.name.equals("org.checkerframework.checker.nullness.qual.NonNull")) { return requiresNonNullAnno(elt); } } return null; }
Source:
public void writeTo(OptionalLong entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { if (!entity.isPresent()) { throw new NoContentException("Empty content."); } entityStream.write(Long.toString(entity.getAsLong()).getBytes(StandardCharsets.US_ASCII)); }

Target:
public void writeTo(OptionalLong entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { if (!entity.isPresent()) { throw new WebApplicationException(Status.NO_CONTENT); } entityStream.write(Long.toString(entity.getAsLong()).getBytes(StandardCharsets.US_ASCII)); }
Source:
public SerializedPage serialize(Page page) { SliceOutput serializationBuffer = new DynamicSliceOutput(toIntExact((page.getSizeInBytes() + Integer.BYTES))); writeRawPage(page, serializationBuffer, blockEncodingSerde); byte markings = PageCodecMarker.none(); if (!compressor.isPresent()) { return new SerializedPage(serializationBuffer.slice(), markings, page.getPositionCount(), serializationBuffer.size()); } int maxCompressedLength = maxCompressedLength(serializationBuffer.size()); byte[] compressionBuffer = new byte[maxCompressedLength]; int actualCompressedLength = compressor.get().compress(serializationBuffer.slice().getBytes(), 0, serializationBuffer.size(), compressionBuffer, 0, maxCompressedLength); if (((1.0 * actualCompressedLength) / serializationBuffer.size()) > MINIMUM_COMPRESSION_RATIO) { return new SerializedPage(serializationBuffer.slice(), markings, page.getPositionCount(), serializationBuffer.size()); } else { return new SerializedPage( Slices.copyOf(Slices.wrappedBuffer(compressionBuffer, 0, actualCompressedLength)), PageCodecMarker.COMPRESSED.mark(markings), page.getPositionCount(), serializationBuffer.size()); } }

Target:
public SerializedPage serialize(Page page) { SliceOutput serializationBuffer = new DynamicSliceOutput(toIntExact(page.getSizeInBytes() + Integer.BYTES)); writeRawPage(page, serializationBuffer, blockEncodingSerde); Slice slice = serializationBuffer.slice(); int uncompressedSize = serializationBuffer.size(); byte markers = PageCodecMarker.none(); if (compressor.isPresent()) { ByteBuffer compressionBuffer = ByteBuffer.allocate(compressor.get().maxCompressedLength(uncompressedSize)); compressor.get().compress(slice.toByteBuffer(), compressionBuffer); compressionBuffer.flip(); if ((((double) compressionBuffer.remaining()) / uncompressedSize) <= MINIMUM_COMPRESSION_RATIO) { slice = Slices.wrappedBuffer(compressionBuffer); markers = COMPRESSED.set(markers); } } if (spillCipher.isPresent()) { slice = Slices.wrappedBuffer(spillCipher.get().encrypt(slice.toByteBuffer())); markers = ENCRYPTED.set(markers); } else { slice = Slices.copyOf(slice); } return new SerializedPage(slice, markers, page.getPositionCount(), uncompressedSize); }
Source:
public static byte[] buildUsermetadata(RestRequest restRequest) throws RestServiceException { Map<String, List<String>> args = restRequest.getArgs(); Map<String, String> userMetadataMap = new HashMap<String, String>(); int sizeToAllocate = 0; for (Map.Entry<String, List<String>> entry : args.entrySet()) { String key = entry.getKey(); if (key.startsWith(Headers.UserMetaData_Header_Prefix)) { sizeToAllocate += 4; sizeToAllocate += key.substring(Headers.UserMetaData_Header_Prefix_Length).getBytes().length; String value = getHeader(args, key, true); userMetadataMap.put(key.substring(Headers.UserMetaData_Header_Prefix_Length), value); sizeToAllocate += 4; sizeToAllocate += value.getBytes().length; } } ByteBuffer userMetadata = null; if (sizeToAllocate == 0) { userMetadata = ByteBuffer.allocate(0); } else { sizeToAllocate += 2; sizeToAllocate += 4; sizeToAllocate += 4; sizeToAllocate += Crc_Size; userMetadata = ByteBuffer.allocate(sizeToAllocate); userMetadata.putShort(UserMetadata_Version_V1); userMetadata.putInt(sizeToAllocate - 6 - Crc_Size); userMetadata.putInt(userMetadataMap.size()); for (Map.Entry<String, String> entry : userMetadataMap.entrySet()) { String key = entry.getKey(); Utils.serializeString(userMetadata, key, StandardCharsets.US_ASCII); Utils.serializeString(userMetadata, entry.getValue(), StandardCharsets.US_ASCII); } Crc32 crc = new Crc32(); crc.update(userMetadata.array(), 0, sizeToAllocate - Crc_Size); userMetadata.putLong(crc.getValue()); } return userMetadata.array(); }

Target:
public static byte[] buildUsermetadata(RestRequest restRequest) throws RestServiceException { Map<String, List<String>> args = restRequest.getArgs(); Map<String, String> userMetadataMap = new HashMap<String, String>(); int sizeToAllocate = 0; for (Map.Entry<String, List<String>> entry : args.entrySet()) { String key = entry.getKey(); if (key.startsWith(Headers.UserMetaData_Header_Prefix)) { sizeToAllocate += 4; String keyToStore = key.substring(Headers.UserMetaData_Header_Prefix.length()); sizeToAllocate += keyToStore.length(); String value = getHeader(args, key, true); userMetadataMap.put(keyToStore, value); sizeToAllocate += 4; sizeToAllocate += value.getBytes().length; } } ByteBuffer userMetadata = null; if (sizeToAllocate == 0) { userMetadata = ByteBuffer.allocate(0); } else { sizeToAllocate += 2; sizeToAllocate += 4; sizeToAllocate += 4; sizeToAllocate += Crc_Size; userMetadata = ByteBuffer.allocate(sizeToAllocate); userMetadata.putShort(UserMetadata_Version_V1); userMetadata.putInt(sizeToAllocate - 6 - Crc_Size); userMetadata.putInt(userMetadataMap.size()); for (Map.Entry<String, String> entry : userMetadataMap.entrySet()) { String key = entry.getKey(); Utils.serializeString(userMetadata, key, StandardCharsets.US_ASCII); Utils.serializeString(userMetadata, entry.getValue(), StandardCharsets.US_ASCII); } Crc32 crc = new Crc32(); crc.update(userMetadata.array(), 0, sizeToAllocate - Crc_Size); userMetadata.putLong(crc.getValue()); } return userMetadata.array(); }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartNoneEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartNoneEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); if (getMarshallerType() == Marshaller.NEW) { assertEquals(emptyTop.getExecutionSet().getSlaDueDate().getValue(), ""); } }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartNoneEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartNoneEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertNotNull(emptyTop.getExecutionSet()); assertStartEventSlaDueDate(emptyTop.getExecutionSet(), EMPTY_VALUE); }
Source:
public void readRecuperaveis(){ File f = Configuracoes.getInstancia().getDiretorioTemporario(); f.mkdirs(); for (File arquivo : f.listFiles()) { if (arquivo.isDirectory()) { } else { if(arquivo.getName().contains(".por")) { arquivosIniciais.add(arquivo);; } } } }

Target:
public void readRecuperaveis(){ File f = Configuracoes.getInstancia().getDiretorioTemporario(); f.mkdirs(); for (File arquivo : f.listFiles()) { if (!arquivo.isDirectory()) { if(isArquivoRecuperado(arquivo)) { if(arquivo.getName().contains("Sem título")) { arquivosIniciais.add(arquivo); } else { arquivosRecuperados.add(arquivo); } } } } }
Source:
public static void testJPADep(Map<DependencyType, List<DynamicPomDependency>> mapping) { List<DynamicPomDependency> deps = mapping.get(DependencyType.JPA); assertThat(deps).hasSize(1); DynamicPomDependency dep = deps.get(0); assertThat(dep.getGroupID()).isEqualToIgnoringCase("org.hibernate.javax.persistence"); assertThat(dep.getArtifactID()).isEqualToIgnoringCase("hibernate-jpa-2.1-api"); assertThat(dep.getVersion()).isEqualToIgnoringCase("1.0.2.Final"); assertThat(dep.getScope()).isEmpty(); }

Target:
public static void testJPADep(Map<DependencyType, List<DynamicPomDependency>> mapping) { List<DynamicPomDependency> deps = mapping.get(DependencyType.JPA); assertThat(deps).hasSize(1); DynamicPomDependency dep = deps.get(0); assertThat(dep.getGroupID()).isEqualToIgnoringCase(GROUP_ID_TEST); assertThat(dep.getArtifactID()).isEqualToIgnoringCase(ARTIFACT_ID_TEST); assertThat(dep.getVersion()).isEqualToIgnoringCase(VERSION_ID_TEST); assertThat(dep.getScope()).isEmpty(); }
Source:
protected void testExpirationFilter(Object keyToFilterOut, Long keyToFilterOutLifespan, Object keyToUse, Long keyToUselifespan, CacheEventFilter<? super Object, ? super String> filter) { Cache<Object, String> cache0 = cache(0, CACHE_NAME); cache0.put(keyToFilterOut, FIRST_VALUE, keyToFilterOutLifespan, TimeUnit.MILLISECONDS); ClusterListener clusterListener = listener(); cache0.addListener(clusterListener, filter, null); ts0.advance(keyToFilterOutLifespan + 1); ts1.advance(keyToFilterOutLifespan + 1); ts2.advance(keyToFilterOutLifespan + 1); assertEquals(clusterListener.events.size(), 0); assertNull(cache0.get(keyToFilterOut)); String expectedValue = keyToUse + "-expiring"; cache0.put(keyToUse, keyToUse + "-expiring", keyToUselifespan, TimeUnit.MILLISECONDS); ts0.advance(keyToUselifespan + 1); ts1.advance(keyToUselifespan + 1); ts2.advance(keyToUselifespan + 1); assertNull(cache0.get(keyToUse)); verifySimpleExpirationEvents(clusterListener, 2, keyToUse, expectedValue); }

Target:
protected void testExpirationFilter(Object keyToFilterOut, Long keyToFilterOutLifespan, Object keyToUse, Long keyToUselifespan, CacheEventFilter<? super Object, ? super String> filter) { Cache<Object, String> cache0 = cache(0, CACHE_NAME); cache0.put(keyToFilterOut, FIRST_VALUE, keyToFilterOutLifespan, TimeUnit.MILLISECONDS); ClusterListener clusterListener = listener(); cache0.addListener(clusterListener, filter, null); ts0.advance(keyToFilterOutLifespan + 1); ts1.advance(keyToFilterOutLifespan + 1); ts2.advance(keyToFilterOutLifespan + 1); assertNull(cache0.get(keyToFilterOut)); assertEquals(clusterListener.events.size(), 0); String expectedValue = keyToUse + "-expiring"; cache0.put(keyToUse, keyToUse + "-expiring", keyToUselifespan, TimeUnit.MILLISECONDS); ts0.advance(keyToUselifespan + 1); ts1.advance(keyToUselifespan + 1); ts2.advance(keyToUselifespan + 1); assertNull(cache0.get(keyToUse)); verifySimpleExpirationEvents(clusterListener, 2, keyToUse, expectedValue); }
Source:
public void onPreMerge(Repository repo, CodeReviewCommit commit, ProjectState destProject, NameKey destBranch, Id patchSetId) throws MergeValidationException { try { db = schemaFactory.open(); PatchSetApproval psa = approvalsUtil.getSubmitter(db, commit.notes(), patchSetId); if (psa == null) { throw new MergeValidationException( CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN); } final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId()); if (!submitter.getCapabilities().canAdministrateServer()) { throw new MergeValidationException(CommitMergeStatus.MISSING_DEPENDENCY); } } catch (OrmException e) { throw new MergeValidationException( CommitMergeStatus.SETTING_PARENT_PROJECT_ONLY_ALLOWED_BY_ADMIN); } finally { if (db != null) { db.close(); } } }

Target:
public void onPreMerge(Repository repo, CodeReviewCommit commit, ProjectState destProject, NameKey destBranch, Id patchSetId) throws MergeValidationException { try { db = schemaFactory.open(); PatchSetApproval psa = approvalsUtil.getSubmitter(db, commit.notes(), patchSetId); if (psa == null) { throw new MergeValidationException( CommitMergeStatus.REJECTED_BY_PLUGIN, "Submitter not found"); } final IdentifiedUser submitter = identifiedUserFactory.create(psa.getAccountId()); if (!submitter.getCapabilities().canAdministrateServer()) { throw new MergeValidationException(CommitMergeStatus.REJECTED_BY_PLUGIN, "Submitter is not admin"); } } catch (OrmException e) { throw new MergeValidationException( CommitMergeStatus.REJECTED_BY_PLUGIN, "DB error"); } finally { if (db != null) { db.close(); } } }
Source:
public GlacierResponseException(String message, HttpCommand command, HttpResponse response, GlacierError error, Throwable cause) { super(message, command, response, cause); this.error = checkNotNull(error); }

Target:
public GlacierResponseException(String message, HttpCommand command, HttpResponse response, GlacierError error, Throwable cause) { super(message, command, response, cause); this.error = checkNotNull(error, "error"); }