auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void showWithSheetView(View sheetView, ViewTransformer viewTransformer, OnSheetDismissedListener onSheetDismissedListener) { if (state != State.HIDDEN) { throw new IllegalStateException("A sheet view is already presented, make sure to dismiss it before showing another."); } LayoutParams params = (LayoutParams) sheetView.getLayoutParams(); if (params != null) { params.width = ViewGroup.LayoutParams.MATCH_PARENT; } else { params = generateDefaultLayoutParams(); } super.addView(sheetView, -1, params); initializeSheetValues(); this.viewTransformer = viewTransformer; this.onSheetDismissedListener = onSheetDismissedListener; getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(this); post(new Runnable() { @Override public void run() { if (getSheetView() != null) { peekSheet(); } } }); return true; } }); currentSheetViewHeight = sheetView.getMeasuredHeight(); sheetViewOnLayoutChangeListener = new OnLayoutChangeListener() { @Override public void onLayoutChange(View sheetView, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int newSheetViewHeight = sheetView.getMeasuredHeight(); if (state != State.HIDDEN) { if (newSheetViewHeight < currentSheetViewHeight) { if (state == State.EXPANDED) { setState(State.PEEKED); } setSheetTranslation(sheetView.getMeasuredHeight()); } } currentSheetViewHeight = newSheetViewHeight; } }; sheetView.addOnLayoutChangeListener(sheetViewOnLayoutChangeListener); }

Target:
public void showWithSheetView(View sheetView, ViewTransformer viewTransformer, OnSheetDismissedListener onSheetDismissedListener) { if (state != State.HIDDEN) { throw new IllegalStateException("A sheet view is already presented, make sure to dismiss it before showing another."); } LayoutParams params = (LayoutParams) sheetView.getLayoutParams(); if (params != null) { params.width = ViewGroup.LayoutParams.MATCH_PARENT; } else { params = generateDefaultLayoutParams(); } super.addView(sheetView, -1, params); initializeSheetValues(); this.viewTransformer = viewTransformer; this.onSheetDismissedListener = onSheetDismissedListener; getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(this); post(new Runnable() { @Override public void run() { if (getSheetView() != null) { peekSheet(); } } }); return true; } }); currentSheetViewHeight = sheetView.getMeasuredHeight(); sheetViewOnLayoutChangeListener = new OnLayoutChangeListener() { @Override public void onLayoutChange(View sheetView, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { int newSheetViewHeight = sheetView.getMeasuredHeight(); if (state != State.HIDDEN && newSheetViewHeight < currentSheetViewHeight) { if (state == State.EXPANDED) { setState(State.PEEKED); } setSheetTranslation(newSheetViewHeight); } currentSheetViewHeight = newSheetViewHeight; } }; sheetView.addOnLayoutChangeListener(sheetViewOnLayoutChangeListener); }
Source:
public void onArenaStarts(PAStartEvent event) { Map<String, dObject> context = new HashMap<String, dObject>(); Arena arena = event.getArena(); context.put("arena", new Element(arena.getName())); ArrayList<dPlayer> fighters = new ArrayList<dPlayer>(); for (ArenaPlayer player : event.getArena().getFighters()) fighters.add(new dPlayer(player.get())); context.put("fighters", new dList(fighters)); OldEventManager.doEvents(Arrays.asList ("pvparena starts"), null, context); }

Target:
public void onArenaStarts(PAStartEvent event) { Map<String, dObject> context = new HashMap<String, dObject>(); Arena arena = event.getArena(); context.put("arena", new Element(arena.getName())); ArrayList<dPlayer> fighters = new ArrayList<dPlayer>(); for (ArenaPlayer player : event.getArena().getFighters()) fighters.add(new dPlayer(player.get())); context.put("fighters", new dList(fighters)); OldEventManager.doEvents(Arrays.asList ("pvparena starts", "arena starts"), null, context); }
Source:
protected void doInit() { this.setBeanFactory(this.getBeanFactory()); this.initialized = true; if (this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); TypeLocator typeLocator = this.evaluationContext.getTypeLocator(); if (typeLocator instanceof StandardTypeLocator) { ((StandardTypeLocator) typeLocator).registerImport(Query.class.getPackage().getName()); } } if (this.mongoTemplate == null) { this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mongoConverter); } }

Target:
protected void doInit() { Assert.state(this.queryExpression != null, "no query specified"); Assert.state(this.collectionNameExpression != null, "no collection name specified"); if (this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); TypeLocator typeLocator = this.evaluationContext.getTypeLocator(); if (typeLocator instanceof StandardTypeLocator) { ((StandardTypeLocator) typeLocator).registerImport(Query.class.getPackage().getName()); } } if (this.mongoTemplate == null) { this.mongoTemplate = new MongoTemplate(this.mongoDbFactory, this.mongoConverter); } }
Source:
public void incrementUsageCount(Long templateId) { try { Template toUpdate = em.find(Template.class, templateId); Long usage = toUpdate.getUsageCount(); usage++; toUpdate.setUsageCount(usage); em.merge(toUpdate); } catch (Exception e) { logger.log(Level.INFO, "Increment usage count failed on template id {0}. ", templateId); } }

Target:
public void incrementUsageCount(Long templateId) { Template toUpdate = em.find(Template.class, templateId); Long usage = toUpdate.getUsageCount(); usage++; toUpdate.setUsageCount(usage); em.merge(toUpdate); }
Source:
public static String canonicalNameFromTypeMirror(final TypeMirror type) { final StringBuilder result = new StringBuilder(); type.accept(new SimpleTypeVisitor6<Void, Void>() { @Override public Void visitDeclared(DeclaredType declaredType, Void v) { TypeElement typeElement = (TypeElement) declaredType.asElement(); result.append(typeElement.toString()); return null; } @Override public Void visitPrimitive(PrimitiveType primitiveType, Void v) { return null; } @Override public Void visitArray(ArrayType arrayType, Void v) { result.append(arrayType.getComponentType().toString()); result.append("[]"); return null; } @Override public Void visitTypeVariable(TypeVariable typeVariable, Void v) { return null; } @Override protected Void defaultAction(TypeMirror typeMirror, Void v) { throw new UnsupportedOperationException( "Unexpected TypeKind " + typeMirror.getKind() + " for " + typeMirror); } }, null); return result.toString(); }

Target:
public static String canonicalNameFromTypeMirror(final TypeMirror type) { final StringBuilder result = new StringBuilder(); type.accept(new SimpleTypeVisitor6<Void, Void>() { @Override public Void visitDeclared(DeclaredType declaredType, Void v) { TypeElement typeElement = (TypeElement) declaredType.asElement(); result.append(typeElement.toString()); return null; } @Override public Void visitPrimitive(PrimitiveType primitiveType, Void v) { throw new UnsupportedOperationException( "Unexpected TypeKind " + primitiveType.getKind() + " for " + primitiveType); } @Override public Void visitArray(ArrayType arrayType, Void v) { throw new UnsupportedOperationException( "Unexpected TypeKind " + arrayType.getKind() + " for " + arrayType); } @Override public Void visitTypeVariable(TypeVariable typeVariable, Void v) { throw new UnsupportedOperationException( "Unexpected TypeKind " + typeVariable.getKind() + " for " + typeVariable); } @Override protected Void defaultAction(TypeMirror typeMirror, Void v) { throw new UnsupportedOperationException( "Unexpected TypeKind " + typeMirror.getKind() + " for " + typeMirror); } }, null); return result.toString(); }
Source:
public synchronized void increaseToAtLeast(long newTimestamp) { long current = this.timestamp; if (newTimestamp > current) { this.timestamp = newTimestamp; } }

Target:
public synchronized void increaseToAtLeast(long newTimestamp) { if (newTimestamp > this.timestamp) { this.timestamp = newTimestamp; } }
Source:
private String tfsSdkCommandTCLAdapterClassName() { String className = "com.thoughtworks.go.tfssdk14.TfsSDKCommandTCLAdapter"; if (new SystemEnvironment().get(SystemEnvironment.TFS_SDK_10)) { className = "com.thoughtworks.go.tfssdk10.TfsSDKCommandTCLAdapter"; } return className; }

Target:
private String tfsSdkCommandTCLAdapterClassName() { return "com.thoughtworks.go.tfssdk.TfsSDKCommandTCLAdapter"; }
Source:
private void mappingUnifiedNativeNormalAd(NendAdNative ad, boolean shouldReturnUrlsForImageAssets, Bitmap adImageBitmap, Bitmap logoImageBitmap) { Context context = forwarder.contextWeakReference.get(); if (context == null) { Log.e(TAG, "Your context may be released..."); forwarder.failedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST); } else { forwarder.unifiedNativeAdMapper = new NendUnifiedNativeNormalAdMapper( context, forwarder, ad, (shouldReturnUrlsForImageAssets || adImageBitmap != null ? new NendNativeMappedImage( forwarder.contextWeakReference.get(), adImageBitmap, Uri.parse(ad.getAdImageUrl())) : null ), (shouldReturnUrlsForImageAssets || logoImageBitmap != null ? new NendNativeMappedImage( forwarder.contextWeakReference.get(), logoImageBitmap, Uri.parse(ad.getLogoImageUrl())) : null ) ); forwarder.adLoaded(); } }

Target:
private void mappingUnifiedNativeNormalAd(NendAdNative ad, boolean shouldReturnUrlsForImageAssets, Bitmap adImageBitmap, Bitmap logoImageBitmap) { Context context = forwarder.getContextFromWeakReference(); if (context == null) { Log.e(TAG, "Your context may be released..."); forwarder.failedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST); return; } NendNativeMappedImage adImage = null; if (shouldReturnUrlsForImageAssets || adImageBitmap != null) { adImage = new NendNativeMappedImage(context, adImageBitmap, Uri.parse(ad.getAdImageUrl())); } NendNativeMappedImage logoImage = null; if (shouldReturnUrlsForImageAssets || logoImageBitmap != null) { logoImage = new NendNativeMappedImage(context, logoImageBitmap, Uri.parse(ad.getLogoImageUrl())); } forwarder.unifiedNativeAdMapper = new NendUnifiedNativeNormalAdMapper(context, forwarder, ad, adImage, logoImage); forwarder.adLoaded(); }
Source:
private void submitSearch(@Nullable final String query, boolean delayed) { mSearchQuery = query; if (query == null || query.length() < MIN_SEARCH_QUERY_SIZE) { mAdapter.clear(); showEmptyView(true); return; } if (delayed) { mHandler.postDelayed(new Runnable() { @Override public void run() { if (StringUtils.equals(query, mSearchQuery)) { submitSearch(query, false); } } }, 500); } else { requestStockMedia(query, 1); } }

Target:
private void submitSearch(@Nullable final String query, boolean delayed) { mSearchQuery = query; if (delayed) { mHandler.postDelayed(new Runnable() { @Override public void run() { if (StringUtils.equals(query, mSearchQuery)) { submitSearch(query, false); } } }, 500); } else { fetchStockMedia(query, 1); } }
Source:
protected void writeAttributeRaw(String attributeName, String attributeValue) throws XMLStreamException { try { outputStream.write(" ".getBytes(StandardCharsets.UTF_8)); outputStream.write(attributeName.getBytes(StandardCharsets.UTF_8)); outputStream.write("=\"".getBytes(StandardCharsets.UTF_8)); String escapedValue = attributeValue.replace("&", "&amp;"); escapedValue = escapedValue.replace("<", "&lt;"); escapedValue = escapedValue.replace(">", "&gt;"); escapedValue = escapedValue.replace("\"", "&quot;"); escapedValue = escapedValue.replace("\n", "&#10;"); outputStream.write(escapedValue.getBytes(StandardCharsets.UTF_8)); outputStream.write("\" ".getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new XMLStreamException("Could not write raw attribute", e); } }

Target:
protected void writeAttributeRaw(String attributeName, String attributeValue) throws XMLStreamException { try (Writer osWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) { osWriter.write(" "); osWriter.write(attributeName); osWriter.write("=\""); osWriter.write(attributeValue); osWriter.write("\" "); } catch (IOException e) { throw new XMLStreamException("Could not write raw attribute", e); } }
Source:
private void processSelectionChanged() { List<T> selectedItems = getSelectedItems(); selectedIndexes.clear(); model.getItems().forEach(item -> { if (selectedItems.contains(item)) { selectedIndexes.add(model.getItemsAsList().indexOf(item)); } }); updateInfoPanel(); }

Target:
private void processSelectionChanged() { List<T> selectedItems = selectionModel.getSelectedObjects(); selectedIndexes.clear(); model.getItems().forEach(item -> { if (selectedItems.contains(item)) { selectedIndexes.add(model.getItemsAsList().indexOf(item)); } }); updateInfoPanel(); }
Source:
private Locale getLocale() { final ServiceReference<EMFFormsLocaleProvider> serviceReference = bundleContext .getServiceReference(EMFFormsLocaleProvider.class); if (serviceReference == null) { return null; } final EMFFormsLocaleProvider localeProvider = bundleContext.getService(serviceReference); final Locale result = localeProvider.getLocale(); bundleContext.ungetService(serviceReference); return result; }

Target:
private String getLocale() { final ServiceReference<EMFFormsLocaleProvider> serviceReference = bundleContext .getServiceReference(EMFFormsLocaleProvider.class); if (serviceReference == null) { return null; } final EMFFormsLocaleProvider localeProvider = bundleContext.getService(serviceReference); final Locale result = localeProvider.getLocale(); bundleContext.ungetService(serviceReference); return result.getLanguage(); }
Source:
public ThePresentationReconcilerGreen() { RuleBasedScanner scanner= new RuleBasedScanner(); IRule[] rules = new IRule[1]; rules[0]= new SingleLineRule("'", "'", new Token(new TextAttribute(new Color(Display.getCurrent(), new RGB(255, 0, 0))))); scanner.setRules(rules); DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner); this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); }

Target:
public ThePresentationReconcilerGreen() { RuleBasedScanner scanner= new RuleBasedScanner(); IRule[] rules = new IRule[1]; rules[0]= new SingleLineRule("'", "'", new Token(new TextAttribute(new Color(Display.getCurrent(), new RGB(0, 255, 0))))); scanner.setRules(rules); DefaultDamagerRepairer dr= new DefaultDamagerRepairer(scanner); this.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); this.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); }
Source:
protected void doStart() throws Exception { super.doStart(); initSecurityProvider(); RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), getComponentName()); if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(this, config.getComponentProperties()); } }

Target:
protected void doStart() throws Exception { super.doStart(); if (this.securityProvider == null) { initSecurityProvider(); } RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), getComponentName()); if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) { setProperties(this, config.getComponentProperties()); } }
Source:
private @NonNull static List<Definition> createIntDefs(int size, int bits) { List<Definition> defs = new ArrayList<>(size); for (int i = 0; i < size; i++) { String content = "test" + i; defs.add(new IntegerDefinition(IntegerDeclaration.createDeclaration(bits, false, 16, ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, content, 24), null, content, i)); } return defs; }

Target:
private static List<Definition> createIntDefs(int size, int bits) { List<Definition> defs = new ArrayList<>(size); for (int i = 0; i < size; i++) { String content = "test" + i; defs.add(new IntegerDefinition(IntegerDeclaration.createDeclaration(bits, false, 16, ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, content, 24), null, content, i)); } return defs; }
Source:
public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } QueryTraversal queryTraversal = newQueryTraversal(parameters); Map<QueryVisitorFieldEnvironment, List<Integer>> valuesByParent = new LinkedHashMap<>(); queryTraversal.visitPostOrder(new QueryVisitorStub() { @Override public void visitField(QueryVisitorFieldEnvironment env) { int childsComplexity = 0; QueryVisitorFieldEnvironment thisNodeAsParent = new QueryVisitorFieldEnvironment(env.getField(), env.getFieldDefinition(), env.getParentType(), env.getParentEnvironment(), env.getArguments(), env.getSelectionSetContainer()); if (valuesByParent.containsKey(thisNodeAsParent)) { childsComplexity = valuesByParent.get(thisNodeAsParent).stream().mapToInt(Integer::intValue).sum(); } int value = calculateComplexity(env, childsComplexity); valuesByParent.putIfAbsent(env.getParentEnvironment(), new ArrayList<>()); valuesByParent.get(env.getParentEnvironment()).add(value); } }); int totalComplexity = valuesByParent.get(null).stream().mapToInt(Integer::intValue).sum(); if (totalComplexity > maxComplexity) { throw mkAbortException(totalComplexity, maxComplexity); } }); }

Target:
public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) { return whenCompleted((errors, throwable) -> { if ((errors != null && errors.size() > 0) || throwable != null) { return; } QueryTraversal queryTraversal = newQueryTraversal(parameters); Map<QueryVisitorFieldEnvironment, List<Integer>> valuesByParent = new LinkedHashMap<>(); queryTraversal.visitPostOrder(new QueryVisitorStub() { @Override public void visitField(QueryVisitorFieldEnvironment env) { int childsComplexity = 0; QueryVisitorFieldEnvironment thisNodeAsParent = new QueryVisitorFieldEnvironmentImpl(env.getField(), env.getFieldDefinition(), env.getParentType(), env.getParentEnvironment(), env.getArguments(), env.getSelectionSetContainer()); if (valuesByParent.containsKey(thisNodeAsParent)) { childsComplexity = valuesByParent.get(thisNodeAsParent).stream().mapToInt(Integer::intValue).sum(); } int value = calculateComplexity(env, childsComplexity); valuesByParent.putIfAbsent(env.getParentEnvironment(), new ArrayList<>()); valuesByParent.get(env.getParentEnvironment()).add(value); } }); int totalComplexity = valuesByParent.get(null).stream().mapToInt(Integer::intValue).sum(); if (totalComplexity > maxComplexity) { throw mkAbortException(totalComplexity, maxComplexity); } }); }
Source:
public void finish(OwlTelescopeReporter telescope) { processSeenContent(telescope); processTopLevelSeries(telescope); processStandAloneEpisodes(telescope); if (cached.values().size() > 0) { log.warn("{} extracted but unwritten", cached.values().size()); for (Entry<String, Collection<ModelWithPayload<? extends Content>>> mapping : cached.asMap().entrySet()) { log.warn(mapping.toString()); } for(ModelWithPayload<? extends Content> content : cached.values()) { telescope.reportFailedEvent( content.getModel().getId(), "Content has been extracted but not written", EntityType.CONTENT, content.getPayload() ); } } seenContainer.clear(); cached.clear(); topLevelSeries.clear(); standAloneEpisodes.clear(); checkForDeletedContent(telescope); seenContent.clear(); }

Target:
public void finish(OwlTelescopeReporter telescope) { processSeenContent(telescope); processTopLevelSeries(telescope); processStandAloneEpisodes(telescope); if (cached.values().size() > 0) { log.warn("{} extracted but unwritten", cached.values().size()); for (Entry<String, Collection<ModelWithPayload<? extends Content>>> mapping : cached.asMap().entrySet()) { log.warn(mapping.toString()); for(ModelWithPayload<? extends Content> map : mapping.getValue()) { telescope.reportFailedEvent( map.getModel().getId(), "Content has been extracted but not written", EntityType.CONTENT, map.getPayload() ); } } } seenContainer.clear(); cached.clear(); topLevelSeries.clear(); standAloneEpisodes.clear(); checkForDeletedContent(telescope); seenContent.clear(); }
Source:
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception { String body = in.get(config.field); if (body == null) { return; } try { org.apache.commons.csv.CSVParser parser = org.apache.commons.csv.CSVParser.parse(body, csvFormat); List<CSVRecord> records = parser.getRecords(); for (CSVRecord record : records) { emitter.emit(createStructuredRecord(record, in)); } } catch (IOException e) { throw Throwables.propagate(e); } }

Target:
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception { String body = in.get(config.field); try { if (body == null) { emitter.emit(createStructuredRecord(null, in)); } else { org.apache.commons.csv.CSVParser parser = org.apache.commons.csv.CSVParser.parse(body, csvFormat); List<CSVRecord> records = parser.getRecords(); for (CSVRecord record : records) { emitter.emit(createStructuredRecord(record, in)); } } } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
private static String encodingParams(final List<String> paramValues, final String encoding) throws UnsupportedEncodingException { if (null == paramValues) { return null; } StringBuilder sb = new StringBuilder(); for (Iterator<String> iter = paramValues.iterator(); iter.hasNext();) { sb.append(iter.next()).append("="); sb.append(URLEncoder.encode(iter.next(), encoding)); if (iter.hasNext()) { sb.append("&"); } } return sb.toString(); }

Target:
private static String encodingParams(final List<String> paramValues, final String encoding) throws UnsupportedEncodingException { if (null == paramValues || 0 == paramValues.size()) { return null; } StringBuilder stringBuilder = new StringBuilder(); for (Iterator<String> iter = paramValues.iterator(); iter.hasNext();) { stringBuilder.append(iter.next()).append("="); stringBuilder.append(URLEncoder.encode(iter.next(), encoding)); if (iter.hasNext()) { stringBuilder.append("&"); } } return stringBuilder.toString(); }
Source:
public void addNotification() throws Exception { Notification notification = null; for (int i = 1; i <= NO_OF_DEVICES; i++) { DeviceIdentifier testDeviceIdentifier = new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE); notification = TestDataHolder.getNotification(i, Notification.Status.NEW.toString(), testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + i, NOTIFICATION_OPERATION_ID, DEVICE_TYPE); Assert.assertTrue(notificationManagementService.addNotification(testDeviceIdentifier, notification)); } try { notificationManagementService.addNotification(new DeviceIdentifier(DEVICE_ID_PREFIX + 123, DEVICE_TYPE), notification); Assert.fail(); } catch (EntityDoesNotExistException ignored) { } }

Target:
public void addNotification() throws NotificationManagementException { for (int i = 1; i <= NO_OF_DEVICES; i++) { DeviceIdentifier testDeviceIdentifier = new DeviceIdentifier(DEVICE_ID_PREFIX + i, DEVICE_TYPE); Notification notification = TestDataHolder.getNotification(i, Notification.Status.NEW.toString(), testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + i, NOTIFICATION_OPERATION_ID, DEVICE_TYPE); Assert.assertTrue(notificationManagementService.addNotification(testDeviceIdentifier, notification)); } }
Source:
public void testGetById(){ StorageDevice storageDevice = dao.getById(EXISTING_STORAGE_DEVICE_ID_1); assertNotNull("Failed to retrive storage device", storageDevice); assertEquals("Failed to retrive corrective storage device", storageDevice.getId(), EXISTING_STORAGE_DEVICE_ID_1); storageDevice = dao.getById(NON_EXISTING_STORAGE_DEVICE_ID); assertNull(storageDevice); }

Target:
public void testGetById(){ StorageDevice storageDevice = dao.getById(EXISTING_STORAGE_DEVICE_ID_1); assertNotNull("Failed to retrive storage device", storageDevice); assertEquals("Failed to retrive corrective storage device", EXISTING_STORAGE_DEVICE_ID_1, storageDevice.getId()); storageDevice = dao.getById(NON_EXISTING_STORAGE_DEVICE_ID); assertNull(storageDevice); }
Source:
private static SrlBankProblem extractBankProblem(final DBObject dbObject, final String problemBankId, final boolean isAdmin) { final SrlBankProblem.Builder exactProblem = SrlBankProblem.newBuilder(); exactProblem.setId(problemBankId); exactProblem.setQuestionText((String) dbObject.get(QUESTION_TEXT)); if (isAdmin) { exactProblem.setSolutionId((String) dbObject.get(SOLUTION_ID)); } exactProblem.setCourseTopic((String) dbObject.get(COURSE_TOPIC)); exactProblem.setSubTopic((String) dbObject.get(SUB_TOPIC)); exactProblem.setSource((String) dbObject.get(SOURCE)); exactProblem.setQuestionType(Util.QuestionType.valueOf((Integer) dbObject.get(QUESTION_TYPE))); try { if (dbObject.containsField(DatabaseStringConstants.SPECIAL_QUESTION_DATA)) { exactProblem.setSpecialQuestionData( SlideManager.createElementFromQuery((DBObject) dbObject.get(DatabaseStringConstants.SPECIAL_QUESTION_DATA))); } } catch (DatabaseAccessException e) { LOG.error("Error parsing lecture element", e); e.printStackTrace(); } exactProblem.addAllOtherKeywords((ArrayList) dbObject.get(KEYWORDS)); if (dbObject.get(SCRIPT) != null) { exactProblem.setScript((String) dbObject.get(SCRIPT)); } return exactProblem.build(); }

Target:
private static SrlBankProblem extractBankProblem(final DBObject dbObject, final String problemBankId, final boolean isAdmin) { final SrlBankProblem.Builder exactProblem = SrlBankProblem.newBuilder(); exactProblem.setId(problemBankId); exactProblem.setQuestionText((String) dbObject.get(QUESTION_TEXT)); if (isAdmin) { exactProblem.setSolutionId((String) dbObject.get(SOLUTION_ID)); } exactProblem.setCourseTopic((String) dbObject.get(COURSE_TOPIC)); exactProblem.setSubTopic((String) dbObject.get(SUB_TOPIC)); exactProblem.setSource((String) dbObject.get(SOURCE)); exactProblem.setQuestionType(Util.QuestionType.valueOf((Integer) dbObject.get(QUESTION_TYPE))); try { if (dbObject.containsField(DatabaseStringConstants.SPECIAL_QUESTION_DATA)) { exactProblem.setSpecialQuestionData( SlideManager.createElementFromQuery((DBObject) dbObject.get(DatabaseStringConstants.SPECIAL_QUESTION_DATA))); } } catch (DatabaseAccessException e) { LOG.error("Error parsing lecture element", e); } exactProblem.addAllOtherKeywords((ArrayList) dbObject.get(KEYWORDS)); if (dbObject.get(SCRIPT) != null) { exactProblem.setScript((String) dbObject.get(SCRIPT)); } return exactProblem.build(); }
Source:
private void setupAttribution() { Page page = parentFragment.getPage(); pageLicenseText.setText(Html.fromHtml(activity.getString(R.string.content_license_html))); pageLicenseText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); if (page.isMainPage() || page.isFilePage()) { pageLastUpdatedText.setVisibility(View.GONE); } else { String lastUpdatedHtml = "<a href=\"" + page.getTitle().getUriForAction("history") + "\">" + activity.getString(R.string.last_updated_text, formatDateRelative(page.getPageProperties().getLastModified()) + "</a>"); String discussionHtml = "<a href=\"" + page.getTitle().getPrefixedUri("Talk") + "\">" + activity.getString(R.string.talk_page_link_text) + "</a>"; pageLastUpdatedText.setText(Html.fromHtml(lastUpdatedHtml + " -- " + discussionHtml)); pageLastUpdatedText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); pageLastUpdatedText.setVisibility(View.VISIBLE); } }

Target:
private void setupAttribution() { Page page = parentFragment.getPage(); pageLicenseText.setText(Html.fromHtml(activity.getString(R.string.content_license_html))); pageLicenseText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); if (page.isMainPage() || page.isFilePage()) { pageLastUpdatedText.setVisibility(View.GONE); } else { String lastUpdatedHtml = "<a href=\"" + page.getTitle().getUriForAction("history") + "\">" + activity.getString(R.string.last_updated_text, formatDateRelative(page.getPageProperties().getLastModified()) + "</a>"); String discussionHtml = "<a href=\"" + page.getTitle().getPrefixedUri("Talk") + "\">" + activity.getString(R.string.talk_page_link_text) + "</a>"; pageLastUpdatedText.setText(Html.fromHtml(lastUpdatedHtml + " &mdash; " + discussionHtml)); pageLastUpdatedText.setMovementMethod(new LinkMovementMethodExt(linkHandler)); pageLastUpdatedText.setVisibility(View.VISIBLE); } }
Source:
public void onReceive(Context context, Intent intent) { String command = intent.getStringExtra(COMMAND); List<String> supportedCommands = Arrays.asList(COMMAND_ENABLE, COMMAND_DISABLE); if (!supportedCommands.contains(command)) { Log.e(TAG, String.format("Cannot identify the command [%s]", command)); setResultCode(Activity.RESULT_CANCELED); return; } boolean isSuccessful; AbstractSettingHandler handler = getHandler(context); if (handler == null) { setResultCode(Activity.RESULT_CANCELED); return; } if (command.equals(COMMAND_ENABLE)) { isSuccessful = getHandler(context).enable(); } else { isSuccessful = getHandler(context).disable(); } setResultCode(isSuccessful ? Activity.RESULT_OK : Activity.RESULT_CANCELED); }

Target:
public void onReceive(Context context, Intent intent) { String command = intent.getStringExtra(COMMAND); List<String> supportedCommands = Arrays.asList(COMMAND_ENABLE, COMMAND_DISABLE); if (!supportedCommands.contains(command)) { Log.e(TAG, String.format("Cannot identify the command [%s]", command)); setResultCode(Activity.RESULT_CANCELED); return; } boolean isSuccessful; AbstractSettingHandler handler = getHandler(context); if (handler == null) { setResultCode(Activity.RESULT_CANCELED); return; } if (command.equals(COMMAND_ENABLE)) { isSuccessful = handler.enable(); } else { isSuccessful = handler.disable(); } setResultCode(isSuccessful ? Activity.RESULT_OK : Activity.RESULT_CANCELED); }
Source:
private void initializeNetworkList() { AsyncDataProvider.getInstance().getAllDataCenterNetworks(new AsyncQuery<>(networks -> { Set<Guid> iscsiBonded = isBondExist() ? new HashSet<>(getIscsiBond().getNetworkIds()) : Collections.emptySet(); List<Network> selected = networks.stream().filter(n -> iscsiBonded.contains(n.getId())).collect(Collectors.toList()); networks = networks.stream().filter(n -> !n.isExternal()).collect(Collectors.toList()); filterNonRequiredNetworks(networks, selected); }), getStoragePool().getId()); }

Target:
private void initializeNetworkList() { AsyncDataProvider.getInstance().getAllDataCenterNetworks(new AsyncQuery<>(networks -> { Set<Guid> iscsiBonded = isBondExist() ? new HashSet<>(getIscsiBond().getNetworkIds()) : Collections.emptySet(); networks = networks.stream().filter(n -> !n.isExternal()).collect(Collectors.toList()); List<Network> selected = networks.stream().filter(n -> iscsiBonded.contains(n.getId())).collect(Collectors.toList()); filterNonRequiredNetworks(networks, selected); }), getStoragePool().getId()); }
Source:
public void reInitSysProc(CatalogContext catalogContext, CatalogSpecificPlanner csp) { assert(m_procedure != null); if (! m_isSysProc) { return; } assert(m_procedure instanceof VoltSystemProcedure); ((VoltSystemProcedure) m_procedure).initSysProc(m_site, catalogContext.cluster, catalogContext.getClusterSettings(), catalogContext.getNodeSettings()); m_csp = csp; }

Target:
public void reInitSysProc(CatalogContext catalogContext, CatalogSpecificPlanner csp) { assert(m_procedure != null); if (! m_isSysProc) { return; } ((VoltSystemProcedure) m_procedure).initSysProc(m_site, catalogContext.cluster, catalogContext.getClusterSettings(), catalogContext.getNodeSettings()); m_csp = csp; }
Source:
public FluoConfiguration resolveFluoConfiguration(String appName) { try { return getAppConfiguration(appName); } catch (FluoException e) { FluoConfiguration config = new FluoConfiguration(getFluoConfiguration()); config.setApplicationName(appName); return config; } }

Target:
public FluoConfiguration resolveFluoConfiguration(String appName) { return resolveFluoConfiguration(appName, true); }
Source:
public static String formatRequest(String url, Position position, String alarm) { Uri serverUrl = Uri.parse(url); Uri.Builder builder = serverUrl.buildUpon() .appendQueryParameter("id", position.getDeviceId()) .appendQueryParameter("timestamp", String.valueOf(position.getTime().getTime() / 1000)) .appendQueryParameter("lat", String.valueOf(position.getLatitude())) .appendQueryParameter("lon", String.valueOf(position.getLongitude())) .appendQueryParameter("speed", String.valueOf(position.getSpeed())) .appendQueryParameter("bearing", String.valueOf(position.getCourse())) .appendQueryParameter("altitude", String.valueOf(position.getAltitude())) .appendQueryParameter("accuracy", String.valueOf(position.getAccuracy())) .appendQueryParameter("batt", String.valueOf(position.getBattery())) .appendQueryParameter("mock", String.valueOf(position.getMock())); if (alarm != null) { builder.appendQueryParameter("alarm", alarm); } return builder.build().toString(); }

Target:
public static String formatRequest(String url, Position position, String alarm) { Uri serverUrl = Uri.parse(url); Uri.Builder builder = serverUrl.buildUpon() .appendQueryParameter("id", position.getDeviceId()) .appendQueryParameter("timestamp", String.valueOf(position.getTime().getTime() / 1000)) .appendQueryParameter("lat", String.valueOf(position.getLatitude())) .appendQueryParameter("lon", String.valueOf(position.getLongitude())) .appendQueryParameter("speed", String.valueOf(position.getSpeed())) .appendQueryParameter("bearing", String.valueOf(position.getCourse())) .appendQueryParameter("altitude", String.valueOf(position.getAltitude())) .appendQueryParameter("accuracy", String.valueOf(position.getAccuracy())) .appendQueryParameter("batt", String.valueOf(position.getBattery())); if (position.getMock()) { builder.appendQueryParameter("mock", String.valueOf(position.getMock())); } if (alarm != null) { builder.appendQueryParameter("alarm", alarm); } return builder.build().toString(); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scratch_project_details); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setUpActionBar(); programData = getIntent().getParcelableExtra(Constants.INTENT_SCRATCH_PROGRAM_DATA); Preconditions.checkState(programData != null); if (conversionManager.isJobInProgress(programData.getId())) { onJobInProgress(); } else if (conversionManager.isJobDownloading(programData.getId())) { onJobDownloading(); } else { onJobNotInProgress(); } conversionManager.addJobViewListener(programData.getId(), this); conversionManager.addGlobalDownloadCallback(this); final Activity activity = this; findViewById(R.id.scratch_project_convert_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int numberOfJobsInProgress = conversionManager.getNumberOfJobsInProgress(); if (numberOfJobsInProgress >= Constants.SCRATCH_CONVERTER_MAX_NUMBER_OF_JOBS_PER_CLIENT) { ToastUtil.showError(activity, getResources().getQuantityString( R.plurals.error_cannot_convert_more_than_x_programs, Constants.SCRATCH_CONVERTER_MAX_NUMBER_OF_JOBS_PER_CLIENT, Constants.SCRATCH_CONVERTER_MAX_NUMBER_OF_JOBS_PER_CLIENT)); return; } onJobInProgress(); Intent intent = new Intent(); intent.putExtra(Constants.INTENT_SCRATCH_PROGRAM_DATA, (Parcelable) programData); setResult(RESULT_OK, intent); finish(); } }); loadAdditionalData(programData); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scratch_project_details); setUpActionBar(); programData = getIntent().getParcelableExtra(Constants.INTENT_SCRATCH_PROGRAM_DATA); Preconditions.checkState(programData != null); if (conversionManager.isJobInProgress(programData.getId())) { onJobInProgress(); } else if (conversionManager.isJobDownloading(programData.getId())) { onJobDownloading(); } else { onJobNotInProgress(); } conversionManager.addJobViewListener(programData.getId(), this); conversionManager.addGlobalDownloadCallback(this); findViewById(R.id.scratch_project_convert_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int numberOfJobsInProgress = conversionManager.getNumberOfJobsInProgress(); if (numberOfJobsInProgress >= Constants.SCRATCH_CONVERTER_MAX_NUMBER_OF_JOBS_PER_CLIENT) { ToastUtil.showError(getContext(), getResources().getQuantityString( R.plurals.error_cannot_convert_more_than_x_programs, Constants.SCRATCH_CONVERTER_MAX_NUMBER_OF_JOBS_PER_CLIENT, Constants.SCRATCH_CONVERTER_MAX_NUMBER_OF_JOBS_PER_CLIENT)); return; } onJobInProgress(); Intent intent = new Intent(); intent.putExtra(Constants.INTENT_SCRATCH_PROGRAM_DATA, (Parcelable) programData); setResult(RESULT_OK, intent); finish(); } }); loadAdditionalData(programData); }
Source:
protected Object handleRequestMessage(Message<?> requestMessage) { Object query = this.queryExpression.getValue(this.evaluationContext, requestMessage); Assert.notNull(query, "The twitter search query cannot evaluate to 'null'."); SearchParameters searchParameters; if (query instanceof SearchParameters) { searchParameters = (SearchParameters) query; } else if (query instanceof String) { int count = this.limitExpression.getValue(this.evaluationContext, requestMessage, Integer.class); searchParameters = new SearchParameters((String) query).count(count); } else { throw new IllegalArgumentException("Query must evaluate to a 'SearchParamters' or 'String'."); } SearchResults results = this.getTwitter().searchOperations().search(searchParameters); List<Tweet> tweets = (results != null) ? results.getTweets() : Collections.<Tweet>emptyList(); if (this.isRequiresReply() && (tweets == null || tweets.size() == 0)) { return null; } else { return this.getMessageBuilderFactory().withPayload(tweets) .setHeader(TwitterHeaders.SEARCH_METADATA, results.getSearchMetadata()); } }

Target:
protected Object handleRequestMessage(Message<?> requestMessage) { Object args = this.searchArgsExpression.getValue(this.evaluationContext, requestMessage); Assert.notNull(args, "The twitter search expression cannot evaluate to 'null'."); SearchParameters searchParameters; if (args instanceof SearchParameters) { searchParameters = (SearchParameters) args; } else if (args instanceof String) { searchParameters = new SearchParameters((String) args).count(DEFAULT_PAGE_SIZE); } else if (args instanceof List) { List<?> list = (List<?>) args; Assert.isTrue(list.size() > 0 && list.size() < 5, "Between 1 and 4 search arguments are required"); Assert.isInstanceOf(String.class, list.get(0), "The first search argument (query) must be a String"); searchParameters = new SearchParameters((String) list.get(0)); if (list.size() > 1) { Assert.isInstanceOf(Number.class, list.get(1), "The second search argument (pageSize) must be a Number"); searchParameters.count(((Number) list.get(1)).intValue()); if (list.size() > 2) { Assert.isInstanceOf(Number.class, list.get(2), "The third search argument (sinceId) must be a Number"); searchParameters.sinceId(((Number) list.get(2)).longValue()); } if (list.size() > 3) { Assert.isInstanceOf(Number.class, list.get(3), "The fourth search argument (maxId) must be a Number"); searchParameters.maxId(((Number) list.get(3)).longValue()); } } } else { throw new IllegalArgumentException( "Search Expression must evaluate to a 'SearchParameters', 'String' or 'List'."); } SearchResults results = this.getTwitter().searchOperations().search(searchParameters); List<Tweet> tweets = (results != null) ? results.getTweets() : null; if (tweets == null) { tweets = Collections.<Tweet>emptyList(); } return this.getMessageBuilderFactory().withPayload(tweets) .setHeader(TwitterHeaders.SEARCH_METADATA, results.getSearchMetadata()); }
Source:
public void testLombokGeneratedAnnotation() { final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, Opcodes.ACC_SYNTHETIC, "lambda$1", "()V", null, null); m.visitInsn(Opcodes.NOP); m.visitInsn(Opcodes.RETURN); AnnotationNode a = new AnnotationNode("Llombok/Generated;"); m.invisibleAnnotations = Arrays.asList(a); filter.filter(m, this); assertEquals(m.instructions.getFirst(), fromInclusive); assertEquals(m.instructions.getLast(), toInclusive); }

Target:
public void testLombokGeneratedAnnotation() { final MethodNode m = new MethodNode(InstrSupport.ASM_API_VERSION, 0, "hashCode", "()I", null, null); m.visitAnnotation("Llombok/Generated;", false); m.visitInsn(Opcodes.ICONST_0); m.visitInsn(Opcodes.IRETURN); filter.filter(m, this); assertEquals(m.instructions.getFirst(), fromInclusive); assertEquals(m.instructions.getLast(), toInclusive); }
Source:
public static Matcher<Instant> isInstant( final int year, final int month, final int day, final int hour, final int minute, final int second) { Preconditions.checkArgument(month > 0 && month < 13); Preconditions.checkArgument(day > 0 && day < 32); Preconditions.checkArgument(hour >= 0 && hour < 24); Preconditions.checkArgument(minute >= 0 && minute < 60); Preconditions.checkArgument(second >= 0 && second < 60); return is( equalTo( Instant.parse( String.format( "%s-%s-%sT%s:%s:%sZ", StringUtils.leftPad(String.valueOf(year), 4, '0'), StringUtils.leftPad(String.valueOf(month), 2, '0'), StringUtils.leftPad(String.valueOf(day), 2, '0'), StringUtils.leftPad(String.valueOf(hour), 2, '0'), StringUtils.leftPad(String.valueOf(minute), 2, '0'), StringUtils.leftPad(String.valueOf(second), 2, '0'))))); }

Target:
public static Matcher<Instant> isInstant( final int year, final int month, final int day, final int hour, final int minute, final int second) { return is( equalTo( LocalDateTime.of(year, month, day, hour, minute, second).toInstant(ZoneOffset.UTC))); }
Source:
public void setUp() throws IOException { serverSocket = new ServerSocket(8030); }

Target:
public void setUp() throws IOException { serverSocket = new ServerSocket(port); }
Source:
public Void perform(Task task, TaskActionToolbox toolbox) throws IOException { TaskActionPreconditions.checkTaskLocks(task, toolbox.getTaskLockbox(), segments); toolbox.getIndexerMetadataStorageCoordinator().deleteSegments(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension(DruidMetrics.DATASOURCE, task.getDataSource()) .setDimension(DruidMetrics.TASK_TYPE, task.getType()); for (DataSegment segment : segments) { metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segment/nuked/bytes", segment.getSize())); } return null; }

Target:
public Void perform(Task task, TaskActionToolbox toolbox) throws IOException { TaskActionPreconditions.checkLockCoversSegments(task, toolbox.getTaskLockbox(), segments); final List<Interval> intervals = segments.stream().map(DataSegment::getInterval).collect(Collectors.toList()); try { toolbox.getTaskLockbox().doInCriticalSection( task, intervals, CriticalAction.builder() .onValidLocks( () -> { toolbox.getIndexerMetadataStorageCoordinator().deleteSegments(segments); return null; } ) .onInvalidLocks( () -> { throw new ISE("Some locks for task[%s] are already revoked", task.getId()); } ) .build() ); } catch (Exception e) { throw new RuntimeException(e); } final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension(DruidMetrics.DATASOURCE, task.getDataSource()) .setDimension(DruidMetrics.TASK_TYPE, task.getType()); for (DataSegment segment : segments) { metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segment/nuked/bytes", segment.getSize())); } return null; }
Source:
private Block[] getBlocksForType(Type type, int positionCount) throws IOException { RowType rowType = (RowType) type; Block[] blocks = new Block[rowType.getFields().size()]; for (int i = 0; i < rowType.getFields().size(); i++) { Optional<String> fieldName = rowType.getFields().get(i).getName(); Type fieldType = rowType.getFields().get(i).getType(); if (fieldName.isPresent() && structFields.containsKey(fieldName.get())) { StreamReader streamReader = structFields.get(fieldName.get()); streamReader.prepareNextRead(positionCount); blocks[i] = streamReader.readBlock(fieldType); } else { blocks[i] = getNullBlock(fieldType, positionCount); } } return blocks; }

Target:
private Block[] getBlocksForType(Type type, int positionCount) throws IOException { RowType rowType = (RowType) type; Block[] blocks = new Block[rowType.getFields().size()]; for (int i = 0; i < rowType.getFields().size(); i++) { Optional<String> fieldName = rowType.getFields().get(i).getName(); Type fieldType = rowType.getFields().get(i).getType(); if (!fieldName.isPresent()) { throw new IllegalArgumentException("Missing struct field name in type " + rowType); } String lowerCaseFieldName = fieldName.get().toLowerCase(Locale.ENGLISH); StreamReader streamReader = structFields.get(lowerCaseFieldName); if (streamReader != null) { streamReader.prepareNextRead(positionCount); blocks[i] = streamReader.readBlock(fieldType); } else { blocks[i] = getNullBlock(fieldType, positionCount); } } return blocks; }
Source:
private boolean processFetchResponse(FetchResponse fetchResponse, long tempTime) { try { ByteBufferMessageSet messageBuffer = fetchResponse.messageSet(kafkaRequest.getTopic(), kafkaRequest.getPartition()); lastFetchTime = (System.currentTimeMillis() - tempTime); log.debug("Time taken to fetch : " + (lastFetchTime / 1000) + " seconds"); log.debug("The size of the ByteBufferMessageSet returned is : " + messageBuffer.sizeInBytes()); int skipped = 0; totalFetchTime += lastFetchTime; messageIter = messageBuffer.iterator(); Iterator<MessageAndOffset> messageIter2 = messageBuffer.iterator(); MessageAndOffset message = null; while (messageIter2.hasNext()) { message = messageIter2.next(); if (message.offset() < currentOffset) { skipped++; } else { log.debug("Skipped offsets till : " + message.offset()); break; } } log.debug("Number of offsets to be skipped: " + skipped); while (skipped != 0) { MessageAndOffset skippedMessage = messageIter.next(); log.debug("Skipping offset : " + skippedMessage.offset()); skipped--; } if (!messageIter.hasNext()) { System.out.println("No more data left to process. Returning false"); messageIter = null; return false; } return true; } catch (Exception e) { log.info("Exception generated during processing fetchResponse"); e.printStackTrace(); return false; } }

Target:
private boolean processFetchResponse(FetchResponse fetchResponse, long tempTime) { try { ByteBufferMessageSet messageBuffer = fetchResponse.messageSet(kafkaRequest.getTopic(), kafkaRequest.getPartition()); lastFetchTime = (System.currentTimeMillis() - tempTime); log.debug("Time taken to fetch : " + (lastFetchTime / 1000) + " seconds"); log.debug("The size of the ByteBufferMessageSet returned is : " + messageBuffer.sizeInBytes()); int skipped = 0; totalFetchTime += lastFetchTime; messageIter = messageBuffer.iterator(); Iterator<MessageAndOffset> messageIter2 = messageBuffer.iterator(); MessageAndOffset message = null; while (messageIter2.hasNext()) { message = messageIter2.next(); if (message.offset() < currentOffset) { skipped++; } else { log.debug("Skipped offsets till : " + message.offset()); break; } } log.debug("Number of offsets to be skipped: " + skipped); while (skipped != 0) { MessageAndOffset skippedMessage = messageIter.next(); log.debug("Skipping offset : " + skippedMessage.offset()); skipped--; } if (!messageIter.hasNext()) { System.out.println("No more data left to process. Returning false"); messageIter = null; return false; } return true; } catch (Exception e) { log.info("Exception generated during processing fetchResponse"); return false; } }