auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void parseAddress(XmlPullParser parser, VCard vCard) throws XmlPullParserException, IOException { boolean isWork = true; boolean done = false; while (!done) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG && parser.getName().equals("HOME")) { isWork = false; } else if (eventType == XmlPullParser.START_TAG) { String name = parser.getName(); for (Adr a : Adr.class.getEnumConstants()) { if (a.name().equals(name)) { if (isWork) { vCard.setAddressFieldWork(name, parser.nextText()); } else { vCard.setAddressFieldHome(name, parser.nextText()); } } } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getName().equals("ADR")) { done = true; } } } }

Target:
private void parseAddress(XmlPullParser parser, VCard vCard) throws XmlPullParserException, IOException { int initialDepth = parser.getDepth(); boolean isWork = true; outerloop: while (true) { int eventType = parser.next(); switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); if ("HOME".equals(name)) { isWork = false; } else { for (Adr a : Adr.class.getEnumConstants()) { if (a.name().equals(name)) { if (isWork) { vCard.setAddressFieldWork(name, parser.nextText()); } else { vCard.setAddressFieldHome(name, parser.nextText()); } } } } break; case XmlPullParser.END_TAG: if (parser.getDepth() == initialDepth) { break outerloop; } break; default: break; } } }
Source:
FunctionDef mockFunctionDef(String function) { List<ParamDef> params = new ArrayList<>(); params.add(mockParamDef(PARAM1_NAME, PARAM1_TYPE)); params.add(mockParamDef(PARAM2_NAME, PARAM2_TYPE)); FunctionDef functionDef = new FunctionDef(function, params); when(functionNamingService.getFunctionName(function)).thenReturn(FUNCTION_TRANSLATED_NAME); when(functionNamingService.getParamName(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_HELP); when(functionNamingService.getParamName(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_HELP); return functionDef; }

Target:
private FunctionDef mockFunctionDef(String function) { List<ParamDef> params = new ArrayList<>(); params.add(mockParamDef(PARAM1_NAME, PARAM1_TYPE)); params.add(mockParamDef(PARAM2_NAME, PARAM2_TYPE)); FunctionDef functionDef = new FunctionDef(function, params); when(functionNamingService.getFunctionName(function)).thenReturn(FUNCTION_TRANSLATED_NAME); when(functionNamingService.getParamName(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM1_NAME)).thenReturn(PARAM1_TRANSLATED_HELP); when(functionNamingService.getParamName(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_NAME); when(functionNamingService.getParamHelp(function, PARAM2_NAME)).thenReturn(PARAM2_TRANSLATED_HELP); return functionDef; }
Source:
public void close() { wrappedIterator.close(); }

Target:
public void close() { isOpen = false; wrappedIterator.close(); }
Source:
public void after() throws InterruptedException { if (storageManager != null) { storageManager.shutdown(); } }

Target:
public void after() throws InterruptedException { storageManager.shutdown(); }
Source:
private static TextView createField(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent, @NonNull final FormField field, @NonNull final String value, boolean readOnly, @NonNull View.OnClickListener onClickListener) { final TextView textView = (TextView) inflater.inflate(R.layout.edit_user_profile_field, parent, false); final SpannableString formattedValue = new SpannableString(value); formattedValue.setSpan(new ForegroundColorSpan(parent.getResources().getColor(R.color.edx_brand_gray_base)), 0, formattedValue.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(ResourceUtil.getFormattedString(parent.getResources(), R.string.edit_user_profile_field, new HashMap<String, CharSequence>() {{ put("label", field.getLabel()); put("value", formattedValue); }})); textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < 16) { textView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { textView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } String contentDescription = TextUtils.ellipsize(textView.getText(), textView.getPaint(), (float) textView.getWidth(), TextUtils.TruncateAt.END).toString(); textView.setContentDescription(contentDescription); } }); Context context = parent.getContext(); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds( textView, null, null, new IconDrawable(context, FontAwesomeIcons.fa_angle_right) .colorRes(context, R.color.edx_brand_gray_back) .sizeDp(context, 24), null); if (readOnly) { textView.setEnabled(false); textView.setBackgroundColor(textView.getResources().getColor(R.color.edx_brand_gray_x_back)); } else { textView.setOnClickListener(onClickListener); } parent.addView(textView); return textView; }

Target:
private static TextView createField(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent, @NonNull final FormField field, @NonNull final String value, boolean readOnly, @NonNull View.OnClickListener onClickListener) { final TextView textView = (TextView) inflater.inflate(R.layout.edit_user_profile_field, parent, false); final SpannableString formattedValue = new SpannableString(value); formattedValue.setSpan(new ForegroundColorSpan(parent.getResources().getColor(R.color.edx_brand_gray_base)), 0, formattedValue.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(ResourceUtil.getFormattedString(parent.getResources(), R.string.edit_user_profile_field, new HashMap<String, CharSequence>() {{ put("label", field.getLabel()); put("value", formattedValue); }})); Context context = parent.getContext(); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds( textView, null, null, new IconDrawable(context, FontAwesomeIcons.fa_angle_right) .colorRes(context, R.color.edx_brand_gray_back) .sizeDp(context, 24), null); if (readOnly) { textView.setEnabled(false); textView.setBackgroundColor(textView.getResources().getColor(R.color.edx_brand_gray_x_back)); } else { textView.setOnClickListener(onClickListener); } parent.addView(textView); return textView; }
Source:
private List<Artifact> mergeArtifactLists(List<Artifact> childArtifacts, List<Artifact> parentArtifacts) { List<Artifact> artifactList = new ArrayList<>(); artifactList.addAll(childArtifacts); for (Artifact parentArtifact : parentArtifacts) { boolean found = false; for (Artifact childArtifact : childArtifacts) { if (childArtifact.getArtifactId().equals(parentArtifact.getArtifactId())) { found = true; break; } } if (!found) { artifactList.add(parentArtifact); } } return artifactList; }

Target:
private List<Artifact> mergeArtifactLists(List<Artifact> childArtifacts, List<Artifact> parentArtifacts) { List<Artifact> artifactList = new ArrayList<>(); artifactList.addAll(childArtifacts); for (Artifact parentArtifact : parentArtifacts) { boolean found = false; for (Artifact childArtifact : childArtifacts) { boolean isGroupIdMatch = childArtifact.getGroupId().equals(parentArtifact.getGroupId()); boolean isArtifactIdMatch = childArtifact.getArtifactId().equals(parentArtifact.getArtifactId()); boolean isTypeMatch = childArtifact.getType().equals(parentArtifact.getType()); if (isGroupIdMatch && isArtifactIdMatch && isTypeMatch) { found = true; break; } } if (!found) { artifactList.add(parentArtifact); } } return artifactList; }
Source:
protected VpcOffering createVpcOffering(final String name, final String displayText, final Map<Network.Service, Set<Network.Provider>> svcProviderMap, final boolean isDefault, final VpcOffering.State state, final Long serviceOfferingId) { return Transaction.execute(new TransactionCallback<VpcOffering>() { @Override public VpcOffering doInTransaction(TransactionStatus status) { VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, false, false); if (state != null) { offering.setState(state); } s_logger.debug("Adding vpc offering " + offering); offering = _vpcOffDao.persist(offering); if (svcProviderMap != null) { for (Network.Service service : svcProviderMap.keySet()) { Set<Network.Provider> providers = svcProviderMap.get(service); if (providers != null && !providers.isEmpty()) { for (Network.Provider provider : providers) { VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider); _vpcOffSvcMapDao.persist(offService); s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName()); } } else { throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName()); } } } return offering; } }); }

Target:
protected VpcOffering createVpcOffering(final String name, final String displayText, final Map<Network.Service, Set<Network.Provider>> svcProviderMap, final boolean isDefault, final VpcOffering.State state, final Long serviceOfferingId) { return Transaction.execute(new TransactionCallback<VpcOffering>() { @Override public VpcOffering doInTransaction(TransactionStatus status) { VpcOfferingVO offering = new VpcOfferingVO(name, displayText, isDefault, serviceOfferingId, false, false); if (state != null) { offering.setState(state); } if (s_logger.isDebugEnabled()) { s_logger.debug("Adding vpc offering " + offering); } offering = _vpcOffDao.persist(offering); if (svcProviderMap != null) { for (Network.Service service : svcProviderMap.keySet()) { Set<Network.Provider> providers = svcProviderMap.get(service); if (providers != null && !providers.isEmpty()) { for (Network.Provider provider : providers) { VpcOfferingServiceMapVO offService = new VpcOfferingServiceMapVO(offering.getId(), service, provider); _vpcOffSvcMapDao.persist(offService); if (s_logger.isTraceEnabled()) { s_logger.trace("Added service for the vpc offering: " + offService + " with provider " + provider.getName()); } } } else { throw new InvalidParameterValueException("Provider is missing for the VPC offering service " + service.getName()); } } } return offering; } }); }
Source:
public void test(TestHarness th) { try { client = (LocalMessageProtocolConnection)Connector.open("localmsg://" + PROTO_NAME); testProtocolVersion(th); testScaleImage(th, 0, 100, 100); testScaleImage(th, 1, 0, 0); testScaleImage(th, 10000, 0, 0); testScaleImage(th, 10000, 101, 101); client.close(); } catch (IOException ioe) { th.fail("Unexpected exception"); ioe.printStackTrace(); } }

Target:
public void test(TestHarness th) { try { client = (LocalMessageProtocolConnection)Connector.open("localmsg://" + PROTO_NAME); testProtocolVersion(th); testScaleImage(th, 0, 100, 100); testScaleImage(th, 1, 0, 0); testScaleImage(th, 10000, 0, 0); testScaleImage(th, 10000, 101, 101); testScaleImage(th, 10000, 10000, 10000); client.close(); } catch (IOException ioe) { th.fail("Unexpected exception"); ioe.printStackTrace(); } }
Source:
boolean isDualTable(String tableName) { return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("F", tableName)) || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) && equalsToken("SYSDUMMY1", tableName)); }

Target:
boolean isDualTable(String tableName) { return ((schemaName == null || equalsToken(schemaName, "SYS")) && equalsToken("DUAL", tableName)) || (database.getMode().sysDummy1 && (schemaName == null || equalsToken(schemaName, "SYSIBM")) && equalsToken("SYSDUMMY1", tableName)); }
Source:
void projectionTestHelper(String projectionField, Object expectedValue) { ExtendedSearchIntegrator searchFactory = sfHolder.getSearchFactory(); QueryBuilder guestQueryBuilder = searchFactory.buildQueryBuilder().forEntity( ExampleEntity.class ).get(); Query queryAllGuests = guestQueryBuilder.all().createQuery(); List<EntityInfo> queryEntityInfos = searchFactory.createHSQuery().luceneQuery( queryAllGuests ) .targetedEntities( Arrays.asList( new Class<?>[] { ExampleEntity.class } ) ) .projection( projectionField ) .queryEntityInfos(); Assert.assertEquals( 1, queryEntityInfos.size() ); EntityInfo entityInfo = queryEntityInfos.get( 0 ); Object projectedValue = entityInfo.getProjection()[0]; Assert.assertEquals( expectedValue, projectedValue ); }

Target:
void projectionTestHelper(String projectionField, Object expectedValue) { ExtendedSearchIntegrator searchFactory = sfHolder.getSearchFactory(); QueryBuilder queryBuilder = searchFactory.buildQueryBuilder().forEntity( ExampleEntity.class ).get(); Query queryAllGuests = queryBuilder.all().createQuery(); List<EntityInfo> queryEntityInfos = searchFactory.createHSQuery().luceneQuery( queryAllGuests ) .targetedEntities( Arrays.asList( new Class<?>[] { ExampleEntity.class } ) ) .projection( projectionField ) .queryEntityInfos(); Assert.assertEquals( 1, queryEntityInfos.size() ); EntityInfo entityInfo = queryEntityInfos.get( 0 ); Object projectedValue = entityInfo.getProjection()[0]; Assert.assertEquals( expectedValue, projectedValue ); }
Source:
protected File discoverGitSystemConfig() { File gitExe = discoverGitExe(); if (gitExe == null) return null; Map<String, String> env = new HashMap<>(); env.put("GIT_EDITOR", "echo"); String w = readPipe(gitExe.getParentFile(), new String[]{"git", "config", "--system", "--edit"}, Charset.defaultCharset().name(), env); if (StringUtils.isEmptyOrNull(w)) return null; return new File(w); }

Target:
protected File discoverGitSystemConfig() { File gitExe = discoverGitExe(); if (gitExe == null) { return null; } Map<String, String> env = new HashMap<>(); env.put("GIT_EDITOR", "echo"); String w = readPipe(gitExe.getParentFile(), new String[] { "git", "config", "--system", "--edit" }, Charset.defaultCharset().name(), env); if (StringUtils.isEmptyOrNull(w)) { return null; } return new File(w); }
Source:
public Object getRelation(DataStoreTransaction relationTx, Object entity, String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope scope) { Object values = PersistentResource.getValue(entity, relationName, scope); Map<String, Object> validChildren = new HashMap<>(); if (dictionary.getRelationshipType(entity, relationName).isToOne()) { if (values == null) { return null; } validChildren.put(dictionary.getId(values), values); } else if (values instanceof Collection) { validChildren.putAll((Map) ((Collection) values).stream() .collect(Collectors.toMap(dictionary::getId, Function.identity()))); } else { throw new IllegalStateException("An unexpected error occurred querying a relationship"); } Class entityClass = dictionary.getParameterizedType(entity, relationName); return processData(entityClass, validChildren, filterExpression, sorting, pagination, scope); }

Target:
public Object getRelation(DataStoreTransaction relationTx, Object entity, String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope scope) { Object values = PersistentResource.getValue(entity, relationName, scope); Map<String, Object> idToChildResource = new HashMap<>(); if (dictionary.getRelationshipType(entity, relationName).isToOne()) { if (values == null) { return null; } idToChildResource.put(dictionary.getId(values), values); } else if (values instanceof Collection) { idToChildResource.putAll((Map) ((Collection) values).stream() .collect(Collectors.toMap(dictionary::getId, Function.identity()))); } else { throw new IllegalStateException("An unexpected error occurred querying a relationship"); } Class entityClass = dictionary.getParameterizedType(entity, relationName); return processData(entityClass, idToChildResource, filterExpression, sorting, pagination, scope); }
Source:
public KafkaRyaSubGraphExporter(KafkaProducer<String, RyaSubGraph> producer) { Preconditions.checkNotNull(producer); this.producer = producer; }

Target:
public KafkaRyaSubGraphExporter(KafkaProducer<String, RyaSubGraph> producer) { checkNotNull(producer); this.producer = producer; }
Source:
public static void setUpBeforeClass() throws Exception { Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml"); Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml"); Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml"); String absoluteDataPath = TEST_UTIL.getDataTestDir().toString(); String dataBasePath = System.getProperty(HBaseCommonTestingUtility.BASE_TEST_DIRECTORY_KEY, HBaseCommonTestingUtility.DEFAULT_BASE_TEST_DIRECTORY); String dataPath = absoluteDataPath.substring(absoluteDataPath.indexOf(dataBasePath)); newCnfPath = Paths.get(dataPath + "/hbase-site.xml"); newCnf2Path = Paths.get(dataPath + "/hbase-site2.xml"); newCnf3Path = Paths.get(dataPath + "/hbase-site3.xml"); Files.createDirectories(Paths.get(dataPath)); Files.copy(cnfPath, newCnfPath); Files.copy(cnf2Path, newCnf2Path); Files.copy(cnf3Path, newCnf3Path); TEST_UTIL.getConfiguration().addResource(TEST_UTIL.getDataTestDir("hbase-site.xml")); TEST_UTIL.getConfiguration().setInt(HConstants.MASTER_INFO_PORT, 0); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 60000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, 120000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2); TEST_UTIL.getConfiguration().setInt(START_LOG_ERRORS_AFTER_COUNT_KEY, 0); TEST_UTIL.startMiniCluster(2); ASYNC_CONN = ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get(); for (int i = 0; i < 2; i ++) { TEST_UTIL.getMiniHBaseCluster().getRegionServer(i).getConfiguration(). addResource(TEST_UTIL.getDataTestDir("hbase-site.xml")); } }

Target:
public static void setUpBeforeClass() throws Exception { setUpConfigurationFiles(TEST_UTIL); TEST_UTIL.getConfiguration().setInt(HConstants.MASTER_INFO_PORT, 0); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 60000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, 120000); TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2); TEST_UTIL.getConfiguration().setInt(START_LOG_ERRORS_AFTER_COUNT_KEY, 0); TEST_UTIL.startMiniCluster(2); ASYNC_CONN = ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get(); addResourceToRegionServerConfiguration(TEST_UTIL); }
Source:
private static boolean isValid(final String s) { final int includeTrailingEmpty = -1; final String[] parts = s.split("/", includeTrailingEmpty); boolean wildcard = false; for (int i = 0; i < parts.length; i++) { String part = parts[i]; if (part.length() == 0) return false; if (part.equals("*")) { if (wildcard) return false; wildcard = true; } else if (part.contains("*")) { return false; } } return true; }

Target:
private static boolean isValid(final String s) { if (s.startsWith("/")) return false; if (s.contains(" return false; int i = s.indexOf('*'); if (i != -1) { if (s.indexOf('*', i + 1) > i) return false; if (i > 0 && s.charAt(i - 1) != '/') return false; if (i < s.length() - 1 && s.charAt(i + 1) != '/') return false; } return true; }
Source:
public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig == null) { pathComponents = DEFAULT_PATH_COMPONENTS; return; } if (!StringUtils.isEmpty(filterConfig.getInitParameter(PATH_COMPONENT_PARAM))) { pathComponents = Integer.valueOf(filterConfig.getInitParameter(PATH_COMPONENT_PARAM)); } }

Target:
public void init(FilterConfig filterConfig) throws ServletException { Histogram.Builder builder = Histogram.build() .labelNames("path", "method"); if (filterConfig == null && isEmpty(metricName)) { throw new ServletException("No configuration object provided, and no metricName passed via constructor"); } if (filterConfig != null) { if (isEmpty(metricName)) { metricName = filterConfig.getInitParameter(METRIC_NAME_PARAM); if (isEmpty(metricName)) { throw new ServletException("Init parameter \"" + METRIC_NAME_PARAM + "\" is required; please supply a value"); } } if (!isEmpty(filterConfig.getInitParameter(HELP_PARAM))) { help = filterConfig.getInitParameter(HELP_PARAM); } if (!isEmpty(filterConfig.getInitParameter(PATH_COMPONENT_PARAM))) { pathComponents = Integer.valueOf(filterConfig.getInitParameter(PATH_COMPONENT_PARAM)); } if (!isEmpty(filterConfig.getInitParameter(BUCKET_CONFIG_PARAM))) { String[] bucketParams = filterConfig.getInitParameter(BUCKET_CONFIG_PARAM).split(","); buckets = new double[bucketParams.length]; for (int i = 0; i < bucketParams.length; i++) { buckets[i] = Double.parseDouble(bucketParams[i]); } } } if (buckets != null) { builder = builder.buckets(buckets); } histogram = builder .help(help) .name(metricName) .register(); }
Source:
RecordFlow evictAckedEventAndScheduleNextEvent(RecordsDeliveryAck recordsDeliveryAck) { final RecordsRetrievedContext recordsRetrievedContext = recordsDeliveryQueue.peek(); RecordFlow flowToBeReturned = null; final RecordsRetrieved recordsRetrieved = recordsRetrievedContext != null ? recordsRetrievedContext.getRecordsOrShutDownEvent() .map(recordsEvent -> recordsEvent, shutDownEvent -> null) : null; if (recordsRetrieved != null && recordsRetrieved.batchUniqueIdentifier() .equals(recordsDeliveryAck.batchUniqueIdentifier())) { recordsDeliveryQueue.poll(); takeDelayedDeliveryActionIfRequired(shardId, recordsRetrievedContext.getEnqueueTimestamp(), log); currentSequenceNumber = ((FanoutRecordsRetrieved)recordsRetrieved).continuationSequenceNumber(); flowToBeReturned = recordsRetrievedContext.getRecordFlow(); if (!recordsDeliveryQueue.isEmpty()) { recordsDeliveryQueue.peek().getRecordsOrShutDownEvent() .apply(recordsEvent -> scheduleNextEvent(recordsEvent), shutDownEvent -> shutDownEvent.getSubscriptionShutDownAction().run()); } } else { if (flow != null && recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier() .equals(flow.getSubscribeToShardId())) { log.error( "{}: Received unexpected ack for the active subscription {}. Throwing. ", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); throw new IllegalStateException("Unexpected ack for the active subscription"); } else { log.info("{}: Publisher received an ack for stale subscription {}. Ignoring.", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); } } return flowToBeReturned; }

Target:
RecordFlow evictAckedEventAndScheduleNextEvent(RecordsDeliveryAck recordsDeliveryAck) { final RecordsRetrievedContext recordsRetrievedContext = recordsDeliveryQueue.peek(); RecordFlow flowToBeReturned = null; final RecordsRetrieved recordsRetrieved = recordsRetrievedContext != null ? recordsRetrievedContext.getRecordsRetrieved() : null; if (recordsRetrieved != null && recordsRetrieved.batchUniqueIdentifier() .equals(recordsDeliveryAck.batchUniqueIdentifier())) { recordsDeliveryQueue.poll(); takeDelayedDeliveryActionIfRequired(shardId, recordsRetrievedContext.getEnqueueTimestamp(), log); currentSequenceNumber = ((FanoutRecordsRetrieved)recordsRetrieved).continuationSequenceNumber(); flowToBeReturned = recordsRetrievedContext.getRecordFlow(); if (!recordsDeliveryQueue.isEmpty()) { recordsDeliveryQueue.peek().executeEventAction(subscriber); } } else { if (flow != null && recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier() .equals(flow.getSubscribeToShardId())) { log.error( "{}: Received unexpected ack for the active subscription {}. Throwing. ", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); throw new IllegalStateException("Unexpected ack for the active subscription"); } else { log.info("{}: Publisher received an ack for stale subscription {}. Ignoring.", shardId, recordsDeliveryAck.batchUniqueIdentifier().getFlowIdentifier()); } } return flowToBeReturned; }
Source:
public Set<QualifiedTablePrefix> calculatePrefixesWithTableName( ConnectorSession connectorSession, Set<QualifiedTablePrefix> prefixes, TupleDomain<ColumnHandle> constraint, Predicate<Map<ColumnHandle, NullableValue>> predicate) { Optional<Set<String>> tables = stringFilter(constraint, TABLE_COLUMN_HANDLE); ImmutableSet.Builder<QualifiedTablePrefix> result = ImmutableSet.builder(); if (tables.isPresent()) { for (QualifiedTablePrefix prefix : prefixes) { tables.get().stream() .map(table -> new QualifiedTablePrefix(prefix.getCatalogName(), prefix.getSchemaName().get(), table)) .forEach(result::add); } } else { Session session = ((FullConnectorSession) connectorSession).getSession(); for (QualifiedTablePrefix prefix : prefixes) { Stream.concat( metadata.listTables(session, prefix).stream(), metadata.listViews(session, prefix).stream()) .filter(objectName -> predicate.test(ImmutableMap.of( CATALOG_COLUMN_HANDLE, new NullableValue(createUnboundedVarcharType(), utf8Slice(catalogName)), SCHEMA_COLUMN_HANDLE, new NullableValue(createUnboundedVarcharType(), utf8Slice(objectName.getSchemaName())), TABLE_COLUMN_HANDLE, new NullableValue(createUnboundedVarcharType(), utf8Slice(objectName.getObjectName()))))) .map(QualifiedObjectName::asQualifiedTablePrefix) .forEach(result::add); } } return result.build(); }

Target:
public Set<QualifiedTablePrefix> calculatePrefixesWithTableName( ConnectorSession connectorSession, Set<QualifiedTablePrefix> prefixes, TupleDomain<ColumnHandle> constraint, Predicate<Map<ColumnHandle, NullableValue>> predicate) { Session session = ((FullConnectorSession) connectorSession).getSession(); Optional<Set<String>> tables = filterString(constraint, TABLE_NAME_COLUMN_HANDLE); if (tables.isPresent()) { return prefixes.stream() .flatMap(prefix -> tables.get().stream() .map(table -> new QualifiedObjectName(catalogName, prefix.getSchemaName().get(), table))) .filter(objectName -> metadata.getTableHandle(session, objectName).isPresent() || metadata.getView(session, objectName).isPresent()) .map(QualifiedObjectName::asQualifiedTablePrefix) .collect(toImmutableSet()); } return prefixes.stream() .flatMap(prefix -> Stream.concat( metadata.listTables(session, prefix).stream(), metadata.listViews(session, prefix).stream())) .filter(objectName -> predicate.test(asFixedValues(objectName))) .map(QualifiedObjectName::asQualifiedTablePrefix) .collect(toImmutableSet()); }
Source:
public IterableStream<ServiceBusReceivedMessage> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessage> messages = Flux.create((emitter) -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); }

Target:
public IterableStream<ServiceBusReceivedMessageContext> receive(int maxMessages, Duration maxWaitTime) { if (maxMessages <= 0) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxMessages' cannot be less than or equal to 0. maxMessages: " + maxMessages)); } else if (Objects.isNull(maxWaitTime)) { throw logger.logExceptionAsError( new NullPointerException("'maxWaitTime' cannot be null.")); } else if (maxWaitTime.isNegative() || maxWaitTime.isZero()) { throw logger.logExceptionAsError( new IllegalArgumentException("'maxWaitTime' cannot be zero or less. maxWaitTime: " + maxWaitTime)); } final Flux<ServiceBusReceivedMessageContext> messages = Flux.create(emitter -> queueWork(maxMessages, maxWaitTime, emitter)); return new IterableStream<>(messages); }
Source:
private SortedPositionLinks(PositionLinks positionLinks, int[][] sortedPositionLinks, JoinFilterFunction lessThanFunction) { this.positionLinks = requireNonNull(positionLinks, "positionLinks is null"); this.sortedPositionLinks = requireNonNull(sortedPositionLinks, "sortedPositionLinks is null"); this.lessThanFunction = requireNonNull(lessThanFunction, "lessThanFunction is null"); this.sizeInBytes = INSTANCE_SIZE + positionLinks.getSizeInBytes() + (SizeOf.sizeOf(sortedPositionLinks[0]) * sortedPositionLinks.length); }

Target:
private SortedPositionLinks(PositionLinks positionLinks, int[][] sortedPositionLinks, JoinFilterFunction lessThanFunction) { this.positionLinks = requireNonNull(positionLinks, "positionLinks is null"); this.sortedPositionLinks = requireNonNull(sortedPositionLinks, "sortedPositionLinks is null"); this.lessThanFunction = requireNonNull(lessThanFunction, "lessThanFunction is null"); this.sizeInBytes = INSTANCE_SIZE + positionLinks.getSizeInBytes() + sizeOfPositionLinks(sortedPositionLinks); }
Source:
public ClusterValidator( ClusterDao clusterDao, StoragePoolDao dataCenterDao, Cluster cluster, CpuFlagsManagerHandler cpuFlagsManagerHandler) { this(clusterDao, dataCenterDao, cluster, cpuFlagsManagerHandler, null, null, null, null, null, null); }

Target:
public ClusterValidator( ClusterDao clusterDao, StoragePoolDao dataCenterDao, Cluster cluster, CpuFlagsManagerHandler cpuFlagsManagerHandler) { this.cluster = cluster; this.clusterDao = clusterDao; this.dataCenterDao = dataCenterDao; this.cpuFlagsManagerHandler = cpuFlagsManagerHandler; }
Source:
public String entityId(final Object message) { if (message instanceof JobExecutorActor.Reload) { return _refSerializer.jobRefToEntityID(((JobExecutorActor.Reload) message).getJobRef()); } return null; }

Target:
public String entityId(final Object message) { if (message instanceof JobExecutorActor.Reload) { return _refSerializer.serialize(((JobExecutorActor.Reload) message).getJobRef()); } return null; }
Source:
private boolean verifyMetricsFromSink() throws InterruptedException { Map<String, Long> expectedMetrics = new HashMap<>(); for (GlobalMetric m : PhoenixRuntime.getGlobalPhoenixClientMetrics()) { expectedMetrics.put(m.getMetricType().name(), m.getTotalSum()); } for (int i = 0; i < MAX_RETRIES; i++) { LOG.info("Verifying Global Metrics from Hadoop Sink, Retry: " + (i + 1)); if (verifyMetricsFromSinkOnce(expectedMetrics)) { LOG.info("Values from Hadoop Metrics Sink match actual values"); return true; } Thread.sleep(1000); } return false; }

Target:
private boolean verifyMetricsFromSink() { Map<String, Long> expectedMetrics = new HashMap<>(); for (GlobalMetric m : PhoenixRuntime.getGlobalPhoenixClientMetrics()) { expectedMetrics.put(m.getMetricType().name(), m.getTotalSum()); } for (int i = 0; i < MAX_RETRIES; i++) { LOG.info("Verifying Global Metrics from Hadoop Sink, Retry: " + (i + 1)); if (verifyMetricsFromSinkOnce(expectedMetrics)) { LOG.info("Values from Hadoop Metrics Sink match actual values"); return true; } try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } } return false; }
Source:
private Retryer<MessageSendingResult> createRetryer(final MessageBatch batch, int messageBackoff, int messageTtl, boolean retryClientErrors) { return RetryerBuilder.<MessageSendingResult>newBuilder() .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() .retryIfResult(result -> isConsuming() && !result.succeeded() && (!result.isClientError() || retryClientErrors)) .withWaitStrategy(fixedWait(messageBackoff, MILLISECONDS)) .withStopStrategy(attempt -> attempt.getDelaySinceFirstAttempt() > messageTtl) .withRetryListener(getRetryListener(result -> monitoring.markFailed(batch, subscription, result))) .build(); }

Target:
private Retryer<MessageSendingResult> createRetryer(final MessageBatch batch, int messageBackoff, int messageTtl, boolean retryClientErrors) { return RetryerBuilder.<MessageSendingResult>newBuilder() .retryIfExceptionOfType(IOException.class) .retryIfRuntimeException() .retryIfResult(result -> isConsuming() && !result.succeeded() && shouldRetryOnClientError(retryClientErrors, result)) .withWaitStrategy(fixedWait(messageBackoff, MILLISECONDS)) .withStopStrategy(attempt -> attempt.getDelaySinceFirstAttempt() > messageTtl) .withRetryListener(getRetryListener(result -> monitoring.markFailed(batch, subscription, result))) .build(); }
Source:
private void createOptionGroup(Composite parent) { if (fExperimentName != null) { Group comp = new Group(parent, SWT.SHADOW_NONE); comp.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_OptionsGroupName); GridLayout layout = new GridLayout(2, false); comp.setLayout(layout); GridData data = new GridData(GridData.FILL, GridData.CENTER, true, false); comp.setLayoutData(data); fCreateExperimentCheckbox = new Button(comp, SWT.CHECK); fCreateExperimentCheckbox.setFont(comp.getFont()); fCreateExperimentCheckbox.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_CreateExperimentName); fCreateExperimentCheckbox.setSelection(false); data = new GridData(GridData.BEGINNING, GridData.CENTER, false, false); fCreateExperimentCheckbox.setLayoutData(data); fExperimentNameText = new Text(comp, SWT.NONE); data = new GridData(GridData.FILL, GridData.CENTER, true, false); fExperimentNameText.setLayoutData(data); fExperimentNameText.setText(fExperimentName); fExperimentNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePageCompletion(); } }); fCreateExperimentCheckbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fExperimentNameText.setEnabled(fCreateExperimentCheckbox.getSelection()); } }); } }

Target:
private void createOptionGroup(Composite parent) { if (fExperimentName != null) { Group comp = new Group(parent, SWT.SHADOW_NONE); comp.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_OptionsGroupName); GridLayout layout = new GridLayout(2, false); comp.setLayout(layout); GridData data = new GridData(GridData.FILL, GridData.CENTER, true, false); comp.setLayoutData(data); fCreateExperimentCheckbox = new Button(comp, SWT.CHECK); fCreateExperimentCheckbox.setFont(comp.getFont()); fCreateExperimentCheckbox.setText(RemoteMessages.RemoteFetchLogWizardRemotePage_CreateExperimentName); fCreateExperimentCheckbox.setSelection(false); data = new GridData(GridData.BEGINNING, GridData.CENTER, false, false); fCreateExperimentCheckbox.setLayoutData(data); fExperimentNameText = new Text(comp, SWT.BORDER); data = new GridData(GridData.FILL, GridData.CENTER, true, false); fExperimentNameText.setLayoutData(data); fExperimentNameText.setText(fExperimentName); fExperimentNameText.setEnabled(fCreateExperimentCheckbox.getSelection()); fExperimentNameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { updatePageCompletion(); } }); fCreateExperimentCheckbox.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fExperimentNameText.setEnabled(fCreateExperimentCheckbox.getSelection()); updatePageCompletion(); } }); } }
Source:
static Collection<Column> getColumns(Class<? extends Entity> entityClass) { checkNotNull(entityClass); ensureRegistered(entityClass); return knownEntityProperties.get(entityClass); }

Target:
static Collection<Column> getColumns(Class<? extends Entity> entityClass) { checkNotNull(entityClass); ensureRegistered(entityClass); final Collection<Column> result = knownEntityProperties.get(entityClass); return result; }
Source:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { if (!AcidUtils.isAcidEnabled(context.hiveConf)) { context.log.error("Cannot load alloc write id event as acid is not enabled"); throw new SemanticException("Cannot load alloc write id event as acid is not enabled"); } AllocWriteIdMessage msg = deserializer.getAllocWriteIdMessage(context.dmd.getPayload()); String dbName = (context.dbName != null && !context.dbName.isEmpty() ? context.dbName : msg.getDbName()); String tableName = (context.tableName != null && !context.tableName.isEmpty() ? context.tableName : msg .getTableName()); Table tbl; try { tbl = context.db.getTable(dbName, tableName); } catch (InvalidTableException e) { return new ArrayList<>(); } catch (HiveException e) { throw new SemanticException("Cannot load alloc write id event as get table failed with error: " + e.getMessage()); } Map<String, String> params = tbl.getParameters(); if (params != null && (params.containsKey(ReplicationSpec.KEY.CURR_STATE_ID.toString()))) { String replLastId = params.get(ReplicationSpec.KEY.CURR_STATE_ID.toString()); if (Long.parseLong(replLastId) >= context.dmd.getEventTo()) { return new ArrayList<>(); } } ReplTxnWork work = new ReplTxnWork(dbName, context.tableName, ReplTxnWork.OperationType.REPL_ALLOC_WRITE_ID, msg.getTxnToWriteIdList()); work.setTableName(tableName); Task<? extends Serializable> allocWriteIdTask = TaskFactory.get(work, context.hiveConf); context.log.info("Added alloc write id task : {}", allocWriteIdTask.getId()); updatedMetadata.set(context.dmd.getEventTo().toString(), dbName, tableName, null); return Collections.singletonList(allocWriteIdTask); }

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { if (!AcidUtils.isAcidEnabled(context.hiveConf)) { context.log.error("Cannot load alloc write id event as acid is not enabled"); throw new SemanticException("Cannot load alloc write id event as acid is not enabled"); } AllocWriteIdMessage msg = deserializer.getAllocWriteIdMessage(context.dmd.getPayload()); String dbName = (context.dbName != null && !context.dbName.isEmpty() ? context.dbName : msg.getDB()); String tableName = (context.tableName != null && !context.tableName.isEmpty() ? context.tableName : msg .getTableName()); ReplTxnWork work = new ReplTxnWork(HiveUtils.getReplPolicy(dbName, context.tableName), dbName, tableName, ReplTxnWork.OperationType.REPL_ALLOC_WRITE_ID, msg.getTxnToWriteIdList(), context.eventOnlyReplicationSpec()); Task<? extends Serializable> allocWriteIdTask = TaskFactory.get(work, context.hiveConf); context.log.info("Added alloc write id task : {}", allocWriteIdTask.getId()); updatedMetadata.set(context.dmd.getEventTo().toString(), dbName, tableName, null); return Collections.singletonList(allocWriteIdTask); }
Source:
public Collection<ColumnMeta> getOrderedColumns() { if (needCreator) { List<String> params = new ArrayList<String>(); List<ColumnMeta> orderedColumns = new ArrayList<ColumnMeta>(Collections.<ColumnMeta>nCopies(columns.size(), null)); for (VariableElement param : creator.getParameters()) { params.add(param.getSimpleName().toString()); } for (ColumnMeta column : columns.values()) { orderedColumns.set(params.indexOf(column.getRealElementName()), column); } return orderedColumns; } else { return columns.values(); } }

Target:
public Collection<ColumnMeta> getOrderedColumns() { if (needCreator) { List<String> params = new ArrayList<String>(columns.size()); List<ColumnMeta> orderedColumns = new ArrayList<ColumnMeta>(Collections.<ColumnMeta>nCopies(columns.size(), null)); for (VariableElement param : creator.getParameters()) { params.add(param.getSimpleName().toString()); } for (ColumnMeta column : columns.values()) { orderedColumns.set(params.indexOf(column.getRealElementName()), column); } return orderedColumns; } else { return columns.values(); } }
Source:
public long[] transformToLongValuesSV(ProjectionBlock projectionBlock) { int[] selected = getSelectedArray(projectionBlock); long[] results = new long[DocIdSetPlanNode.MAX_DOC_PER_CALL]; for (int i = 0; i < _elseThenStatements.size(); i++) { TransformFunction transformFunction = _elseThenStatements.get(i); FieldSpec.DataType dataType = transformFunction.getResultMetadata().getDataType(); switch (dataType) { case INT: int[] evalInts = transformFunction.transformToIntValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalInts[j]; } } break; case LONG: long[] evalLongs = transformFunction.transformToLongValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = evalLongs[j]; } } break; case FLOAT: float[] evalFloats = transformFunction.transformToFloatValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = (long) evalFloats[j]; } } break; case DOUBLE: double[] evalDoubles = transformFunction.transformToDoubleValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = (long) evalDoubles[j]; } } break; case STRING: String[] evalStrings = transformFunction.transformToStringValuesSV(projectionBlock); for (int j = 0; j < selected.length; j++) { if (selected[j] == i) { results[j] = new BigDecimal(evalStrings[i]).longValue(); } } break; default: throw new IllegalStateException(String .format("Cannot convert result type [%s] to [LONG] for transform function [%s]", dataType, transformFunction)); } } return results; }

Target:
public long[] transformToLongValuesSV(ProjectionBlock projectionBlock) { if (_resultMetadata.getDataType() != FieldSpec.DataType.LONG) { return super.transformToLongValuesSV(projectionBlock); } int[] selected = getSelectedArray(projectionBlock); if (_longResults == null) { _longResults = new long[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } for (int i = 0; i < _elseThenStatements.size(); i++) { TransformFunction transformFunction = _elseThenStatements.get(i); FieldSpec.DataType dataType = transformFunction.getResultMetadata().getDataType(); int blockNumDocs = projectionBlock.getNumDocs(); long[] evalLongs; if (dataType == FieldSpec.DataType.LONG) { evalLongs = transformFunction.transformToLongValuesSV(projectionBlock); } else { evalLongs = new long[blockNumDocs]; ArrayCopyUtils.copy(transformFunction.transformToIntValuesSV(projectionBlock), evalLongs, blockNumDocs); } for (int j = 0; j < blockNumDocs; j++) { if (selected[j] == i) { _longResults[j] = evalLongs[j]; } } } return _longResults; }
Source:
String getMatchIdxFileName(@NonNull String moduleName) { return ("dld_match_" + moduleName + ".idx").toLowerCase(); }

Target:
String getMatchIdxFileName(@NonNull String moduleName) { return "dld_match_" + moduleName.toLowerCase() + ".idx"; }
Source:
private byte[] _save() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); HashMap<String,Integer> symbolTable = new HashMap<>(); ArrayList<String> symbols = new ArrayList<>(); for (LgBuilder lg : locGroups) { for (SummaryInfo si : lg.summaries) { for (String symbol : si.summary.keySet()) { if (!symbolTable.containsKey(symbol)) { symbolTable.put(symbol, symbols.size()); symbols.add(symbol); } } } } WritableUtils.writeVInt(dos, symbols.size()); for (String symbol : symbols) { dos.writeUTF(symbol); } WritableUtils.writeVInt(dos, locGroups.size()); for (LgBuilder lg : locGroups) { lg.save(dos, symbolTable); } dos.close(); return baos.toByteArray(); }

Target:
private byte[] _save() throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos)) { HashMap<String,Integer> symbolTable = new HashMap<>(); ArrayList<String> symbols = new ArrayList<>(); for (LgBuilder lg : locGroups) { for (SummaryInfo si : lg.summaries) { for (String symbol : si.summary.keySet()) { if (!symbolTable.containsKey(symbol)) { symbolTable.put(symbol, symbols.size()); symbols.add(symbol); } } } } WritableUtils.writeVInt(dos, symbols.size()); for (String symbol : symbols) { dos.writeUTF(symbol); } WritableUtils.writeVInt(dos, locGroups.size()); for (LgBuilder lg : locGroups) { lg.save(dos, symbolTable); } dos.close(); return baos.toByteArray(); } }
Source:
public boolean createHook() { if (ghRepository == null) { logger.log(Level.INFO, "Repository not available, cannot set pull request hook for repository {0}", reponame); return false; } try { if (hookExist()) { return true; } Map<String, String> config = new HashMap<String, String>(); String secret = getSecret(); config.put("url", new URL(getHookUrl()).toExternalForm()); config.put("insecure_ssl", "1"); if (secret != null && !secret.equals("")) { config.put("secret", secret); } ghRepository.createHook("web", config, HOOK_EVENTS, true); return true; } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn''t create web hook for repository {0}. Does the user (from global configuration) have admin rights to the repository?", reponame); return false; } }

Target:
public boolean createHook() { if (ghRepository == null) { logger.log(Level.INFO, "Repository not available, cannot set pull request hook for repository {0}", reponame); return false; } try { if (hookExist()) { return true; } Map<String, String> config = new HashMap<String, String>(); String secret = getSecret(); config.put("url", new URL(getHookUrl()).toExternalForm()); config.put("insecure_ssl", "1"); if (!StringUtils.isEmpty(secret)) { config.put("secret", secret); } ghRepository.createHook("web", config, HOOK_EVENTS, true); return true; } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn''t create web hook for repository {0}. Does the user (from global configuration) have admin rights to the repository?", reponame); return false; } }
Source:
@Override public boolean canHandleSource(@NonNull BufferedSource source) { try { if (Utils.isWebPFile(source)) { return true; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(source.peek().inputStream(), null, options); return options.outWidth > 0 && options.outHeight > 0; } catch (IOException e) { return false; } }

Target:
@Override public boolean canHandleSource(@NonNull BufferedSource source) { try { if (Utils.isWebPFile(source)) { return true; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(source.inputStream(), null, options); return options.outWidth > 0 && options.outHeight > 0; } catch (IOException e) { return false; } }