auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object result; if( ReflectionUtil.hasField( entity.getClass(), Persistence.DEFAULT_OBJECT_ID_FIELD ) ) { result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity } ); } else { String objectId = FootprintsManager.getInstance().getObjectId( entity ); result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), objectId } ); } FootprintsManager.getInstance().Inner.removeFootprintForObject( BackendlessSerializer.serializeToMap( entity ), entity ); return ((Number) result).longValue(); }

Target:
protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object entityArg = ReflectionUtil.hasField( entity.getClass(), Persistence.DEFAULT_OBJECT_ID_FIELD ) ? entity : FootprintsManager.getInstance().getObjectId( entity ); Object result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entityArg } ); FootprintsManager.getInstance().Inner.removeFootprintForObject( BackendlessSerializer.serializeToMap( entity ), entity ); return ((Number) result).longValue(); }
Source:
public boolean containsAll(Collection<?> c) { for (Object name : c) if (!wrappedSet.contains(IdentityWrapper.wrap(name))) return false; return true; }

Target:
public boolean containsAll(Collection<?> c) { for (Object element : c) if (!wrappedSet.contains(IdentityWrapper.wrap(element))) return false; return true; }
Source:
private SegmentEvent transformSegmentEvent(org.atlasapi.media.segment.SegmentEvent input, Version version) throws UnresolvedLegacySegmentException { SegmentEvent se = new SegmentEvent(); setIdentifiedFields(se, input); se.setOffset(input.getOffset()); se.setIsChapter(input.getIsChapter()); org.atlasapi.media.entity.Description d = input.getDescription(); se.setDescription(d.getSynopsis()); se.setTitle(d.getTitle()); se.setImage(d.getImage()); se.setThumbnail(d.getThumbnail()); org.atlasapi.media.segment.SegmentRef sr = input.getSegment(); Id segmentId = Id.valueOf(sr.identifier()); WriteResult<Segment, Segment> legacyMigrationResult = legacySegmentMigrator.migrateLegacySegment(segmentId); se.setSegment(new SegmentRef(segmentId, legacyMigrationResult.getResource().getPublisher())); se.setVersionId(version.getCanonicalUri()); return se; }

Target:
private SegmentEvent transformSegmentEvent(org.atlasapi.media.segment.SegmentEvent input, Version version) throws UnresolvedLegacySegmentException { SegmentEvent se = new SegmentEvent(); setIdentifiedFields(se, input); se.setOffset(input.getOffset()); se.setIsChapter(input.getIsChapter()); org.atlasapi.media.entity.Description d = input.getDescription(); se.setDescription(new Description(d.getTitle(), d.getSynopsis(), d.getImage(), d.getThumbnail())); org.atlasapi.media.segment.SegmentRef sr = input.getSegment(); Id segmentId = Id.valueOf(sr.identifier()); WriteResult<Segment, Segment> legacyMigrationResult = legacySegmentMigrator.migrateLegacySegment(segmentId); se.setSegment(new SegmentRef(segmentId, legacyMigrationResult.getResource().getPublisher())); se.setVersionId(version.getCanonicalUri()); return se; }
Source:
public PeriodicMeterReadGasResponseDto(final PeriodTypeDto periodType, final List<PeriodicMeterReadsGasResponseItemDto> periodicMeterReadsGas) { this.periodicMeterReadsGas = new ArrayList<PeriodicMeterReadsGasResponseItemDto>(periodicMeterReadsGas); this.periodType = periodType; }

Target:
public PeriodicMeterReadGasResponseDto(final PeriodTypeDto periodType, final List<PeriodicMeterReadsGasResponseItemDto> periodicMeterReadsGas) { this.periodicMeterReadsGas = new ArrayList<>(periodicMeterReadsGas); this.periodType = periodType; }
Source:
private void onFailure(Throwable caught) { if (failed) { return; } failed = true; Throwable caughtDuringOnFailure = null; for (Object o : callbacks) { try { if (o instanceof AsyncCallback) { @SuppressWarnings("unchecked") AsyncCallback<Object> cb = (AsyncCallback<Object>) o; cb.onFailure(caught); } else { @SuppressWarnings("unchecked") com.google.gwtjsonrpc.common.AsyncCallback<Object> cb = (com.google.gwtjsonrpc.common.AsyncCallback<Object>) o; cb.onFailure(caught); } } catch (Throwable t) { if (caughtDuringOnFailure == null) { caughtDuringOnFailure = t; } } } propagate(caught); }

Target:
private void onFailure(Throwable caught) { if (failed) { return; } failed = true; for (Object o : callbacks) { if (o instanceof AsyncCallback) { @SuppressWarnings("unchecked") AsyncCallback<Object> cb = (AsyncCallback<Object>) o; cb.onFailure(caught); } else { @SuppressWarnings("unchecked") com.google.gwtjsonrpc.common.AsyncCallback<Object> cb = (com.google.gwtjsonrpc.common.AsyncCallback<Object>) o; cb.onFailure(caught); } } }
Source:
public void readInto(ByteBuffer buffer, long position) throws IOException { if (position < 0 || position > getEndOffset()) { throw new IllegalArgumentException( "Provided position [" + position + "] is out of bounds for the segment [" + file.getAbsolutePath() + "] with end offset [" + getEndOffset() + "]"); } if (position + buffer.remaining() > getEndOffset()) { metrics.overflowReadError.inc(); throw new IllegalArgumentException("Cannot read from segment [" + file.getAbsolutePath() + "] from position [" + position + "] for size [" + buffer.remaining() + "] because it exceeds the end offset [" + endOffset + "]"); } long bytesRead = 0; int size = buffer.remaining(); while (bytesRead < size) { bytesRead += fileChannel.read(buffer, position + bytesRead); } }

Target:
public void readInto(ByteBuffer buffer, long position) throws IOException { if (position < 0 || position >= getEndOffset()) { throw new IndexOutOfBoundsException( "Provided position [" + position + "] is out of bounds for the segment [" + file.getAbsolutePath() + "] with end offset [" + getEndOffset() + "]"); } if (position + buffer.remaining() > getEndOffset()) { metrics.overflowReadError.inc(); throw new IndexOutOfBoundsException("Cannot read from segment [" + file.getAbsolutePath() + "] from position [" + position + "] for size [" + buffer.remaining() + "] because it exceeds the end offset [" + endOffset + "]"); } long bytesRead = 0; int size = buffer.remaining(); while (bytesRead < size) { bytesRead += fileChannel.read(buffer, position + bytesRead); } }
Source:
public Builder withSingleValuedColumn(VSizeIndexedInts singleValuedColumn) { Preconditions.checkState(compressedSingleValuedColumn == null, "Cannot set both singleValuedColumn and compressedSingleValuedColumn"); Preconditions.checkState(multiValuedColumn == null, "Cannot set both singleValuedColumn and multiValuedColumn"); this.singleValuedColumn = singleValuedColumn; return this; }

Target:
public Builder withSingleValuedColumn(VSizeIndexedInts singleValuedColumn) { Preconditions.checkState(multiValuedColumn == null, "Cannot set both singleValuedColumn and multiValuedColumn"); this.version = VERSION.UNCOMPRESSED_SINGLE_VALUE; this.singleValuedColumn = singleValuedColumn.asWritableSupplier(); return this; }
Source:
public <T> void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { if (particle == null) { throw new IllegalArgumentException("particle cannot be null!"); } if (data != null && !particle.getDataType().isInstance(data)) { throw new IllegalArgumentException("wrong data type " + data.getClass() + " should be " + particle.getDataType()); } for (Player player : getPlayers()) { GlowPlayer glowPlayer = (GlowPlayer) player; double distance = player.getLocation().distanceSquared(location); boolean isLongDistance = GlowParticle.isLongDistance(particle); int particleId = GlowParticle.getId(particle); int[] particleData = GlowParticle.getData(particle, data); if (distance <= 1024.0D || isLongDistance && distance <= 262144.0D) { glowPlayer.getSession().send(new PlayParticleMessage(particleId, isLongDistance, (float) location.getX(), (float) location.getY(), (float) location.getZ(), (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count, particleData)); } } }

Target:
public <T> void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { if (particle == null) { throw new IllegalArgumentException("particle cannot be null!"); } if (data != null && !particle.getDataType().isInstance(data)) { throw new IllegalArgumentException("wrong data type " + data.getClass() + " should be " + particle.getDataType()); } for (GlowPlayer player : getRawPlayers()) { double distance = player.getLocation().distanceSquared(location); boolean isLongDistance = GlowParticle.isLongDistance(particle); int particleId = GlowParticle.getId(particle); int[] particleData = GlowParticle.getExtData(particle, data); if (distance <= 1024.0D || isLongDistance && distance <= 262144.0D) { player.getSession().send(new PlayParticleMessage(particleId, isLongDistance, (float) location.getX(), (float) location.getY(), (float) location.getZ(), (float) offsetX, (float) offsetY, (float) offsetZ, (float) extra, count, particleData)); } } }
Source:
public void destroy() { this.canvasHandler = null; this.canvasHighlight = null; this.sourceNode = null; this.palette.destroy(); this.nodeDragProxyFactory.destroy(); this.nodeBuilderControl.setCommandManagerProvider(null); this.nodeBuilderControl.disable(); this.graphBoundsIndexer.destroy(); this.canvasHighlight.destroy(); }

Target:
public void destroy() { this.palette.destroy(); this.nodeDragProxyFactory.destroy(); this.nodeBuilderControl.setCommandManagerProvider(null); this.nodeBuilderControl.disable(); this.graphBoundsIndexer.destroy(); this.canvasHighlight.destroy(); this.canvasHandler = null; this.canvasHighlight = null; this.sourceNode = null; }
Source:
private String arrayToStr(Header[] headers) { StringBuilder sb = new StringBuilder(); for (Header header : headers) { sb.append(header.toString()); } return sb.toString(); }

Target:
private static String arrayToStr(Header[] headers) { StringBuilder sb = new StringBuilder(); for (Header header : headers) { sb.append(header.toString()).append("\r\n"); } return sb.toString(); }
Source:
boolean evaluate() throws E, IOException; } @InterfaceAudience.Private public interface ExplainingPredicate<E extends Exception> extends Predicate<E> { String explainFailure() throws E; }

Target:
boolean evaluate() throws E; } @InterfaceAudience.Private public interface ExplainingPredicate<E extends Exception> extends Predicate<E> { String explainFailure() throws E; }
Source:
public Description getDescription() { Description spec = Description.createSuiteDescription(getName(), classAnnotations()); List<Method> testMethods = this.testMethods; for (Method method : testMethods) { spec.addChild(methodDescription(method)); } return spec; }

Target:
public Description getDescription() { Description spec = Description.createSuiteDescription(getName(), classAnnotations()); List<Method> methods = testMethods; for (Method method : methods) { spec.addChild(methodDescription(method)); } return spec; }
Source:
public HttpResponse doAddFixedToken(@AncestorInPath User u, @QueryParameter String newTokenName, @QueryParameter String newTokenPlainValue) throws IOException { if (!hasCurrentUserRightToGenerateNewToken(u)) { return HttpResponses.forbidden(); } final String tokenName; if (StringUtils.isBlank(newTokenName)) { tokenName = String.format("Token created on %s", DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now())); } else { tokenName = newTokenName; } ApiTokenProperty p = u.getProperty(ApiTokenProperty.class); if (p == null) { p = forceNewInstance(u, false); u.addProperty(p); } String tokenUuid = p.tokenStore.addFixedNewToken(tokenName, newTokenPlainValue); u.save(); return HttpResponses.okJSON(new HashMap<String, String>() {{ put("tokenUuid", tokenUuid); put("tokenName", tokenName); }}); }

Target:
public HttpResponse doAddFixedToken(@AncestorInPath User u, @QueryParameter String newTokenName, @QueryParameter String newTokenPlainValue) throws IOException { if (!hasCurrentUserRightToGenerateNewToken(u)) { return HttpResponses.forbidden(); } final String tokenName; if (StringUtils.isBlank(newTokenName)) { tokenName = String.format("Token created on %s", DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now())); } else { tokenName = newTokenName; } ApiTokenProperty p = u.getProperty(ApiTokenProperty.class); if (p == null) { p = forceNewInstance(u, false); u.addProperty(p); } String tokenUuid = p.tokenStore.addFixedNewToken(tokenName, newTokenPlainValue); u.save(); Map<String, String> data = new HashMap<>(); data.put("tokenUuid", tokenUuid); data.put("tokenName", tokenName); return HttpResponses.okJSON(data); }
Source:
public void createNorthAnt() { inputFile = new String[] { "0000", "0000", "0a00", "0000" }; runs = new Run[] { new ExactRun("ant", is("a")), new NoOutputRun("create B,1,1"), new ExactRun("ant", is("a,b")), new ExactRun("position b", is("1,1")), new ExactRun("direction b", is("N")), new ExactRun("field 1,1", is("b")), quit() }; sessionTest(runs, Input.getFile(inputFile)); inputFile = new String[] { "b000", "0000", "0a00", "Z000" }; runs = new Run[] { new ExactRun("ant", is("a,b,z")), new NoOutputRun("create H,1,3"), new ExactRun("ant", is("a,b,h,z")), new ExactRun("position h", is("1,3")), new ExactRun("direction h", is("N")), new ExactRun("field 1,3", is("b")), quit() }; sessionTest(runs, Input.getFile(inputFile)); }

Target:
public void createNorthAnt() { inputFile = new String[] { "0000", "0000", "0a00", "0000" }; runs = new Run[] { new ExactRun("ant", is("a")), new NoOutputRun("create B,1,1"), new ExactRun("ant", is("a,b")), new ExactRun("position b", is("1,1")), new ExactRun("direction b", is("N")), new ExactRun("field 1,1", is("b")), quit() }; sessionTest(runs, Input.getFile(inputFile)); inputFile = new String[] { "b000", "0000", "0a00", "Z000" }; runs = new Run[] { new ExactRun("ant", is("a,b,z")), new NoOutputRun("create H,1,3"), new ExactRun("ant", is("a,b,h,z")), new ExactRun("position h", is("1,3")), new ExactRun("direction h", is("N")), new ExactRun("field 1,3", is("h")), quit() }; sessionTest(runs, Input.getFile(inputFile)); }
Source:
public File getLocalFile(String pdbId) { LinkedList<File> searchdirs = new LinkedList<File>(); String middle = pdbId.substring(1,3).toLowerCase(); File splitdir = new File(splitDirPath, middle); searchdirs.add(splitdir); if(getObsoleteBehavior() == ObsoleteBehavior.FETCH_OBSOLETE) { File obsdir = new File(obsoleteDirPath,middle); searchdirs.add(obsdir); } String[] prefixes = new String[] {"", "pdb"}; for( File searchdir :searchdirs){ for( String prefix : prefixes) { for(String ex : getExtensions() ){ File f = new File(searchdir,prefix + pdbId.toLowerCase() + ex) ; if ( f.exists()) { if( f.length() < MIN_PDB_FILE_SIZE ) { boolean success = f.delete(); if( ! success) { return null; } assert(!f.exists()); } return f; } } } } return null; }

Target:
public File getLocalFile(String pdbId) throws IOException { LinkedList<File> searchdirs = new LinkedList<File>(); String middle = pdbId.substring(1,3).toLowerCase(); File splitdir = new File(splitDirPath, middle); searchdirs.add(splitdir); if(getObsoleteBehavior() == ObsoleteBehavior.FETCH_OBSOLETE) { File obsdir = new File(obsoleteDirPath,middle); searchdirs.add(obsdir); } String[] prefixes = new String[] {"", "pdb"}; for( File searchdir :searchdirs){ for( String prefix : prefixes) { for(String ex : getExtensions() ){ File f = new File(searchdir,prefix + pdbId.toLowerCase() + ex) ; if ( f.exists()) { if( f.length() < MIN_PDB_FILE_SIZE ) { Files.delete(f.toPath()); return null; } return f; } } } } return null; }
Source:
private Map<String, ?> determineUriVariables(Message<?> requestMessage) { if (this.uriVariablesExpression != null) { return this.uriVariablesExpression.getValue(this.evaluationContext, requestMessage, Map.class); } else { return ExpressionEvalMap.from(this.uriVariableExpressions) .usingEvaluationContext(this.evaluationContext) .withRoot(requestMessage) .build(); } }

Target:
private Map<String, ?> determineUriVariables(Message<?> requestMessage) { Map<String, ?> expressions; if (this.uriVariablesExpression != null) { expressions = this.uriVariablesExpression.getValue(this.evaluationContext, requestMessage, Map.class); } else { expressions = this.uriVariableExpressions; } return ExpressionEvalMap.from(expressions) .usingEvaluationContext(this.evaluationContext) .withRoot(requestMessage) .build(); }
Source:
public int isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; final IObservableValue observableValue = Activator.getDefault().getEMFFormsDatabinding() .getObservableValue(control.getDomainModelReference(), viewModelContext.getDomainModel()); final EStructuralFeature feature = (EStructuralFeature) observableValue.getValueType(); final EObject eObject = (EObject) ((IObserving) observableValue).getObserved(); if (VKeyAttributeDomainModelReference.class.isInstance(eObject) && VKeyattributedmrPackage.eINSTANCE.getKeyAttributeDomainModelReference_KeyDMR() == feature) { return 6; } if (VKeyAttributeDomainModelReference.class.isInstance(eObject) && VKeyattributedmrPackage.eINSTANCE.getKeyAttributeDomainModelReference_ValueDMR() == feature) { return 6; } return NOT_APPLICABLE; }

Target:
public int isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; final IValueProperty valueProperty = Activator.getDefault().getEMFFormsDatabinding() .getValueProperty(control.getDomainModelReference()); final EStructuralFeature feature = (EStructuralFeature) valueProperty.getValueType(); if (VKeyattributedmrPackage.eINSTANCE.getKeyAttributeDomainModelReference_KeyDMR() == feature) { return 6; } if (VKeyattributedmrPackage.eINSTANCE.getKeyAttributeDomainModelReference_ValueDMR() == feature) { return 6; } return NOT_APPLICABLE; }
Source:
public SQLExecEnvironment registerTable(String name, Endpoint endpoint) { registerTable(name, new ApexSQLTable(schema, name, endpoint)); return this; }

Target:
public SQLExecEnvironment registerTable(String name, Endpoint endpoint) { Preconditions.checkNotNull(name, "Table name cannot be null"); registerTable(name, new ApexSQLTable(schema, name, endpoint)); return this; }
Source:
public void execute(OutboundPatientLocationQueryOrchestratable message) { LOG.trace("Begin OutboundPatientLocationQueryStrategyImpl.execute"); NhinPatientLocationQueryProxy nhincDocSubmission = getNhinDocDataSubmissionProxy(); PatientLocationQueryResponseType response = nhincDocSubmission.processPatientLocationQuery(message.getRequest(), message.getAssertion(), message.getTarget(), NhincConstants.GATEWAY_API_LEVEL.LEVEL_g0); message.setResponse(response); LOG.trace("End OutboundPatientLocationQueryStrategyImpl.execute"); }

Target:
public void execute(OutboundPatientLocationQueryOrchestratable message) { LOG.trace("Begin OutboundPatientLocationQueryStrategyImpl.execute"); NhinPatientLocationQueryProxy plqProxy = getNhinPatientLocationQueryProxy(); PatientLocationQueryResponseType response = plqProxy.processPatientLocationQuery(message.getRequest(), message.getAssertion(), message.getTarget(), NhincConstants.GATEWAY_API_LEVEL.LEVEL_g0); message.setResponse(response); LOG.trace("End OutboundPatientLocationQueryStrategyImpl.execute"); }
Source:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof NumberItem || item instanceof DimmerItem || item instanceof RollershutterItem || item instanceof StringItem)) { throw new BindingConfigParseException( "item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only SwitchItem, NumberItem, DimmerItem, RollershutterItem and StringItem are allowed - please check your *.items configuration"); } }

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!(item instanceof SwitchItem || item instanceof NumberItem || item instanceof DimmerItem || item instanceof RollershutterItem || item instanceof StringItem)) { throw new BindingConfigParseException("item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "', only Switch, Number, Dimmer, Rollershutter and String are allowed - please check your *.items configuration"); } }
Source:
public void execute(TupleWindow inputWindow) { Map<K, KeyValue<V1, V2>> joinMap = new HashMap<>(); for (Tuple tuple : inputWindow.get()) { if (tuple.getSourceComponent().equals(leftComponent)) { KeyValue<K, V1> tup = (KeyValue<K, V1>) tuple.getValue(0); if (tup.getKey() != null) { addMapLeft(joinMap, tup); } } else { KeyValue<K, V2> tup = (KeyValue<K, V2>) tuple.getValue(0); if (tup.getKey() != null) { addMapRight(joinMap, tup); } } } for (K key : joinMap.keySet()) { KeyValue<V1, V2> val = joinMap.get(key); switch (joinType) { case INNER: if (val.getKey() != null && val.getValue() != null) { joinAndEmit(key, val); } break; case LEFT: if (val.getKey() != null) { joinAndEmit(key, val); } break; case OUTER: joinAndEmit(key, val); break; default: throw new RuntimeException("Unknown jointype"); } } }

Target:
public void execute(TupleWindow inputWindow) { Map<K, KeyValue<V1, V2>> joinMap = new HashMap<>(); for (Tuple tuple : inputWindow.get()) { if (tuple.getSourceComponent().equals(leftComponent)) { KeyValue<K, V1> tup = (KeyValue<K, V1>) tuple.getValue(0); if (tup.getKey() != null) { addMapLeft(joinMap, tup); } } else { KeyValue<K, V2> tup = (KeyValue<K, V2>) tuple.getValue(0); if (tup.getKey() != null) { addMapRight(joinMap, tup); } } } evaluateJoinMap(joinMap, inputWindow); }
Source:
void updatePartitions(Collection<? extends PartitionId> allPartitions, String localDatacenterName) { this.allPartitions = allPartitions; partitionIdsByClassAndLocalReplicaCount = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (PartitionId partition : allPartitions) { String partitionClass = partition.getPartitionClass(); int localReplicaCount = 0; for (ReplicaId replicaId : partition.getReplicaIds()) { if (localDatacenterName != null && !localDatacenterName.isEmpty() && replicaId.getDataNodeId() .getDatacenterName() .equals(localDatacenterName)) { localReplicaCount++; } } if (!partitionIdsByClassAndLocalReplicaCount.containsKey(partitionClass)) { partitionIdsByClassAndLocalReplicaCount.put(partitionClass, new TreeMap<>()); } SortedMap<Integer, List<PartitionId>> replicaCountToPartitionIds = partitionIdsByClassAndLocalReplicaCount.get(partitionClass); if (!replicaCountToPartitionIds.containsKey(localReplicaCount)) { replicaCountToPartitionIds.put(localReplicaCount, new ArrayList<>()); } replicaCountToPartitionIds.get(localReplicaCount).add(partition); } }

Target:
void updatePartitions(Collection<? extends PartitionId> allPartitions, String localDatacenterName) { this.allPartitions = allPartitions; partitionIdsByClassAndLocalReplicaCount = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (PartitionId partition : allPartitions) { String partitionClass = partition.getPartitionClass(); int localReplicaCount = 0; for (ReplicaId replicaId : partition.getReplicaIds()) { if (localDatacenterName != null && !localDatacenterName.isEmpty() && replicaId.getDataNodeId() .getDatacenterName() .equals(localDatacenterName)) { localReplicaCount++; } } SortedMap<Integer, List<PartitionId>> replicaCountToPartitionIds = partitionIdsByClassAndLocalReplicaCount.computeIfAbsent(partitionClass, key -> new TreeMap<>()); replicaCountToPartitionIds.computeIfAbsent(localReplicaCount, key -> new ArrayList<>()).add(partition); } }
Source:
public TimeLineTopComponent(TimeLineController controller) { initComponents(); this.controller = controller; associateLookup(ExplorerUtils.createLookup(em, getActionMap())); setName(NbBundle.getMessage(TimeLineTopComponent.class, "CTL_TimeLineTopComponent")); setToolTipText(NbBundle.getMessage(TimeLineTopComponent.class, "HINT_TimeLineTopComponent")); setIcon(WindowManager.getDefault().getMainWindow().getIconImage()); dataContentPanel = DataContentPanel.createInstance(); this.contentViewerContainerPanel.add(dataContentPanel, BorderLayout.CENTER); tlrv = new TimeLineResultView(controller, dataContentPanel); final DataResultPanel dataResultPanel = tlrv.getDataResultPanel(); this.resultContainerPanel.add(dataResultPanel, BorderLayout.CENTER); dataResultPanel.open(); customizeFXComponents(); controller.viewModeProperty().addListener((Observable observable) -> { switch (controller.getViewMode()) { case COUNTS: case DETAIL: SwingUtilities.invokeLater(() -> { splitYPane.remove(contentViewerContainerPanel); if ((lowerSplitXPane.getParent() == splitYPane) == false) { splitYPane.add(lowerSplitXPane); lowerSplitXPane.add(contentViewerContainerPanel); } }); break; case LIST: SwingUtilities.invokeLater(() -> { splitYPane.remove(lowerSplitXPane); splitYPane.add(contentViewerContainerPanel); dataResultPanel.setNode(null); }); break; default: throw new UnsupportedOperationException("Unknown ViewMode: " + controller.getViewMode()); } }); }

Target:
public TimeLineTopComponent(TimeLineController controller) { initComponents(); this.controller = controller; associateLookup(ExplorerUtils.createLookup(em, getActionMap())); setName(NbBundle.getMessage(TimeLineTopComponent.class, "CTL_TimeLineTopComponent")); setToolTipText(NbBundle.getMessage(TimeLineTopComponent.class, "HINT_TimeLineTopComponent")); setIcon(WindowManager.getDefault().getMainWindow().getIconImage()); dataContentPanel = DataContentPanel.createInstance(); this.contentViewerContainerPanel.add(dataContentPanel, BorderLayout.CENTER); tlResultView = new TimeLineResultView(controller, dataContentPanel); final DataResultPanel dataResultPanel = tlResultView.getDataResultPanel(); this.resultContainerPanel.add(dataResultPanel, BorderLayout.CENTER); dataResultPanel.open(); customizeFXComponents(); controller.viewModeProperty().addListener(viewMode -> { switch (controller.getViewMode()) { case COUNTS: case DETAIL: SwingUtilities.invokeLater(() -> { splitYPane.remove(contentViewerContainerPanel); if ((lowerSplitXPane.getParent() == splitYPane) == false) { splitYPane.add(lowerSplitXPane); lowerSplitXPane.add(contentViewerContainerPanel); } }); break; case LIST: SwingUtilities.invokeLater(() -> { splitYPane.remove(lowerSplitXPane); splitYPane.add(contentViewerContainerPanel); dataResultPanel.setNode(null); }); break; default: throw new UnsupportedOperationException("Unknown ViewMode: " + controller.getViewMode()); } }); }
Source:
public TxKeyCacheSet(VisitableCommand rCommand, CacheSet<K> set, boolean isRemoteIteration, InvocationContext rCtx) { super(Caches.getCacheWithFlags(TxInterceptor.this.cache, (FlagAffectedCommand) rCommand), set); this.isRemoteIteration = isRemoteIteration; this.rCtx = rCtx; }

Target:
TxKeyCacheSet(VisitableCommand rCommand, CacheSet<K> set, boolean isRemoteIteration, InvocationContext rCtx) { super(Caches.getCacheWithFlags(TxInterceptor.this.cache, (FlagAffectedCommand) rCommand), set); this.isRemoteIteration = isRemoteIteration; this.rCtx = rCtx; }
Source:
private void replaceVariables(Node node) throws Exception { boolean failFast = false; List<ConfigReplacer> replacers = new ArrayList<ConfigReplacer>(); PropertyReplacer propertyReplacer = new PropertyReplacer(); propertyReplacer.init(properties); replacers.add(propertyReplacer); Node replacersNode = node.getAttributes().getNamedItem(ConfigSections.CONFIG_REPLACERS.name); if (replacersNode != null) { String failFastAttr = getAttribute(replacersNode, "fail-if-value-missing", true); failFast = isNullOrEmpty(failFastAttr) ? true : Boolean.parseBoolean(failFastAttr); for (Node n : childElements(replacersNode)) { String nodeName = cleanNodeName(n); if ("replacers".equals(nodeName)) { for (Node replacerNode : childElements(n)) { replacers.add(createReplacer(replacerNode)); } } } } ConfigReplacerHelper.traverseChildrenAndReplaceVariables(node, replacers, failFast); }

Target:
private void replaceVariables(Node node) throws Exception { boolean failFast = false; List<ConfigReplacer> replacers = new ArrayList<ConfigReplacer>(); PropertyReplacer propertyReplacer = new PropertyReplacer(); propertyReplacer.init(properties); replacers.add(propertyReplacer); Node replacersNode = node.getAttributes().getNamedItem(ConfigSections.CONFIG_REPLACERS.name); if (replacersNode != null) { String failFastAttr = getAttribute(replacersNode, "fail-if-value-missing", true); failFast = isNullOrEmpty(failFastAttr) || Boolean.parseBoolean(failFastAttr); for (Node n : childElements(replacersNode)) { String nodeName = cleanNodeName(n); if ("replacers".equals(nodeName)) { for (Node replacerNode : childElements(n)) { replacers.add(createReplacer(replacerNode)); } } } } ConfigReplacerHelper.traverseChildrenAndReplaceVariables(node, replacers, failFast, new YamlDomVariableReplacer()); }
Source:
public synchronized void setup() { ExecutorType type = ExecutorType.valueOf(executorType); switch (type) { case defaultEventExecutor: executor = new DefaultEventExecutor(); executorToShutdown = executor; break; case juc: executor = Executors.newSingleThreadScheduledExecutor(); executorToShutdown = executor; break; case nioEventLoop: NioEventLoopGroup group = new NioEventLoopGroup(1); group.setIoRatio(1); executor = group.next(); executorToShutdown = group; break; } }

Target:
public void setup() { ExecutorType type = ExecutorType.valueOf(executorType); switch (type) { case spinning: executor = new SpinExecutorService(Math.min(1024, burstLength * 4)); executorToShutdown = executor; break; case defaultEventExecutor: executor = new DefaultEventExecutor(); executorToShutdown = executor; break; case juc: executor = Executors.newSingleThreadScheduledExecutor(); executorToShutdown = executor; break; case nioEventLoop: NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(1); nioEventLoopGroup.setIoRatio(1); executor = nioEventLoopGroup.next(); executorToShutdown = nioEventLoopGroup; break; case epollEventLoop: Epoll.ensureAvailability(); EpollEventLoopGroup epollEventLoopGroup = new EpollEventLoopGroup(1); epollEventLoopGroup.setIoRatio(1); executor = epollEventLoopGroup.next(); executorToShutdown = epollEventLoopGroup; break; case kqueueEventLoop: KQueue.ensureAvailability(); KQueueEventLoopGroup kQueueEventLoopGroup = new KQueueEventLoopGroup(1); kQueueEventLoopGroup.setIoRatio(1); executor = kQueueEventLoopGroup.next(); executorToShutdown = kQueueEventLoopGroup; break; } }
Source:
private List<String> getProcessedFileList(String processedFileTable, Date preProcessedDate) throws Exception { DataSetManager<KeyValueTable> dataSetManager = getDataset(processedFileTable); KeyValueTable table = dataSetManager.get(); CloseableIterator<KeyValue<byte[], byte[]>> iterator = table.scan(null, null); List<String> processedFileList = new ArrayList<String>(); while (iterator.hasNext()) { KeyValue<byte[], byte[]> keyValue = iterator.next(); Date date = new Date(Long.valueOf(new String(keyValue.getValue(), Charsets.UTF_8))); if (date.after(preProcessedDate)) { processedFileList.add(new String(keyValue.getKey(), Charsets.UTF_8)); } } return processedFileList; }

Target:
private List<String> getProcessedFileList(String processedFileTable, Date preProcessedDate) throws Exception { List<String> processedFileList = new ArrayList<String>(); DataSetManager<KeyValueTable> dataSetManager = getDataset(processedFileTable); KeyValueTable table = dataSetManager.get(); try (CloseableIterator<KeyValue<byte[], byte[]>> iterator = table.scan(null, null)) { if (iterator != null) { while (iterator.hasNext()) { KeyValue<byte[], byte[]> keyValue = iterator.next(); Date date = new Date(Bytes.toLong(keyValue.getValue())); if (date.after(preProcessedDate)) { processedFileList.add(Bytes.toString(keyValue.getKey())); } } } } return processedFileList; }
Source:
} catch (IOException e) { Assumption.fail(e.toString()); }

Target:
} catch (IOException e) { Assumption.fail(TeammatesException.toStringWithStackTrace(e)); }
Source:
protected Network findVnicNetwork() { if (nic.getVnicProfileId() == null) { return null; } VnicProfile vnicProfile = getDbFacade().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile == null) { validationResult = new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_NOT_EXISTS); return null; } return getNetworkByVnicProfile(vnicProfile); }

Target:
protected Network findVnicNetwork() { if (nic.getVnicProfileId() == null) { return null; } VnicProfile vnicProfile = findVnicProfile(); if (vnicProfile == null) { return null; } return getNetworkByVnicProfile(vnicProfile); }
Source:
private void initChapters(@NonNull ArrayList<Chapter> chapters) { Chapter selectedChapter = null; if (getIntent().hasExtra(Const.EXTRA_CHAPTER_ID)) { final String chapterId = getIntent().getStringExtra(Const.EXTRA_CHAPTER_ID); for (Chapter c : chapters) { if (c.getGplusId().equals(chapterId)) { selectedChapter = c; break; } } } else if (getIntent().getData() != null && getIntent().getData().getScheme().equals("https")) { final String chapterId = getIntent().getData().getLastPathSegment(); for (Chapter c : chapters) { if (c.getGplusId().equals(chapterId)) { selectedChapter = c; break; } } } if (selectedChapter == null) { selectedChapter = chapters.get(0); } initChapters(chapters, selectedChapter); }

Target:
private void initChapters(@NonNull ArrayList<Chapter> chapters) { String chapterId = getChapterIdFromIntent(getIntent()); Chapter selectedChapter = null; if (chapterId != null) { for (Chapter c : chapters) { if (c.getGplusId().equals(chapterId)) { selectedChapter = c; break; } } } if (selectedChapter == null) { selectedChapter = chapters.get(0); } initChapters(chapters, selectedChapter); }
Source:
public BakingActionResult checkActionIsApplicableInState(State state, String[] params) { BakingActionResult superResult = super.checkActionIsApplicableInState(state, params); if (!superResult.getIsSuccess()) { return superResult; } String containerName = params[1]; ObjectInstance container = state.getObject(params[1]); ObjectInstance grease = state.getObject(params[2]); if (!ContainerFactory.isEmptyContainer(container)) { return BakingActionResult.failure(containerName + " is not an empty container"); } if (!ContainerFactory.isBakingContainer(container)) { return BakingActionResult.failure(containerName + " is not an baking container"); } if (ContainerFactory.isGreasedContainer(container)) { return BakingActionResult.failure(containerName + " is not an greased container"); } if (!IngredientFactory.isLubricant(grease)) { return BakingActionResult.failure(containerName + " is not an greased container"); } return BakingActionResult.success(); }

Target:
public BakingActionResult checkActionIsApplicableInState(State state, String[] params) { BakingActionResult superResult = super.checkActionIsApplicableInState(state, params); if (!superResult.getIsSuccess()) { return superResult; } String containerName = params[1]; ObjectInstance container = state.getObject(params[1]); String ingredientName = params[2]; ObjectInstance grease = state.getObject(params[2]); if (!ContainerFactory.isEmptyContainer(container)) { return BakingActionResult.failure(containerName + " is not an empty container"); } if (!ContainerFactory.isBakingContainer(container)) { return BakingActionResult.failure(containerName + " is not an baking container"); } if (ContainerFactory.isGreasedContainer(container)) { return BakingActionResult.failure(containerName + " is not an greasable container"); } if (!IngredientFactory.isLubricant(grease)) { return BakingActionResult.failure(ingredientName + " is not a suitable grease"); } return BakingActionResult.success(); }
Source:
static public void writeErrors(JsonGenerator writer, List<Exception> exceptions) throws IOException { for (Exception e : exceptions) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); writer.writeStartObject(); String errorMessage = e.getLocalizedMessage(); if(e instanceof TreeReaderException) { errorMessage += "\nPlease correct the format of your input file, or choose another" + " importer type such as Line-based"; } writer.writeStringField("message", errorMessage); writer.writeStringField("stack", sw.toString()); writer.writeEndObject(); } }

Target:
static public void writeErrors(JsonGenerator writer, List<Exception> exceptions) throws IOException { for (Exception e : exceptions) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); writer.writeStartObject(); writer.writeStringField("message", e.getLocalizedMessage()); writer.writeStringField("stack", sw.toString()); writer.writeEndObject(); } }
Source:
public long nextLong() { long s1 = this.seed0; final long s0 = this.seed1; this.seed0 = s0; s1 ^= s1 << 23; return (this.seed1 = s1 ^ s0 ^ (s1 >>> 17) ^ (s0 >>> 26)) + s0; }

Target:
public long nextLong() { long s1 = seed0; final long s0 = seed1; seed0 = s0; s1 ^= s1 << 23; seed1 = s1 ^ s0 ^ (s1 >>> 17) ^ (s0 >>> 26); return seed1 + s0; }
Source:
public RenewableBatchIdSequence( IdSequence source, int batchSize, LongConsumer excessIdConsumer ) { this.source = source; this.batchSize = batchSize; this.excessIdConsumer = excessIdConsumer; }

Target:
RenewableBatchIdSequence( IdSequence source, int batchSize, LongConsumer excessIdConsumer ) { this.source = source; this.batchSize = batchSize; this.excessIdConsumer = excessIdConsumer; }
Source:
public void run() { SensorJob sensorJob = circuit.getNextSensorJob(); if (sensorJob != null && connectionManager.checkConnection()) { sensorJob.execute(dSAPI, connectionManager.getSessionToken()); } if (circuit.noMoreJobs()) { logger.debug("no more jobs... stop circuit schedduler with id = {}", circuit.getMeterDSID().toString()); pollingSchedulers.get(circuit.getMeterDSID()).cancel(true); } }

Target:
public void run() { SensorJob sensorJob = circuit.getNextSensorJob(); if (sensorJob != null && connectionManager.checkConnection()) { sensorJob.execute(dSAPI, connectionManager.getSessionToken()); } if (circuit.noMoreJobs()) { logger.debug("no more jobs... stop circuit schedduler with id = {}", circuit.getMeterDSID()); pollingSchedulers.get(circuit.getMeterDSID()).cancel(true); } }
Source:
public void migrate() { List<byte[]> rangeBoundaries = getRangeBoundaries(); int totalTasks = rangeBoundaries.size() - 1; progress.beginTask("Migrating table " + srcTable + "...", totalTasks); Map<Long, byte[]> boundaryById = Maps.newHashMap(); for (long rangeId = 0; rangeId < rangeBoundaries.size() - 1; rangeId++) { boundaryById.put(rangeId, rangeBoundaries.get((int)rangeId)); } checkpointer.createCheckpoints(srcTable.getQualifiedName(), boundaryById); rangeMigrator.checkStatus(rangeBoundaries.size()); List<Future<Void>> futures = Lists.newArrayList(); for (long rangeId = 0; rangeId < rangeBoundaries.size() - 1; rangeId++) { byte[] end = rangeBoundaries.get((int)rangeId + 1); RangeRequest range = RangeRequest.builder(). endRowExclusive(end). batchHint(readBatchSize). retainColumns(columnSelection). build(); Callable<Void> task = createMigrationTask( range, rangeId); Callable<Void> wrappedTask = PTExecutors.wrap(task); Future<Void> f = executor.submit(wrappedTask); futures.add(f); } waitForFutures(futures); progress.taskComplete(); }

Target:
public void migrate() { List<byte[]> rangeBoundaries = getRangeBoundaries(); int totalTasks = rangeBoundaries.size() - 1; progress.beginTask("Migrating table " + srcTable + "...", totalTasks); Map<Long, byte[]> boundaryById = Maps.newHashMap(); for (long rangeId = 0; rangeId < rangeBoundaries.size() - 1; rangeId++) { boundaryById.put(rangeId, rangeBoundaries.get((int) rangeId)); } checkpointer.createCheckpoints(srcTable.getQualifiedName(), boundaryById); rangeMigrator.logStatus(rangeBoundaries.size()); List<Future<Void>> futures = Lists.newArrayList(); for (long rangeId = 0; rangeId < rangeBoundaries.size() - 1; rangeId++) { byte[] end = rangeBoundaries.get((int) rangeId + 1); RangeRequest range = RangeRequest.builder() .endRowExclusive(end) .batchHint(readBatchSize) .retainColumns(columnSelection) .build(); Callable<Void> task = createMigrationTask( range, rangeId); Callable<Void> wrappedTask = PTExecutors.wrap(task); Future<Void> future = executor.submit(wrappedTask); futures.add(future); } waitForFutures(futures); progress.taskComplete(); }
Source:
private BufferedWriter writeAsString(String str) throws IOException { int len = str.length(); for ( int i = 0; i < len; i++ ) { char c = str.charAt(i); switch (c) { case '\t': case '\b': case '\n': case '\r': case '\f': case '\"': case '\\': _ps.append('\\').append(c); continue; } _ps.append(c); } return _ps; }

Target:
private void writeAsString(String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); switch (c) { case '\t': case '\b': case '\n': case '\r': case '\f': case '\"': case '\\': bufferedWriter.append('\\').append(c); continue; default: } bufferedWriter.append(c); } }
Source:
public void endAssociation(Xid _tranID, XAResource _theXAResource, int xaState, int txInfoState) throws XAException { List<XAResource> xars = new ArrayList<XAResource>(); int txInfo = getXAResourceState(_theXAResource); if ((txInfo != TxInfo.NOT_ASSOCIATED) && (txInfo != TxInfo.FAILED)) { xars.add(_theXAResource); } for (Object resource : _duplicateResources.keySet()) { XAResource dupXar = (XAResource) resource; if (_theXAResource.isSameRM(dupXar)) { xars.add(dupXar); } } for (XAResource xar : xars) { try { xar.end(_tranID, xaState); setXAResourceState(xar, txInfoState); } catch (XAException e1) { switch (e1.errorCode) { case XAException.XA_RBROLLBACK: case XAException.XA_RBCOMMFAIL: case XAException.XA_RBDEADLOCK: case XAException.XA_RBINTEGRITY: case XAException.XA_RBOTHER: case XAException.XA_RBPROTO: case XAException.XA_RBTIMEOUT: case XAException.XA_RBTRANSIENT: setXAResourceState(xar, txInfoState); } throw e1; } } }

Target:
public void endAssociation(Xid _tranID, XAResource _theXAResource, int xaState, int txInfoState) throws XAException { int txInfo = getXAResourceState(_theXAResource); XAException toThrow = null; if ((txInfo != TxInfo.NOT_ASSOCIATED) && (txInfo != TxInfo.FAILED)) { try { doEnd(_tranID, _theXAResource, xaState, txInfoState); } catch (XAException e) { if (toThrow == null) { toThrow = e; } } } for (Object resource : _duplicateResources.keySet()) { XAResource dupXar = (XAResource) resource; if (_theXAResource.isSameRM(dupXar)) { try { doEnd(_tranID, dupXar, xaState, txInfoState); } catch (XAException e) { if (toThrow == null) { toThrow = e; } } } } if (toThrow != null) { throw toThrow; } }
Source:
public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); if (index >= this.servers.length) { index = ThreadLocalRandom.current().nextInt(this.servers.length); } if (trace) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } }

Target:
public void setServers(Collection<SocketAddress> servers) { this.servers = servers.toArray(new SocketAddress[servers.size()]); index = ThreadLocalRandom.current().nextInt(this.servers.length); if (trace) { log.tracef("New server list is: " + Arrays.toString(this.servers)); } }
Source:
public void notifyListeners(int eventType, Event event) { if (this.dropdownTableViewer != null && !this.dropdownTable.isDisposed()) this.dropdownTable.notifyListeners(eventType, event); }

Target:
public void notifyListeners(int eventType, Event event) { if (this.dropdownTable != null && !this.dropdownTable.isDisposed()) this.dropdownTable.notifyListeners(eventType, event); }
Source:
public void testScrollBarViewShowAllWhenLimitedSpace() { setLayoutRestrictions( true, true, false); onView(withId(androidx.car.test.R.id.page_up)).check(matches(isDisplayed())); onView(withId(androidx.car.test.R.id.scrollbar_thumb)).check(matches(isDisplayed())); onView(withId(androidx.car.test.R.id.alpha_jump)).check(matches(isDisplayed())); }

Target:
public void testScrollBarViewShowAllWhenLimitedSpace() { setLayoutRestrictions( true, true, false); onView(withId(R.id.page_up)).check(matches(isDisplayed())); onView(withId(R.id.scrollbar_thumb)).check(matches(isDisplayed())); onView(withId(R.id.alpha_jump)).check(matches(isDisplayed())); }
Source:
private Uri getImageUri(Context context, Intent data) { String imagePath = null; Uri uri = data.getData(); if (Build.VERSION.SDK_INT >= 19) { if (DocumentsContract.isDocumentUri(context, uri)) { String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(context, contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { imagePath = getImagePath(context, uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { imagePath = uri.getPath(); } } else { uri = data.getData(); imagePath = getImagePath(context, uri, null); } File file = new File(imagePath); mTempImagePath = imagePath; mField.setImagePath(imagePath); mField.setHasTemporaryMedia(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(context, mActivity.getApplicationContext().getPackageName() + ".apkgfileprovider", file); } else { uri = Uri.fromFile(file); } return uri; }

Target:
private Uri getImageUri(Context context, Intent data) { String imagePath = null; Uri uri = data.getData(); if (uri == null) { ToastSender.sendToast(context, context.getString(R.string.select_image_failed), Toast.LENGTH_LONG); return null; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (DocumentsContract.isDocumentUri(context, uri)) { String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection); } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(context, contentUri, null); } } else if ("content".equalsIgnoreCase(uri.getScheme())) { imagePath = getImagePath(context, uri, null); } else if ("file".equalsIgnoreCase(uri.getScheme())) { imagePath = uri.getPath(); } } else { uri = data.getData(); imagePath = getImagePath(context, uri, null); } File file = new File(imagePath); mImagePath = imagePath; mField.setImagePath(imagePath); mField.setHasTemporaryMedia(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(context, mActivity.getApplicationContext().getPackageName() + ".apkgfileprovider", file); } else { uri = Uri.fromFile(file); } return uri; }