auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean onShutdown(long timeout, TimeUnit unit) { if (nodeEngine.getLocalMember().isLiteMember()) { return true; } long timeoutNanos = unit.toNanos(timeout); for (CRDTReplicationAwareService service : getReplicationServices()) { service.prepareToSafeShutdown(); final CRDTReplicationContainer replicationOperation = service.prepareReplicationOperation( replicationVectorClocks.getLatestReplicatedVectorClock(service.getName()), 0); if (replicationOperation == null) { logger.fine("Skipping replication since all CRDTs are replicated"); continue; } long startNanos = Timer.nanos(); if (!tryProcessOnOtherMembers(replicationOperation.getOperation(), service.getName(), timeoutNanos)) { logger.warning("Failed replication of CRDTs for " + service.getName() + ". CRDT state may be lost."); } timeoutNanos -= Timer.nanosElapsed(startNanos); if (timeoutNanos < 0) { return false; } } return true; }

Target:
public boolean onShutdown(long timeout, TimeUnit unit) { if (nodeEngine.getLocalMember().isLiteMember()) { return true; } long timeoutNanos = unit.toNanos(timeout); for (CRDTReplicationAwareService service : getReplicationServices()) { service.prepareToSafeShutdown(); final CRDTReplicationContainer replicationOperation = service.prepareReplicationOperation( replicationVectorClocks.getLatestReplicatedVectorClock(service.getName()), 0); if (replicationOperation == null) { logger.fine("Skipping replication since all CRDTs are replicated"); continue; } long start = System.nanoTime(); if (!tryProcessOnOtherMembers(replicationOperation.getOperation(), service.getName(), timeoutNanos)) { logger.warning("Failed replication of CRDTs for " + service.getName() + ". CRDT state may be lost."); } timeoutNanos -= (System.nanoTime() - start); if (timeoutNanos < 0) { return false; } } return true; }
Source:
public GeoserveRegionsService(final String endpointUrl, final int connectTimeout, final int readTimeout) { this.endpointUrl = endpointUrl; this.connectTimeout = connectTimeout; this.readTimeout = readTimeout; }

Target:
public GeoserveRegionsService(final String endpointUrl, final int connectTimeout, final int readTimeout) { this.setEndpointURL(endpointUrl); this.setConnectTimeout(connectTimeout); this.setReadTimeout(readTimeout); }
Source:
public IfTttDaemon(final AlarmDao alarmDao, final TransactionOperations transactionOperations) { this.m_alarmDao = alarmDao; this.m_transactionOperations = transactionOperations; this.m_fileReloadContainer = new FileReloadContainer<>(ifTttConfigFile, (object, resource) -> { LOG.debug("Reloading configuration file {}.", resource.getFilename()); return JaxbUtils.unmarshal(IfTttConfig.class, ifTttConfigFile); }); }

Target:
public IfTttDaemon(final AlarmDao alarmDao, final TransactionOperations transactionOperations) { this(alarmDao, transactionOperations, Paths.get(System.getProperty("opennms.home", ""), "etc", "ifttt-config.xml").toFile()); }
Source:
private void doUsfmImportUri(Uri uri) { String path = uri.toString(); String ext = FilenameUtils.getExtension(path).toLowerCase(); boolean tstudio = ext.equalsIgnoreCase(Translator.ARCHIVE_EXTENSION); if (tstudio) { importUri(uri); } else { ImportUsfmActivity.startActivityForUriImport(getActivity(), uri); } }

Target:
private void doUsfmImportUri(Uri uri) { String path = uri.toString(); String ext = FilenameUtils.getExtension(path).toLowerCase(); ImportUsfmActivity.startActivityForUriImport(getActivity(), uri); }
Source:
boolean isPushingSection( OSMWay way ) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return way.hasTag("highway", pushingSections) || way.hasTag("railway", "platform") || way.hasTag("bicycle", "dismount") || "track".equals(highway) && trackType != null && !"grade1".equals(trackType); }

Target:
boolean isPushingSection( OSMWay way ) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return super.isPushingSection(way) || "track".equals(highway) && trackType != null && !"grade1".equals(trackType); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ModuleMetadata other = (ModuleMetadata) obj; return Objects.equals(id, other.id) && Objects.equals(version, other.version) && Objects.equals(displayName, other.displayName) && Objects.equals(description, other.description) && Objects.equals(requiredPermissions, other.requiredPermissions) && Objects.equals(dependencies, other.dependencies) && Objects.equals(extensions, other.extensions); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ModuleMetadata) { ModuleMetadata other = (ModuleMetadata) obj; return Objects.equals(id, other.id) && Objects.equals(version, other.version) && Objects.equals(displayName, other.displayName) && Objects.equals(description, other.description) && Objects.equals(requiredPermissions, other.requiredPermissions) && Objects.equals(dependencies, other.dependencies) && Objects.equals(extensions, other.extensions); } return false; }
Source:
public Transceiver read(final String journal, final String parentArg) throws IOException { return new Transceiver() { @Override protected Calendar getLastModifiedDate() throws IOException { return null; } @Override protected Object getData() throws IOException { String parent = parentArg; CategoryView categoryView; try { categoryView = legacyTaxonomyService.parseCategories(journal); } catch (ApplicationException e) { throw new RuntimeException(e); } if (parent == null) { parent = ""; } else { String[] levels = parent.split("/"); for (String level : levels) { categoryView = categoryView.getChild(level); } if (parent.charAt(0) != '/') { parent = '/' + parent; } } Map<String, Long> articleCounts; try { articleCounts = legacyTaxonomyService.getCounts(categoryView, journal); } catch (ApplicationException e) { throw new IOException(e); } Map<String, SortedSet<String>> tree = CategoryUtils.getShortTree(categoryView); List<Result> results = new ArrayList<>(tree.size()); for (Map.Entry<String, SortedSet<String>> entry : tree.entrySet()) { long articleCount = articleCounts.get(entry.getKey()); results.add(new Result(parent + '/' + entry.getKey(), entry.getValue().size(), articleCount)); } Collections.sort(results); return results; } }; }

Target:
public Transceiver read(final String journal, final String parentArg) throws IOException { return new Transceiver() { @Override protected Calendar getLastModifiedDate() throws IOException { return null; } @Override protected Object getData() throws IOException { String parent = parentArg; CategoryView categoryView; try { categoryView = legacyTaxonomyService.parseCategories(journal); } catch (ApplicationException e) { throw new RuntimeException(e); } if (parent == null) { parent = ""; } else { String[] levels = parent.split("/"); for (String level : levels) { categoryView = categoryView.getChild(level); } if (parent.charAt(0) != '/') { parent = '/' + parent; } } Map<String, Long> articleCounts; try { articleCounts = legacyTaxonomyService.getCounts(categoryView, journal); } catch (ApplicationException e) { throw new IOException(e); } Map<String, SortedSet<String>> tree = CategoryUtils.getShortTree(categoryView); List<Result> results = new ArrayList<>(tree.size()); for (Map.Entry<String, SortedSet<String>> entry : tree.entrySet()) { String subject = parent + '/' + entry.getKey(); int childCount = entry.getValue().size(); long articleCount = articleCounts.get(entry.getKey()); results.add(new Result(subject, childCount, articleCount)); } Collections.sort(results); return results; } }; }
Source:
private V1NetworkAttachmentDefinitionList getKubevirtNetworks(ApiClient client, Guid clusterId) { K8sCniCncfIoV1Api cniApi = new K8sCniCncfIoV1Api(client); try { return cniApi.listV1NetworkAttachmentDefinitionForAllNamespaces(null, null, null, null, null, null, null, null, Boolean.FALSE); } catch (ApiException e) { KubevirtUtils.auditAuthorizationIssues(e, auditLogDirector, clusterId, providerDao); log.error("Failed to communicate with kubevirt cluster " + clusterId + " due to: " + e.getMessage()); log.debug("Exception", e); return null; } }

Target:
private V1NetworkAttachmentDefinitionList getKubevirtNetworks(ApiClient client, Guid clusterId) { K8sCniCncfIoV1Api cniApi = new K8sCniCncfIoV1Api(client); try { return cniApi.listV1NetworkAttachmentDefinitionForAllNamespaces(null, null, null, null, null, null, null, null, Boolean.FALSE); } catch (ApiException e) { handleException(e, clusterId); return null; } }
Source:
public <T> void forEachAnnotation(AnnotationConsumer<T> annotationConsumer, T target) { for (int i = 0, length = pairs.size(); i < length; i += 2) { Object first = pairs.get(i); if (first instanceof String) continue; annotationConsumer.accept(target, (Long) first, pairs.get(i + 1).toString()); } }

Target:
public <T> void forEachAnnotation(AnnotationConsumer<T> annotationConsumer, T target) { if (annotations == null) return; for (int i = 0, length = annotations.size(); i < length; i += 2) { long timestamp = (long) annotations.get(i); annotationConsumer.accept(target, timestamp, annotations.get(i + 1).toString()); } }
Source:
private static void initMessages() { Map<String, String> messages = readMessagesFromBundle(); for (Entry<String, String> message : messages.entrySet()) { try { AuditLogType type = AuditLogType.valueOf(message.getKey()); if (!mMessages.containsKey(type)) { mMessages.put(type, message.getValue()); } else { log.errorFormat("The type {0} appears more then once in audit log messages bundle with the values '{0}' and '{1}'", mMessages.get(type), message.getValue()); } } catch (Exception e) { log.errorFormat("Cannot convert the string {0} to AuditLogType, the key does not exist in the AuditLogType declared types", message.getKey()); } } checkMessages(); }

Target:
private static void initMessages() { ResourceBundle bundle = readMessagesFromBundle(); for (String key : bundle.keySet()) { try { AuditLogType type = AuditLogType.valueOf(key); if (!messages.containsKey(type)) { messages.put(type, bundle.getString(key)); } else { log.errorFormat("The type {0} appears more then once in audit log messages bundle with the values '{1}' and '{2}'", messages.get(type), bundle.getString(key)); } } catch (Exception e) { log.errorFormat("Cannot convert the string {0} to AuditLogType, the key does not exist in the AuditLogType declared types", bundle.getString(key)); } } checkMessages(); }
Source:
private static void checkRetentionStrategy(EC2RetentionStrategy rs, EC2Computer c) throws InterruptedException { rs.check(c); EC2AbstractSlave node = c.getNode(); while (node.terminateScheduled) Thread.sleep(TimeUnit.SECONDS.toMillis(1)); }

Target:
private static void checkRetentionStrategy(EC2RetentionStrategy rs, EC2Computer c) throws InterruptedException { rs.check(c); EC2AbstractSlave node = c.getNode(); assertTrue(node.terminateScheduled.await(10, TimeUnit.SECONDS)); }
Source:
public JsonObject json() throws IOException { final XML hook = this.storage.xml().nodes( String.format( " this.coords, this.num ) ).get(0); final JsonArrayBuilder events = Json.createArrayBuilder(); for (final XML event : hook.nodes("events/child::*")) { events.add(event.xpath("name()").get(0)); } final JsonObjectBuilder configs = Json.createObjectBuilder(); for (final XML config : hook.nodes("configs/child::*")) { configs.add( config.xpath("name()").get(0), config.xpath("text()").get(0) ); } return Json.createObjectBuilder() .add("id", this.number()) .add("url", hook.xpath("url/text()").get(0)) .add("test_url", hook.xpath("test_url/text()").get(0)) .add("ping_url", hook.xpath("ping_url/text()").get(0)) .add("name", hook.xpath("name/text()").get(0)) .add("events", events) .add( "active", Boolean.parseBoolean(hook.xpath("active/text()").get(0)) ).add("config", configs) .add("updated_at", hook.xpath("updated_at/text()").get(0)) .add("created_at", hook.xpath("created_at/text()").get(0)) .build(); }

Target:
public JsonObject json() throws IOException { return new JsonNode( this.storage.xml().nodes( String.format( " this.repo().coordinates(), this.number() ) ).get(0) ).json(); }
Source:
public void testInvalidTopicDirNegative() { String topic = "a.b.c.d"; String topicDir = "${-1}-${2}-${3}-${4}"; properties.put( HdfsSinkConnectorConfig.TOPIC_REGEX_CAPTURE_GROUP_CONFIG, "([a-z])\\.([a-z])\\.([a-z])\\.([a-z])" ); properties.put(StorageCommonConfig.TOPICS_DIR_CONFIG, topicDir); connectorConfig = new HdfsSinkConnectorConfig(properties); connectorConfig.getTopicsDirFromTopic(topic); }

Target:
public void testInvalidTopicDirNegative() { String topic = "a.b.c.d"; String topicDir = "${-1}-${2}-${3}-${4}"; properties.put( HdfsSinkConnectorConfig.TOPIC_CAPTURE_GROUPS_REGEX_CONFIG, "([a-z])\\.([a-z])\\.([a-z])\\.([a-z])" ); properties.put(StorageCommonConfig.TOPICS_DIR_CONFIG, topicDir); connectorConfig = new HdfsSinkConnectorConfig(properties); connectorConfig.getTopicsDirFromTopic(topic); }
Source:
public void run() { long currentTime = System.currentTimeMillis(); long endTime = currentTime + (eventTime * 1000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(5000); } catch (InterruptedException e) { return; } } isComplete = true; completed(); }

Target:
public void run() { long currentTime = System.currentTimeMillis(); long endTime = currentTime + (eventTime * 1000); while (System.currentTimeMillis() < endTime) { try { Thread.sleep(1000); } catch (InterruptedException e) { return; } } isComplete = true; completed(); }
Source:
public RelOptPredicateList getAllFilterPredicates(RelNode rel, RelMetadataQuery mq, RexNode pred) { final RelNode input = rel.getInput(0); final RexBuilder rexBuilder = rel.getCluster().getRexBuilder(); final RelOptPredicateList predsBelow = mq.getAllPredicates(input); if (predsBelow == null) { return null; } final Set<RelDataTypeField> inputExtraFields = new LinkedHashSet<>(); final RelOptUtil.InputFinder inputFinder = new RelOptUtil.InputFinder(inputExtraFields); pred.accept(inputFinder); final ImmutableBitSet inputFieldsUsed = inputFinder.build(); final Map<RexInputRef, Set<RexNode>> mapping = new LinkedHashMap<>(); for (int idx : inputFieldsUsed) { final RexInputRef ref = RexInputRef.of(idx, rel.getRowType().getFieldList()); final Set<RexNode> originalExprs = mq.getExpressionLineage(rel, ref); if (originalExprs == null) { return null; } mapping.put(ref, originalExprs); } final Set<RexNode> allExprs = RelMdExpressionLineage.createAllPossibleExpressions(rexBuilder, pred, mapping); if (allExprs == null) { return null; } return predsBelow.union(rexBuilder, RelOptPredicateList.of(rexBuilder, allExprs)); }

Target:
private RelOptPredicateList getAllFilterPredicates(RelNode rel, RelMetadataQuery mq, RexNode pred) { final RexBuilder rexBuilder = rel.getCluster().getRexBuilder(); final RelOptPredicateList predsBelow = mq.getAllPredicates(rel); if (predsBelow == null) { return null; } final Set<RelDataTypeField> inputExtraFields = new LinkedHashSet<>(); final RelOptUtil.InputFinder inputFinder = new RelOptUtil.InputFinder(inputExtraFields); pred.accept(inputFinder); final ImmutableBitSet inputFieldsUsed = inputFinder.build(); final Map<RexInputRef, Set<RexNode>> mapping = new LinkedHashMap<>(); for (int idx : inputFieldsUsed) { final RexInputRef ref = RexInputRef.of(idx, rel.getRowType().getFieldList()); final Set<RexNode> originalExprs = mq.getExpressionLineage(rel, ref); if (originalExprs == null) { return null; } mapping.put(ref, originalExprs); } final Set<RexNode> allExprs = RelMdExpressionLineage.createAllPossibleExpressions(rexBuilder, pred, mapping); if (allExprs == null) { return null; } return predsBelow.union(rexBuilder, RelOptPredicateList.of(rexBuilder, allExprs)); }
Source:
void updateSettingsPage() { assert connector != null; if (!connector.getConnectorKind().equals(lastConnectorKind)) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(connector.getConnectorKind()); settingsPage = connectorUi.getSettingsPage(null); if (settingsPage == null) { TasksUiInternal.displayFrameworkError(NLS.bind( "The connector implementation is incomplete: AbstractRepositoryConnectorUi.getSettingsPage() for connector ''{0}'' returned null. Please contact the vendor of the connector to resolve the problem.", connector.getConnectorKind())); } settingsPage.setWizard(this); lastConnectorKind = connector.getConnectorKind(); } if (settingsPage instanceof AbstractRepositorySettingsPage) { ((AbstractRepositorySettingsPage) settingsPage).setBrand(brand); } }

Target:
void updateSettingsPage() { assert connector != null; if (!connector.getConnectorKind().equals(lastConnectorKind)) { AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(connector.getConnectorKind()); settingsPage = connectorUi.getSettingsPage(null); if (settingsPage == null) { TasksUiInternal.displayFrameworkError(NLS.bind( "The connector implementation is incomplete: AbstractRepositoryConnectorUi.getSettingsPage() for connector ''{0}'' returned null. Please contact the vendor of the connector to resolve the problem.", connector.getConnectorKind())); } settingsPage.setWizard(this); lastConnectorKind = connector.getConnectorKind(); } if (settingsPage instanceof AbstractRepositorySettingsPage) { ((AbstractRepositorySettingsPage) settingsPage).setBrand(Strings.nullToEmpty(brand)); } }
Source:
public CodeBlock wrapWithErrorHandling( CodeBlock innerBlock, ExecutableElement methodElement, Map<Name, TypeElement> typeParameters) { TypeName returnTypeName = GeneratedCodePatterns.getTypeName(methodElement.getReturnType(), typeParameters); CodeBlock.Builder callWrapError = CodeBlock.builder() .beginControlFlow("try") .addStatement( "@$1T(\"unchecked\") $2T result =\n($2T) producer.wrapError(e)", SuppressWarnings.class, returnTypeName) .addStatement("return result"); for (TypeMirror thrownType : methodElement.getThrownTypes()) { callWrapError.nextControlFlow("catch ($T e2)", thrownType).addStatement("throw e2"); } callWrapError .nextControlFlow("catch ($T e2)", Exception.class) .addStatement("$T.throwIfUnchecked(e2)", Throwables.class) .addStatement("throw new $T(e2)", RuntimeException.class) .endControlFlow(); return wrapWithErrorHandling(innerBlock, callWrapError.build()); }

Target:
public CodeBlock wrapWithErrorHandling( CodeBlock innerBlock, ExecutableElement methodElement, Map<Name, TypeElement> typeParameters) { return innerBlock; }
Source:
void sendWriteRequest(int bookieIndex) { int flags = isRecoveryAdd ? BookieProtocol.FLAG_RECOVERY_ADD : BookieProtocol.FLAG_NONE; lh.bk.getBookieClient().addEntry(lh.metadata.currentEnsemble.get(bookieIndex), lh.ledgerId, lh.ledgerKey, entryId, toSend, this, bookieIndex, flags, lh.writeFlags); ++pendingWriteRequests; }

Target:
void sendWriteRequest(int bookieIndex) { int flags = isRecoveryAdd ? FLAG_RECOVERY_ADD | FLAG_HIGH_PRIORITY : FLAG_NONE; lh.bk.getBookieClient().addEntry(lh.metadata.currentEnsemble.get(bookieIndex), lh.ledgerId, lh.ledgerKey, entryId, toSend, this, bookieIndex, flags, allowFailFast, lh.writeFlags); ++pendingWriteRequests; }
Source:
private static String getPath(ITimeGraphPresentationProvider presentationProvider, StateItem stateItem) { String id = String.valueOf(presentationProvider.getPreferenceKey()); String stateName = stateItem.getStateString(); if (isLink(stateItem)) { return PREFIX + id + SEPARATOR + LINK + stateName; } return PREFIX + id + SEPARATOR + stateName; }

Target:
private static String getPath(ITimeGraphPresentationProvider presentationProvider, StateItem stateItem) { StringJoiner sj = new StringJoiner(SEPARATOR); sj.add(PREFIX + String.valueOf(presentationProvider.getPreferenceKey())); sj.add((String) getItemProperty(stateItem)); sj.add(stateItem.getStateString()); return sj.toString(); }
Source:
protected void run() throws UnloggedFailure { if (regex == null) { regex = "^*.*$"; } for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { Logger log = logger.nextElement(); if (log.getName().matches(regex)) { Level l = log.getEffectiveLevel(); stdout.println(log.getName() + " : " + l); } } }

Target:
protected void run() { if (regex == null) { regex = "^*.*$"; } for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { Logger log = logger.nextElement(); if (log.getName().matches(regex)) { Level l = log.getEffectiveLevel(); stdout.println(log.getName() + " : " + l); } } }
Source:
public boolean onCreateOptionsMenu(Menu menu) { MenuItem buttonSettings = menu.add(R.string.title_settings); buttonSettings.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); buttonSettings.setOnMenuItemClickListener(new MenuItem. OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Intent settingsIntent = new Intent(SummaryActivity.this, SettingsActivity.class); settingsIntent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, SettingsFragment.class.getName()); settingsIntent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true); SummaryActivity.this.startActivity(settingsIntent); return false; } }); MenuItem buttonSignout = menu.add(R.string.title_signout); buttonSignout.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); buttonSignout.setOnMenuItemClickListener(new MenuItem. OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { ApiInterface.getInstance().logOut(); Intent logOut = new Intent(SummaryActivity.this, LoginActivity.class); logOut.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(logOut); return false; } }); return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.items, menu); return super.onCreateOptionsMenu(menu); }
Source:
public static List<InstructorFeedbackResultsResponseRow> sortListWithDefaultOrder( List<InstructorFeedbackResultsResponseRow> responseRows) { responseRows.sort((InstructorFeedbackResultsResponseRow a1, InstructorFeedbackResultsResponseRow a2) -> { return ComparisonChain.start() .compare(a1.getGiverTeam(), a2.getGiverTeam()) .compare(a1.getGiverDisplayableIdentifier(), a2.getGiverDisplayableIdentifier()) .result(); }); return responseRows; }

Target:
public static List<InstructorFeedbackResultsResponseRow> sortListWithDefaultOrder( List<InstructorFeedbackResultsResponseRow> responseRows) { responseRows.sort(Comparator.comparing((InstructorFeedbackResultsResponseRow obj) -> obj.getGiverTeam()) .thenComparing(obj -> obj.getGiverDisplayableIdentifier())); return responseRows; }
Source:
public void selectDrawerItem(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.login_fragment: LoginFragment.newInstance(new LoginFragment.OnLoginLogoutListener() { @Override public void onLoginOrLogout(boolean status) { loginStatus = status; MenuItem item = nvDrawer.getMenu().findItem(R.id.login_fragment); if (loginStatus) item.setTitle("LOGOUT"); else item.setTitle("LOGIN"); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { } }).show(getSupportFragmentManager(), "Login_with_Facebook"); break; case R.id.profile_fragment: setContentFragment(new ProfileFragment()); break; case R.id.settings_fragment: showSettingsDialog(); break; } menuItem.setChecked(true); setTitle(menuItem.getTitle()); mDrawer.closeDrawers(); }

Target:
public void selectDrawerItem(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.login_fragment: new LoginFragment().show(getSupportFragmentManager(), "Login_with_Facebook"); break; case R.id.profile_fragment: setContentFragment(new ProfileFragment()); break; case R.id.settings_fragment: showSettingsDialog(); break; } menuItem.setChecked(true); setTitle(menuItem.getTitle()); mDrawer.closeDrawers(); }
Source:
public DataTransactionResult set(DataHolder dataHolder, GameModeData manipulator, MergeFunction function) { if (dataHolder instanceof EntityPlayerMP) { final GameMode oldMode = (GameMode) ((Object) ((EntityPlayerMP) dataHolder).theItemInWorldManager.getGameType()); final GameModeData oldData = from(dataHolder).get(); final ImmutableValue<GameMode> newMode = function.merge(oldData, manipulator).type().asImmutable(); try { ((EntityPlayerMP) dataHolder).setGameType((WorldSettings.GameType) ((Object) newMode.get())); return DataTransactionBuilder.successReplaceResult(ImmutableDataCachingUtil .getWildValue(ImmutableSpongeValue.class, Keys.GAME_MODE, oldMode, oldMode), newMode); } catch (Exception e) { return DataTransactionBuilder.errorResult(newMode); } } return DataTransactionBuilder.failResult(manipulator.getValues()); }

Target:
public DataTransactionResult set(DataHolder dataHolder, GameModeData manipulator, MergeFunction function) { checkNotNull(function, "MergeFunction cannot be null!"); if (dataHolder instanceof EntityPlayerMP) { final GameMode oldMode = (GameMode) (Object) ((EntityPlayerMP) dataHolder).theItemInWorldManager.getGameType(); final GameModeData oldData = from(dataHolder).get(); final ImmutableValue<GameMode> newMode = function.merge(oldData, manipulator).type().asImmutable(); try { ((EntityPlayerMP) dataHolder).setGameType((WorldSettings.GameType) (Object) newMode.get()); return DataTransactionBuilder.successReplaceResult(getGameModeValue(oldMode), newMode); } catch (Exception e) { return DataTransactionBuilder.errorResult(newMode); } } return DataTransactionBuilder.failResult(manipulator.getValues()); }
Source:
public BoundingBox getBoundingBox() { double width = wrapBoundaries.getWidth(); int numOfLines = 1; String[] words = textSupplier.get().split(" "); StringBuilder nextLine = new StringBuilder(words[0]); for (int i = 1; i < words.length; i++) { if (getBoundingBoxForString(nextLine + " " + words[i]).getWidth() <= wrapBoundaries.getWidth()) { nextLine.append(" ").append(words[i]); } else { nextLine.setLength(words[i].length()); nextLine.replace(0,words[i].length(),words[i]); numOfLines++; } } double height = getBoundingBoxForString(textSupplier.get()).getHeight(); height = height * numOfLines; return new BoundingBox().addX(0).addX(width).addY(0).addY(height); }

Target:
public BoundingBox getBoundingBox() { final String[] words = textSupplier.get().split(" "); if (words.length < 1) { return wrapBoundaries; } int numOfLines = 1; final double width = wrapBoundaries.getWidth(); final StringBuilder nextLine = new StringBuilder(words[0]); for (int i = 1; i < words.length; i++) { if (getBoundingBoxForString(nextLine + " " + words[i]).getWidth() <= wrapBoundaries.getWidth()) { nextLine.append(" ").append(words[i]); } else { nextLine.setLength(words[i].length()); nextLine.replace(0, words[i].length(), words[i]); numOfLines++; } } double height = getBoundingBoxForString(textSupplier.get()).getHeight(); height = height * numOfLines; return new BoundingBox().addX(0).addX(width).addY(0).addY(height); }
Source:
OpenState(CircuitBreakerStateMachine stateMachine, CircuitBreakerMetrics circuitBreakerMetrics) { super(stateMachine); this.retryAfterWaitDuration = Instant.now().plus(stateMachine.getCircuitBreakerConfig().getWaitDurationInOpenState()); this.circuitBreakerMetrics = circuitBreakerMetrics; if (stateMachine.getCircuitBreakerConfig().isAutomaticTransitionFromOpenToHalfOpenEnabled()) { OpenToHalfOpenAutoTransitioner.scheduleAutoTransitionToHalfOpen(stateMachine, this.retryAfterWaitDuration); } }

Target:
OpenState(CircuitBreakerStateMachine stateMachine, CircuitBreakerMetrics circuitBreakerMetrics) { super(stateMachine); final Duration waitDurationInOpenState = stateMachine.getCircuitBreakerConfig().getWaitDurationInOpenState(); this.retryAfterWaitDuration = Instant.now().plus(waitDurationInOpenState); this.circuitBreakerMetrics = circuitBreakerMetrics; if (stateMachine.getCircuitBreakerConfig().isAutomaticTransitionFromOpenToHalfOpenEnabled()) { AutoTransitioner.scheduleAutoTransition(stateMachine::transitionToHalfOpenState, waitDurationInOpenState); } }
Source:
private void init() { int autoStartVmsRunnerIntervalInSeconds = Config.<Integer>getValue(ConfigValues.AutoStartVmsRunnerIntervalInSeconds); SchedulerUtilQuartzImpl.getInstance().scheduleAFixedDelayJob( this, "startFailedAutoStartVms", new Class[] {}, new Object[] {}, autoStartVmsRunnerIntervalInSeconds, autoStartVmsRunnerIntervalInSeconds, TimeUnit.SECONDS); }

Target:
private void init() { int autoStartVmsRunnerIntervalInSeconds = Config.<Integer>getValue(ConfigValues.AutoStartVmsRunnerIntervalInSeconds); schedulerUtil.scheduleAFixedDelayJob( this, "startFailedAutoStartVms", new Class[] {}, new Object[] {}, autoStartVmsRunnerIntervalInSeconds, autoStartVmsRunnerIntervalInSeconds, TimeUnit.SECONDS); }
Source:
private ResourceGroupId selectGroup(QueryExecution queryExecution) { Session session = queryExecution.getSession(); SelectionContext context = new SelectionContext(session.getIdentity().getPrincipal().isPresent(), session.getUser(), session.getSource(), getQueryPriority(session), queryExecution instanceof DataDefinitionExecution); for (ResourceGroupSelector selector : configurationManager.get().getSelectors()) { Optional<ResourceGroupId> group = selector.match(context); if (group.isPresent()) { return group.get(); } } throw new PrestoException(QUERY_REJECTED, "Query did not match any selection rule"); }

Target:
private ResourceGroupId selectGroup(QueryExecution queryExecution) { Session session = queryExecution.getSession(); SelectionContext context = new SelectionContext( session.getIdentity().getPrincipal().isPresent(), session.getUser(), session.getSource(), getQueryPriority(session), determineQueryType(queryExecution)); for (ResourceGroupSelector selector : configurationManager.get().getSelectors()) { Optional<ResourceGroupId> group = selector.match(context); if (group.isPresent()) { return group.get(); } } throw new PrestoException(QUERY_REJECTED, "Query did not match any selection rule"); }
Source:
public boolean contains(Position position) { Position entityPosition = entity.getPosition(); int width = entity.getWidth(); int height = entity.getLength(); return position.getX() >= entityPosition.getX() && position.getX() < entityPosition.getX() + width && position.getY() >= entityPosition.getY() && position.getY() < entityPosition.getY() + height && position.getHeight() == entityPosition.getHeight(); }

Target:
public boolean contains(Position position) { int positionX = position.getX(); int positionY = position.getY(); int positionHeight = position.getHeight(); int entityX = entity.getPosition().getX(); int entityY = entity.getPosition().getY(); int entityHeight = entity.getPosition().getHeight(); int width = entity.getWidth(); int length = entity.getLength(); return positionX >= entityX && positionX < entityX + width && positionY >= entityY && positionY < entityY + length && positionHeight == entityHeight; }
Source:
public void testCDANonExistingVds() { doReturn(null).when(vdsDAOMock).get(vdsId); CanDoActionTestUtils.runAndAssertCanDoActionFailure(command, VdcBllMessages.VDS_NOT_EXIST); }

Target:
public void testCDANonExistingVds() { doReturn(null).when(vdsDAOMock).get(vdsId); CanDoActionTestUtils.runAndAssertCanDoActionFailure("canDoAction did not fail for non existing VDS", command, VdcBllMessages.VDS_NOT_EXIST); }
Source:
public void onPingFromClient(PingFromClientEvent event, EntityRef entity){ if (networkSystem.getMode().isServer()) { Instant end = Instant.now(); endMap.put(entity, end); updatePing(entity); } }

Target:
public void onPingFromClient(PingFromClientEvent event, EntityRef entity) { Instant end = Instant.now(); endMap.put(entity, end); updatePing(entity); }
Source:
public void offheapCacheManager() throws InterruptedException { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("tieredCache", CacheConfigurationBuilder.newCacheConfigurationBuilder() .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) .withExpiry(Expirations.timeToLiveExpiration(new Duration(10, TimeUnit.SECONDS))) .buildConfig(Long.class, String.class)).build(true); final Cache<Long, String> tieredCache = cacheManager.getCache("tieredCache", Long.class, String.class); tieredCache.put(1L, "not expired yet..."); Thread.sleep(TimeUnit.SECONDS.toMillis(5)); System.out.println( " 5 Seconds in: " + tieredCache.get(1L)); Thread.sleep(TimeUnit.SECONDS.toMillis(7)); System.out.println("12 Seconds in: " + tieredCache.get(1L)); Thread.sleep(TimeUnit.SECONDS.toMillis(4)); System.out.println("16 Seconds in: " + tieredCache.get(1L)); }

Target:
public void offheapCacheManager() { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("tieredCache", CacheConfigurationBuilder.newCacheConfigurationBuilder() .withResourcePools(ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) .buildConfig(Long.class, String.class)).build(true); cacheManager.close(); }
Source:
private static void waitUntilMergeDone(String r1, String r2, PartitionAdmin admin, String conglomId) throws IOException, InterruptedException { boolean done = false; int wait = 0; int maxWait = 12000; SystemClock clock = new SystemClock(); while (!done && wait < maxWait) { done = true; Iterable<? extends Partition> partitions = admin.allPartitions(conglomId); List<Partition> partitionList = Lists.newArrayList(partitions); for (Partition p : partitionList) { if (p.getEncodedName().compareTo(r1) == 0 || p.getEncodedName().compareTo(r2) == 0) { done = false; break; } } if (!done) { if (wait % 10 == 0) { SpliceLogUtils.info(LOG, "waiting for %s and %s to be merged", r1, r2); } clock.sleep(100, TimeUnit.MILLISECONDS); wait++; } } if (done) { SpliceLogUtils.info(LOG, "merged region %s and %s", r1, r2); } else { SpliceLogUtils.warn(LOG, "region %s and %s are not merged", r1, r2); } }

Target:
private static void waitUntilMergeDone(String r1, String r2, PartitionAdmin admin, String conglomId) throws IOException, InterruptedException, StandardException { boolean done = false; int wait = 0; int maxWait = 12000; SystemClock clock = new SystemClock(); while (!done && wait < maxWait) { done = true; Iterable<? extends Partition> partitions = admin.allPartitions(conglomId); List<Partition> partitionList = Lists.newArrayList(partitions); for (Partition p : partitionList) { if (p.getEncodedName().compareTo(r1) == 0 || p.getEncodedName().compareTo(r2) == 0) { done = false; break; } } if (!done) { if (wait % 10 == 0) { SpliceLogUtils.info(LOG, "waiting for %s and %s to be merged", r1, r2); } clock.sleep(100, TimeUnit.MILLISECONDS); wait++; } } if (done) { SpliceLogUtils.info(LOG, "merged region %s and %s", r1, r2); } else { throw StandardException.newException(SQLState.CANNOT_MERGE_REGION, r1, r2); } }
Source:
protected Document toDocument() { String delim = ","; StringBuilder searchableTextBuilder = new StringBuilder(""); searchableTextBuilder.append(instructor.courseId).append(delim); searchableTextBuilder.append(course != null ? course.name : "").append(delim); searchableTextBuilder.append(instructor.name).append(delim); searchableTextBuilder.append(instructor.email).append(delim); searchableTextBuilder.append(instructor.googleId != null ? instructor.googleId : "").append(delim); searchableTextBuilder.append(instructor.role).append(delim); Document doc = Document.newBuilder() .addField(Field.newBuilder().setName(Const.SearchDocumentField.SEARCHABLE_TEXT).setText(searchableTextBuilder.toString())) .addField(Field.newBuilder().setName(Const.SearchDocumentField.INSTRUCTOR_ATTRIBUTE).setText(new Gson().toJson(instructor))) .setId(StringHelper.encrypt(instructor.key)) .build(); return doc; }

Target:
protected Document toDocument() { String delim = ","; StringBuilder searchableTextBuilder = new StringBuilder(""); searchableTextBuilder.append(instructor.courseId).append(delim); searchableTextBuilder.append(course != null ? course.name : "").append(delim); searchableTextBuilder.append(instructor.name).append(delim); searchableTextBuilder.append(instructor.email).append(delim); searchableTextBuilder.append(instructor.googleId != null ? instructor.googleId : "").append(delim); searchableTextBuilder.append(instructor.role).append(delim); searchableTextBuilder.append(instructor.displayedName).append(delim); Document doc = Document.newBuilder() .addField(Field.newBuilder().setName(Const.SearchDocumentField.SEARCHABLE_TEXT).setText(searchableTextBuilder.toString())) .addField(Field.newBuilder().setName(Const.SearchDocumentField.INSTRUCTOR_ATTRIBUTE).setText(new Gson().toJson(instructor))) .setId(StringHelper.encrypt(instructor.key)) .build(); return doc; }
Source:
public void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws RestServiceException { logger.trace("Reading on channel {}", ctx.channel()); long currentTime = System.currentTimeMillis(); if (obj instanceof HttpRequest) { handleRequest((HttpRequest) obj); } else if (obj instanceof HttpContent) { handleContent((HttpContent) obj); } else { logger.warn("Received null/unrecognized HttpObject on channel {}", obj, ctx.channel()); nettyMetrics.unknownHttpObjectError.inc(); if (responseChannel == null || responseChannel.isResponseComplete()) { refreshState(); } throw new RestServiceException("HttpObject received is null or not of a known type", RestServiceErrorCode.UnknownHttpObject); } if (lastChannelReadTime != null) { nettyMetrics.channelReadIntervalInMs.update(currentTime - lastChannelReadTime); logger.trace("Delay between channel reads is ms", (currentTime - lastChannelReadTime)); } lastChannelReadTime = currentTime; }

Target:
public void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws RestServiceException { logger.trace("Reading on channel {}", ctx.channel()); long currentTime = System.currentTimeMillis(); if (obj instanceof HttpRequest) { handleRequest((HttpRequest) obj); } else if (obj instanceof HttpContent) { handleContent((HttpContent) obj); } else { logger.warn("Received null/unrecognized HttpObject on channel {}", obj, ctx.channel()); nettyMetrics.unknownHttpObjectError.inc(); if (responseChannel == null || responseChannel.isResponseComplete()) { resetState(); } throw new RestServiceException("HttpObject received is null or not of a known type", RestServiceErrorCode.UnknownHttpObject); } if (lastChannelReadTime != null) { nettyMetrics.channelReadIntervalInMs.update(currentTime - lastChannelReadTime); logger.trace("Delay between channel reads is ms", (currentTime - lastChannelReadTime)); } lastChannelReadTime = currentTime; }
Source:
public QueryEngine buildQueryEngine(DataSource defaultDataSource, ObjectProvider<ElideDynamicEntityCompiler> dynamicCompiler, ElideConfigProperties settings) throws ClassNotFoundException { if (isDynamicConfigEnabled(settings)) { MetaDataStore metaDataStore = new MetaDataStore(dynamicCompiler.getIfAvailable()); return new SQLQueryEngine(metaDataStore, defaultDataSource, defaultDialect, dynamicCompiler.getIfAvailable().getConnectionDetailsMap()); } else { MetaDataStore metaDataStore = new MetaDataStore(); return new SQLQueryEngine(metaDataStore, defaultDataSource, defaultDialect); } }

Target:
public QueryEngine buildQueryEngine(DataSource defaultDataSource, ObjectProvider<ElideDynamicEntityCompiler> dynamicCompiler, ElideConfigProperties settings) throws ClassNotFoundException { ConnectionDetails defaultConnectionDetails = new ConnectionDetails(defaultDataSource, settings.getAggregationStore().getDefaultDialect()); if (isDynamicConfigEnabled(settings)) { MetaDataStore metaDataStore = new MetaDataStore(dynamicCompiler.getIfAvailable()); return new SQLQueryEngine(metaDataStore, defaultConnectionDetails, dynamicCompiler.getIfAvailable().getConnectionDetailsMap()); } else { MetaDataStore metaDataStore = new MetaDataStore(); return new SQLQueryEngine(metaDataStore, defaultConnectionDetails); } }
Source:
public String toString() { return Character.valueOf(expectedCharacter).toString(); }

Target:
public String toString() { return String.valueOf(expectedCharacter); }
Source:
public void createNewTermination( boolean createAndContinue ) { TerminationPopup terminationPopup = new TerminationPopup( view ); terminationPopup.init( content, new ArrayList<>() ); terminationPopup.addPopupHandler( handler ); when( view.getSelectedTermination() ).thenReturn( "terminationType" ); Pair<String, String> terminationValue = new Pair<>( "terminationValue", "terminationValue" ); when( view.getTerminationValue() ).thenReturn( terminationValue ); if ( createAndContinue ) { terminationPopup.onCreateAndContinue(); } else { terminationPopup.onCreate(); } verify( view, times( 1 ) ).getSelectedTermination(); verify( view, times( 1 ) ).getTerminationValue(); if ( createAndContinue ) { verify( handler, times( 1 ) ).onCreateAndContinue( "terminationType", terminationValue, content ); } else { verify( handler, times( 1 ) ).onCreate( "terminationType", terminationValue, content ); ; } }

Target:
public void createNewTermination( boolean createAndContinue ) { TerminationPopup terminationPopup = new TerminationPopup( view ); terminationPopup.init( content, new ArrayList<>() ); terminationPopup.addPopupHandler( handler ); when( view.getSelectedTermination() ).thenReturn( "terminationType" ); Pair<String, String> terminationValue = new Pair<>( "terminationValue", "terminationValue" ); when( view.getTerminationValue() ).thenReturn( terminationValue ); if ( createAndContinue ) { terminationPopup.onCreateAndContinue(); } else { terminationPopup.onCreate(); } verify( view, times( 1 ) ).getSelectedTermination(); verify( view, times( 1 ) ).getTerminationValue(); if ( createAndContinue ) { verify( handler, times( 1 ) ).onCreateAndContinue( "terminationType", terminationValue, content ); } else { verify( handler, times( 1 ) ).onCreate( "terminationType", terminationValue, content ); } }
Source:
public OAuth2UserRecord getUserRecord(String code, @NotNull OAuth20Service service) throws IOException, OAuth2Exception, InterruptedException, ExecutionException { OAuth2AccessToken accessToken = service.getAccessToken(code); if ( ! accessToken.getScope().contains(scope) ) { throw new OAuth2Exception(200, BundleUtil.getStringFromBundle("auth.providers.orcid.insufficientScope"), ""); } OAuthRequest request = new OAuthRequest(Verb.GET, getUserEndpoint(accessToken)); request.setCharset("UTF-8"); service.signRequest(accessToken, request); Response response = service.execute(request); int responseCode = response.getCode(); String body = response.getBody(); logger.log(Level.FINE, "In requestUserRecord. Body: {0}", body); if ( responseCode == 200 && body != null ) { return getUserRecord(body, accessToken, service); } else { throw new OAuth2Exception(responseCode, body, "Error getting the user info record."); } }

Target:
public OAuth2UserRecord getUserRecord(String code, @NotNull OAuth20Service service) throws IOException, OAuth2Exception, InterruptedException, ExecutionException { OAuth2AccessToken accessToken = service.getAccessToken(code); if ( ( accessToken.getScope() != null && ! getScope().stream().allMatch(accessToken.getScope()::contains) ) || ( accessToken.getScope() == null && ! getSpacedScope().isEmpty() ) ) { throw new OAuth2Exception(200, BundleUtil.getStringFromBundle("auth.providers.insufficientScope", Arrays.asList(this.getTitle())), ""); } OAuthRequest request = new OAuthRequest(Verb.GET, getUserEndpoint(accessToken)); request.setCharset("UTF-8"); service.signRequest(accessToken, request); Response response = service.execute(request); int responseCode = response.getCode(); String body = response.getBody(); logger.log(Level.FINE, "In requestUserRecord. Body: {0}", body); if ( responseCode == 200 && body != null ) { return getUserRecord(body, accessToken, service); } else { throw new OAuth2Exception(responseCode, body, BundleUtil.getStringFromBundle("auth.providers.exception.userinfo", Arrays.asList(this.getTitle()))); } }
Source:
public void save(byte[] data) throws IOException { if ((data == null) || (data.length == 0)) { return; } synchronized (lock) { this.out.write(data); this.out.write(this.recordDelimiter.getBytes()); if (this.out instanceof HdfsDataOutputStream) { ((HdfsDataOutputStream) this.out).hsync(EnumSet.of(HdfsDataOutputStream.SyncFlag.UPDATE_LENGTH)); } else { this.out.hsync(); } } }

Target:
public void save(byte[] data) throws IOException { if ((data == null) || (data.length == 0)) { return; } if (shouldRotate.compareAndSet(true, false)) { rotateOutputFile(); } this.out.write(data); this.out.write(this.recordDelimiter.getBytes()); if (this.out instanceof HdfsDataOutputStream) { ((HdfsDataOutputStream) this.out).hsync(EnumSet.of(HdfsDataOutputStream.SyncFlag.UPDATE_LENGTH)); } else { this.out.hsync(); } }
Source:
private void onReloadConfigComplete(String result) { synchronized(mConfigLock) { mConfig = new Gson().fromJson(result, Config.class); } if (mConfig == null) { throw new RuntimeException("config is null: " + result); } Log.v(TAG, "onReloadConfigComplete: Successfully parsed configuration."); mCompletion.updateFromConfig(getDevices(true), getFolders()); }

Target:
private void onReloadConfigComplete(String result) { Boolean configParseSuccess; synchronized(mConfigLock) { mConfig = new Gson().fromJson(result, Config.class); configParseSuccess = mConfig != null; } if (!configParseSuccess) { throw new RuntimeException("config is null: " + result); } Log.v(TAG, "onReloadConfigComplete: Successfully parsed configuration."); mCompletion.updateFromConfig(getDevices(true), getFolders()); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Host other = (Host) obj; if (other.hashtag != null) { setHashtag(other.hashtag); } boolean equals = true; equals &= (hostname != null) ? hostname.equals(other.hostname) : other.hostname == null; equals &= (rack != null) ? rack.equals(other.rack) : other.rack == null; return equals; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Host other = (Host) obj; boolean equals = true; equals &= (hostname != null) ? hostname.equals(other.hostname) : other.hostname == null; equals &= (rack != null) ? rack.equals(other.rack) : other.rack == null; return equals; }
Source:
public void onEventMainThread(UploadService.UploadMediaRetryEvent event) { if (!isFinishing()) { if (event.mediaModelList != null && !event.mediaModelList.isEmpty()) { for (MediaModel media : event.mediaModelList) { String localMediaId = String.valueOf(media.getId()); if (mEditorMediaUploadListener != null) { EditorFragmentAbstract.MediaType mediaType = EditorFragmentAbstract.MediaType.IMAGE; if (org.wordpress.android.fluxc.utils.MediaUtils.isVideoMimeType(media.getMimeType())) { mediaType = EditorFragmentAbstract.MediaType.VIDEO; } mEditorMediaUploadListener.onMediaUploadRetry(localMediaId, mediaType); } } } } }

Target:
public void onEventMainThread(UploadService.UploadMediaRetryEvent event) { if (!isFinishing() && event.mediaModelList != null && mEditorMediaUploadListener != null) { for (MediaModel media : event.mediaModelList) { String localMediaId = String.valueOf(media.getId()); EditorFragmentAbstract.MediaType mediaType = media.isVideo() ? EditorFragmentAbstract.MediaType.VIDEO : EditorFragmentAbstract.MediaType.IMAGE; mEditorMediaUploadListener.onMediaUploadRetry(localMediaId, mediaType); } } }
Source:
public InputStream getInputStream() throws IOException { if (data == null) { synchronized (this) { if (data == null) { HttpRequests requests = new HttpRequests(new BasicHttpParams(), null, null); data = IOUtils.toByteArray(requests.get(attachmentURI)); } } } return new ByteArrayInputStream(data); }

Target:
public InputStream getInputStream() throws IOException { if( data == null) { HttpRequests requests = new HttpRequests(new BasicHttpParams(), null, null); return requests.get(attachmentURI); } else { return new ByteArrayInputStream(data); } }