auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public KafkaMirrorMakerConnector(String connectorName, Properties config, String clusterName) { super(connectorName, config, new KafkaMirrorMakerGroupIdConstructor( Boolean.parseBoolean(config.getProperty(IS_GROUP_ID_HASHING_ENABLED, Boolean.FALSE.toString())), clusterName), clusterName, LOG); _isFlushlessModeEnabled = Boolean.parseBoolean(config.getProperty(IS_FLUSHLESS_MODE_ENABLED, Boolean.FALSE.toString())); _partitionFetchIntervalMs = Long.parseLong(config.getProperty(PARTITION_FETCH_INTERVAL, Long.toString(DEFAULT_PARTITION_FETCH_INTERVAL))); VerifiableProperties verifiableProperties = new VerifiableProperties(config); _consumerProperties = verifiableProperties.getDomainProperties(KafkaBasedConnectorConfig.DOMAIN_KAFKA_CONSUMER); _listenerConsumerFactory = new KafkaConsumerFactoryImpl(); _enablePartitionAssignment = _config.getEnablePartitionAssignment(); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); _shutdown = false; }

Target:
public KafkaMirrorMakerConnector(String connectorName, Properties config, String clusterName) { super(connectorName, config, new KafkaMirrorMakerGroupIdConstructor( Boolean.parseBoolean(config.getProperty(IS_GROUP_ID_HASHING_ENABLED, Boolean.FALSE.toString())), clusterName), clusterName, LOG); _isFlushlessModeEnabled = Boolean.parseBoolean(config.getProperty(IS_FLUSHLESS_MODE_ENABLED, Boolean.FALSE.toString())); _partitionFetchIntervalMs = Long.parseLong(config.getProperty(PARTITION_FETCH_INTERVAL, Long.toString(DEFAULT_PARTITION_FETCH_INTERVAL))); VerifiableProperties verifiableProperties = new VerifiableProperties(config); _consumerProperties = verifiableProperties.getDomainProperties(KafkaBasedConnectorConfig.DOMAIN_KAFKA_CONSUMER); _listenerConsumerFactory = new KafkaConsumerFactoryImpl(); _enablePartitionAssignment = _config.getEnablePartitionAssignment(); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); _shutdown = false; if (_enablePartitionAssignment) { LOG.info("PartitionAssignment enabled for KafkaMirrorConnector"); } }
Source:
public void onEvent(StatusUpdateEvent event, long sequence, boolean endOfBatch) throws Exception { TaskStatus status = event.getStatus(); this.schedulerState.updateTask(status); TaskID taskId = status.getTaskId(); NodeTask task = schedulerState.getTask(taskId); if (task == null) { LOGGER.warn("Task: not found, status: {}", taskId.getValue(), status.getState()); return; } LOGGER.info("Status Update for task: | state: {}", taskId.getValue(), status.getState()); TaskState state = status.getState(); switch (state) { case TASK_STAGING: schedulerState.makeTaskStaging(taskId); break; case TASK_STARTING: schedulerState.makeTaskStaging(taskId); break; case TASK_RUNNING: schedulerState.makeTaskActive(taskId); break; case TASK_FINISHED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_FAILED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; case TASK_KILLED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_LOST: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; default: LOGGER.error("Invalid state: {}", state); break; } }

Target:
public void onEvent(StatusUpdateEvent event, long sequence, boolean endOfBatch) throws Exception { TaskStatus status = event.getStatus(); this.schedulerState.updateTask(status); TaskID taskId = status.getTaskId(); NodeTask task = schedulerState.getTask(taskId); if (task == null) { LOGGER.warn("Task: not found, status: {}", taskId.getValue(), status.getState()); schedulerState.removeTask(taskId); return; } LOGGER.info("Status Update for task: | state: {}", taskId.getValue(), status.getState()); TaskState state = status.getState(); switch (state) { case TASK_STAGING: schedulerState.makeTaskStaging(taskId); break; case TASK_STARTING: schedulerState.makeTaskStaging(taskId); break; case TASK_RUNNING: schedulerState.makeTaskActive(taskId); break; case TASK_FINISHED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_FAILED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; case TASK_KILLED: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.removeTask(taskId); break; case TASK_LOST: offerLifecycleManager.declineOutstandingOffers(task.getHostname()); schedulerState.makeTaskPending(taskId); break; default: LOGGER.error("Invalid state: {}", state); break; } }
Source:
public void testValidatePropertyIsNotEmptyWithEmptyValue() { doNothing().when(listPresenter).addToListElement(any()); final List<Property> objs = Collections.singletonList(new Property("foo", " ")); listPresenter.setup(mock(HTMLElement.class), objs, (a, b) -> { }); persistencePresenter.validatePropertyIsNotEmpty(listPresenter.getObjectsList(), "Message").then(e -> { Assert.fail("Promise should've not been resolved!"); return promises.resolve(); }).catch_(e -> { Assert.assertEquals(e, "Message"); return promises.resolve(); }); }

Target:
public void testValidatePropertyIsNotEmptyWithEmptyValue() { setupProperty("foo", " "); validatePropertyIsNotEmptyOnCatch(); }
Source:
public void run(Duration timeout) throws SamzaException, TimeoutException { Preconditions.checkState((app == null && taskClass != null) || (app != null && taskClass == null), "TestRunner should run for Low Level Task api or High Level Application Api"); final LocalApplicationRunner runner = new LocalApplicationRunner(new MapConfig(configs)); boolean timedOut = false; if (app == null) { runner.runTask(); timedOut = !runner.waitForFinish(timeout); } else { runner.run(app); timedOut = !runner.waitForFinish(timeout); } if (timedOut) { throw new TimeoutException("Timed out waiting for application to finish"); } ApplicationStatus status = runner.status(app); if (status.getStatusCode() == ApplicationStatus.StatusCode.UnsuccessfulFinish) { throw new SamzaException(status.getThrowable()); } }

Target:
public void run(Duration timeout) { Preconditions.checkState((app == null && taskClass != null) || (app != null && taskClass == null), "TestRunner should run for Low Level Task api or High Level Application Api"); Preconditions.checkState(!timeout.isZero() || !timeout.isNegative(), "Timeouts should be positive"); final LocalApplicationRunner runner = new LocalApplicationRunner(new MapConfig(configs)); if (app == null) { runner.runTask(); } else { runner.run(app); } boolean timedOut = !runner.waitForFinish(timeout); Assert.assertFalse("Timed out waiting for application to finish", timedOut); ApplicationStatus status = runner.status(app); if (status.getStatusCode() == ApplicationStatus.StatusCode.UnsuccessfulFinish) { throw new SamzaException(ExceptionUtils.getStackTrace(status.getThrowable())); } }
Source:
public Model getPomModel() { if (getPom() != null && getPom().isFile()) { try { try (InputStream is = new FileInputStream(getPom())) { return new MavenXpp3Reader().read(is, false); } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } } else if (getArtifact() != null && getArtifact().isFile()) { ZipHandle handle = null; try { handle = ZipFacade.getZipHandle(getArtifact()); final String embeddedPomPath = "META-INF/maven/" + getGav().getGroupId() + "/" + getGav().getArtifactId() + "/pom.xml"; if (handle.hasEntry(embeddedPomPath)) { try (InputStream is = handle.getEntryContent(embeddedPomPath)) { return new MavenXpp3Reader().read(is, false); } } } catch (IOException e) { e.printStackTrace(); } catch (XmlPullParserException e) { e.printStackTrace(); } finally { try { ZipFacade.close(handle); } catch (Exception e) { } } } return null; }

Target:
public Model getPomModel() { if (getPom() != null && getPom().isFile()) { try { try (InputStream is = new FileInputStream(getPom())) { return new MavenXpp3Reader().read(is, false); } } catch (IOException | XmlPullParserException e) { logger.error(e.getMessage(), e); } } else if (getArtifact() != null && getArtifact().isFile()) { ZipHandle handle = null; try { handle = ZipFacade.getZipHandle(getArtifact()); final String embeddedPomPath = "META-INF/maven/" + getGav().getGroupId() + "/" + getGav().getArtifactId() + "/pom.xml"; if (handle.hasEntry(embeddedPomPath)) { try (InputStream is = handle.getEntryContent(embeddedPomPath)) { return new MavenXpp3Reader().read(is, false); } } } catch (IOException | XmlPullParserException e) { logger.error(e.getMessage(), e); } finally { try { ZipFacade.close(handle); } catch (Exception e) { logger.warn(e.getMessage(), e); } } } return null; }
Source:
public void doGet(HttpServletRequest request, HttpServletResponse response ) throws IOException { final Map<String,String[]> pmap = request.getParameterMap(); final PrintWriter out = response.getWriter(); final InetAddress remoteAddress = InetAddress.getByName(request.getRemoteAddr()); final ServletContext context = getServletContext(); final Configuration conf = RouterHttpServer.getConfFromContext(context); final UserGroupInformation ugi = getUGI(request, conf); try { ugi.doAs((PrivilegedExceptionAction<Object>) () -> { Router router = RouterHttpServer.getRouterFromContext(context); new RouterFsck(router, pmap, out, remoteAddress).fsck(); return null; }); } catch (InterruptedException e) { response.sendError(400, e.getMessage()); } }

Target:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { final Map<String, String[]> pmap = request.getParameterMap(); final PrintWriter out = response.getWriter(); final InetAddress remoteAddress = InetAddress.getByName(request.getRemoteAddr()); final ServletContext context = getServletContext(); final Configuration conf = RouterHttpServer.getConfFromContext(context); final UserGroupInformation ugi = getUGI(request, conf); try { ugi.doAs((PrivilegedExceptionAction<Object>) () -> { Router router = RouterHttpServer.getRouterFromContext(context); new RouterFsck(router, pmap, out, remoteAddress).fsck(); return null; }); } catch (InterruptedException e) { response.sendError(HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage()); } }
Source:
public void test() { connect(); Assert.assertEquals("", getZKLog()); }

Target:
public void test() { connect(); Assert.assertFalse(isZKLogAvailable()); }
Source:
protected void downloadSingleFile(CloudFile cloudFile) throws WAStorageException { final DownloadServiceData serviceData = getServiceData(); try { println("Downloading file:" + cloudFile.getUri().toString()); final FilePath destFile = destinationFilePath(cloudFile.getName()); final long startTime = System.currentTimeMillis(); cloudFile.downloadAttributes(); try (OutputStream fos = destFile.write()) { cloudFile.download(fos, null, new FileRequestOptions(), Utils.updateUserAgent(cloudFile.getProperties().getLength())); } final long endTime = System.currentTimeMillis(); println(String.format( "blob %s is downloaded to %s in %s", cloudFile.getName(), destFile.getParent(), getTime(endTime - startTime))); Map<String, String> properties = new HashMap<>(); properties.put("StorageAccount", AppInsightsUtils.hash(cloudFile.getServiceClient().getCredentials().getAccountName())); properties.put("ContentLength", String.valueOf(cloudFile.getProperties().getLength())); AzureStoragePlugin.sendEvent(AppInsightsConstants.AZURE_FILE_STORAGE, DOWNLOAD, properties); if (serviceData.isDeleteFromAzureAfterDownload()) { cloudFile.deleteIfExists(); println("cloud file " + cloudFile.getName() + " is deleted from Azure."); } } catch (IOException | InterruptedException | StorageException e) { throw new WAStorageException(e.getMessage(), e); } }

Target:
protected void downloadSingleFile(CloudFile cloudFile) throws WAStorageException { final DownloadServiceData serviceData = getServiceData(); String hashedStorageAcc = AppInsightsUtils.hash(cloudFile.getServiceClient().getCredentials().getAccountName()); try { println("Downloading file:" + cloudFile.getUri().toString()); final FilePath destFile = destinationFilePath(cloudFile.getName()); final long startTime = System.currentTimeMillis(); cloudFile.downloadAttributes(); try (OutputStream fos = destFile.write()) { cloudFile.download(fos, null, new FileRequestOptions(), Utils.updateUserAgent(cloudFile.getProperties().getLength())); } final long endTime = System.currentTimeMillis(); println(String.format( "blob %s is downloaded to %s in %s", cloudFile.getName(), destFile.getParent(), getTime(endTime - startTime))); AzureStoragePlugin.sendEvent(AppInsightsConstants.AZURE_FILE_STORAGE, DOWNLOAD, "StorageAccount", hashedStorageAcc, "ContentLength", String.valueOf(cloudFile.getProperties().getLength())); if (serviceData.isDeleteFromAzureAfterDownload()) { cloudFile.deleteIfExists(); println("cloud file " + cloudFile.getName() + " is deleted from Azure."); } } catch (IOException | InterruptedException | StorageException e) { AzureStoragePlugin.sendEvent(AppInsightsConstants.AZURE_FILE_STORAGE, DOWNLOAD_FAILED, "StorageAccount", hashedStorageAcc, "ContentLength", String.valueOf(cloudFile.getProperties().getLength()), "Message", e.getMessage()); throw new WAStorageException(e.getMessage(), e); } }
Source:
public CircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH); mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR); mBorderInset = a.getBoolean(R.styleable.CircleImageView_border_inset, DEFAULT_BORDER_INSET ); a.recycle(); init(); }

Target:
public CircleImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0); mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH); mBorderColor = a.getColor(R.styleable.CircleImageView_border_color, DEFAULT_BORDER_COLOR); mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_border_overlay, DEFAULT_BORDER_OVERLAY); a.recycle(); init(); }
Source:
public void setUp() { org.junit.Assume.assumeTrue(hasBundle(WIN_BUNDLE)); }

Target:
public void setUp() { org.junit.Assume.assumeTrue(hasBundle(is64Bit ? WIN_64BIT_BUNDLE : WIN_BUNDLE)); }
Source:
public void pointsAreWrittenToInfluxDb() throws Exception { InfluxDbWriter writer = getTestInfluxDbWriterWithDefaultSettings(); writer.doWrite(dummyServer(), dummyQuery(), results); verify(influxDB).write(messageCaptor.capture()); BatchPoints batchPoints = messageCaptor.getValue(); assertThat(batchPoints.getDatabase()).isEqualTo(DATABASE_NAME); Map<String, String> expectedTags = new TreeMap<String, String>(); expectedTags.put(enumValueToAttribute(ResultAttribute.ATTRIBUTE_NAME), result.getAttributeName()); expectedTags.put(enumValueToAttribute(ResultAttribute.CLASS_NAME), result.getClassName()); expectedTags.put(enumValueToAttribute(ResultAttribute.OBJ_DOMAIN), result.getObjDomain()); expectedTags.put(TAG_HOSTNAME, HOST); String lineProtocol = buildLineProtocol(result.getKeyAlias(), expectedTags); List<Point> points = batchPoints.getPoints(); assertThat(points).hasSize(1); Point point = points.get(0); String pointLineProtocol = point.lineProtocol(); assertThat(pointLineProtocol).startsWith(lineProtocol); String[] split = pointLineProtocol.split(" "); assertThat(split).hasSize(3); assertThat(split[1]).contains(JMX_PORT_KEY + "=" + DEFAULT_PORT); }

Target:
public void pointsAreWrittenToInfluxDb() throws Exception { BatchPoints batchPoints = writeToInfluxDb(getTestInfluxDbWriterWithDefaultSettings()); assertThat(batchPoints.getDatabase()).isEqualTo(DATABASE_NAME); Map<String, String> expectedTags = new TreeMap<String, String>(); expectedTags.put(ResultAttributes.ATTRIBUTE_NAME.getName() , result.getAttributeName()); expectedTags.put(ResultAttributes.CLASS_NAME.getName(), result.getClassName()); expectedTags.put(ResultAttributes.OBJ_DOMAIN.getName (), result.getObjDomain()); expectedTags.put(TAG_HOSTNAME, HOST); String lineProtocol = buildLineProtocol(result.getKeyAlias(), expectedTags); List<Point> points = batchPoints.getPoints(); assertThat(points).hasSize(1); Point point = points.get(0); assertThat(point.lineProtocol()).startsWith(lineProtocol); }
Source:
public synchronized AdHocPlannedStatement planSqlCalcite(SqlTask task) throws ValidationException, RelConversionException, PlannerFallbackException { VoltPlanner planner = new VoltPlanner(m_schemaPlus); planner.validate(task.getParsedQuery()); RelNode rel = planner.convert(task.getParsedQuery()); compileLog.info("ORIGINAL\n" + RelOptUtil.toString(rel)); RelTraitSet requiredLogicalOutputTraits = planner.getEmptyTraitSet().replace(VoltLogicalRel.CONVENTION); RelNode transformed = planner.transform( PlannerRules.Phase.LOGICAL.ordinal(), requiredLogicalOutputTraits, rel); compileLog.info("LOGICAL\n" + RelOptUtil.toString(transformed)); planner.addRelTraitDef(RelDistributionTraitDef.INSTANCE); transformed = VoltRelUtil.addTraitRecurcively(transformed, RelDistributions.SINGLETON); transformed = VoltPlanner.transformHep(PlannerRules.Phase.MP_FALLBACK, HepMatchOrder.BOTTOM_UP, transformed, false); RelTraitSet physicalTraits = transformed.getTraitSet().replace(VoltPhysicalRel.CONVENTION). replace(RelDistributions.ANY); transformed = planner.transform(PlannerRules.Phase.PHYSICAL_CONVERSION.ordinal(), physicalTraits, transformed); Util.discard(transformed); planner.close(); throw new PlannerFallbackException(); }

Target:
public synchronized AdHocPlannedStatement planSqlCalcite(SqlTask task) throws ValidationException, RelConversionException, PlannerFallbackException { VoltPlanner planner = new VoltPlanner(m_schemaPlus); SqlNode validatedQuery = planner.validate(task.getParsedQuery()); RelNode rel = planner.convert(validatedQuery); compileLog.info("ORIGINAL\n" + RelOptUtil.toString(rel)); RelTraitSet requiredLogicalOutputTraits = planner.getEmptyTraitSet().replace(VoltLogicalRel.CONVENTION); RelNode transformed = planner.transform( Phase.LOGICAL.ordinal(), requiredLogicalOutputTraits, rel); compileLog.info("LOGICAL\n" + RelOptUtil.toString(transformed)); planner.addRelTraitDef(RelDistributionTraitDef.INSTANCE); transformed = VoltRelUtil.addTraitRecurcively(transformed, RelDistributions.ANY); transformed = VoltPlanner.transformHep(Phase.MP_FALLBACK, transformed); RelTraitSet requiredPhysicalOutputTraits = transformed.getTraitSet() .replace(VoltPhysicalRel.CONVENTION) .replace(RelDistributions.ANY); transformed = planner.transform(Phase.PHYSICAL_CONVERSION.ordinal(), requiredPhysicalOutputTraits, transformed); Util.discard(transformed); planner.close(); throw new PlannerFallbackException(); }
Source:
public MultipleHostsModel() { setHosts(new ListModel()); setUseCommonPassword(new EntityModel()); setCommonPassword(new EntityModel()); setApplyPasswordCommand(new UICommand("ApplyPassword", this)); setEnableFirewall(false); getUseCommonPassword().getEntityChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { getCommonPassword().setIsChangable((Boolean) getUseCommonPassword().getEntity()); getApplyPasswordCommand().setIsExecutionAllowed((Boolean) getUseCommonPassword().getEntity()); } }); getUseCommonPassword().setEntity(false); }

Target:
public MultipleHostsModel() { setHosts(new ListModel()); setUseCommonPassword(new EntityModel()); setCommonPassword(new EntityModel()); setApplyPasswordCommand(new UICommand("ApplyPassword", this)); setConfigureFirewall(true); getUseCommonPassword().getEntityChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { getCommonPassword().setIsChangable((Boolean) getUseCommonPassword().getEntity()); getApplyPasswordCommand().setIsExecutionAllowed((Boolean) getUseCommonPassword().getEntity()); } }); getUseCommonPassword().setEntity(false); }
Source:
public String ensureReadData(final String path) { Random rn = new Random(); int jitter; int retry = 1; int step = 50; int counter = 0; String content = this.readData(path); while (content == null) { counter++; jitter = rn.nextInt(100); long wait = retry * step + jitter; try { Thread.sleep(wait); } catch (InterruptedException e) { LOG.error("Failed to sleep at retry: " + counter + " " + e.getMessage()); } content = super.readData(path, false ); } return content; }

Target:
public String ensureReadData(final String path) { return ensureReadData(path, _zkSessionTimeoutMs); }
Source:
public void phoneSignIn() { String cacheKey = TestConstants.PHONE.getNumber() + ":api:phoneSignInRequest"; when(cacheProvider.getString(cacheKey)).thenReturn(TOKEN); when(accountDao.getAccountAfterAuthentication(ACCOUNT_ID_WITH_PHONE)).thenReturn(account); when(participantService.getParticipant(study, account, false)).thenReturn(PARTICIPANT); when(consentService.getConsentStatuses(any())).thenReturn(CONSENTED_STATUS_MAP); service.phoneSignIn(CONTEXT, SIGN_IN_WITH_PHONE); verify(cacheProvider).removeString(cacheKey); verify(accountDao).verifyChannel(ChannelType.PHONE, account); }

Target:
public void phoneSignIn() { StudyParticipant participant = new StudyParticipant.Builder() .withEmail(RECIPIENT_EMAIL).withFirstName("Test").withLastName("Tester").build(); String cacheKey = TestConstants.PHONE.getNumber() + ":api:phoneSignInRequest"; when(cacheProvider.getString(cacheKey)).thenReturn(TOKEN); when(accountDao.getAccountAfterAuthentication(ACCOUNT_ID_WITH_PHONE)).thenReturn(account); when(participantService.getParticipant(study, account, false)).thenReturn(participant); when(consentService.getConsentStatuses(any())).thenReturn(CONSENTED_STATUS_MAP); UserSession session = service.phoneSignIn(CONTEXT, SIGN_IN_WITH_PHONE); assertEquals(RECIPIENT_EMAIL, session.getParticipant().getEmail()); assertEquals("Test", session.getParticipant().getFirstName()); assertEquals("Tester", session.getParticipant().getLastName()); verify(cacheProvider).removeString(cacheKey); verify(accountDao).verifyChannel(ChannelType.PHONE, account); }
Source:
public void start() throws Exception { doStart(); }

Target:
void start() throws Exception { doStart(); }
Source:
public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); this.addPermission(role, host, true); rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); assertEquals(1, allRules.size()); final Rule ruleFromDataBase = allRules.get(0); final List<ConditionGroup> groups = ruleFromDataBase.getGroups(); assertEquals(1, groups.size()); assertEquals(groups.get(0).getOperator(), conditionGroup.getOperator()); final Condition condition = new ConditionDataGen().group(groups.get(0)).next(); rulesAPI.saveCondition(condition, user, false); allRules = rulesAPI.getAllRules(user, false); assertEquals(1, allRules.size()); final List<Condition> conditions = allRules.get(0).getGroups().get(0).getConditions(); assertEquals(1, conditions.size()); assertEquals(condition.getOperator(), conditions.get(0).getOperator()); }

Target:
public void shouldSaveCondition() throws DotSecurityException, DotDataException { final Role role = new RoleDataGen().nextPersisted(); final User user = new UserDataGen().roles(role).nextPersisted(); final Host host = new SiteDataGen().nextPersisted(); final Rule rule = new RuleDataGen().host(host).nextPersisted(); final ConditionGroup conditionGroup = new ConditionGroupDataGen().rule(rule).next(); this.addPermission(role, host, true); rulesAPI.saveConditionGroup(conditionGroup, user, false); List<Rule> allRules = rulesAPI.getAllRules(user, false); assertEquals(1, allRules.size()); final Rule ruleFromDataBase = allRules.get(0); final List<ConditionGroup> groups = ruleFromDataBase.getGroups(); assertEquals(1, groups.size()); assertEquals(conditionGroup.getOperator(), groups.get(0).getOperator()); final Condition condition = new ConditionDataGen().group(groups.get(0)).next(); rulesAPI.saveCondition(condition, user, false); allRules = rulesAPI.getAllRules(user, false); final List<Condition> conditions = allRules.get(0).getGroups().get(0).getConditions(); assertEquals(1, conditions.size()); assertEquals(condition.getOperator(), conditions.get(0).getOperator()); }
Source:
private Language fromDbMap(final Map<String, Object> resultSet){ if(resultSet==null) { return null; } final long id = toLong(resultSet.get("id"), 0L); final String langCode = (resultSet.get("language_code")!=null) ? String.valueOf(resultSet.get("language_code")): null; final String countryCode = (resultSet.get("country_code")!=null) ? String.valueOf(resultSet.get("country_code")) : null; final String language = (resultSet.get("language")!=null) ? String.valueOf(resultSet.get("language")) : null; final String country = (resultSet.get("country")!=null) ? String.valueOf(resultSet.get("country")) : null; return new Language(id, langCode, countryCode, language, country); }

Target:
private Language fromDbMap(final Map<String, Object> resultSet) { if (resultSet == null) { return null; } return new LanguageTransformer(Collections.singletonList(resultSet)).findFirst(); }
Source:
protected ChangeLogScmResult executeChangeLogCommand( ChangeLogScmRequest request ) throws ScmException { final ScmVersion startVersion = request.getStartRevision(); final ScmVersion endVersion = request.getEndRevision(); final ScmFileSet fileSet = request.getScmFileSet(); final String datePattern = request.getDatePattern(); return executeChangeLogCommand( request.getScmRepository().getProviderRepository(), fileSet, request.getStartDate(), request.getEndDate(), request.getScmBranch(), datePattern, startVersion, endVersion, request.getLimit(), request.getRevision() ); }

Target:
protected ChangeLogScmResult executeChangeLogCommand( ChangeLogScmRequest request ) throws ScmException { final ScmVersion startVersion = request.getStartRevision(); final ScmVersion endVersion = request.getEndRevision(); final ScmVersion revision = request.getRevision(); final ScmFileSet fileSet = request.getScmFileSet(); final String datePattern = request.getDatePattern(); final ScmProviderRepository providerRepository = request.getScmRepository().getProviderRepository(); final Date startDate = request.getStartDate(); final Date endDate = request.getEndDate(); final ScmBranch branch = request.getScmBranch(); final Integer limit = request.getLimit(); return executeChangeLogCommand( providerRepository, fileSet, startDate, endDate, branch, datePattern, startVersion, endVersion, limit, revision ); }
Source:
public ShowFileContentResponse execute() throws GitException { if (file == null) { throw new GitException("No file was set."); } reset(); commandLine.add("show"); commandLine.add(version + ":" + file); start(); String content = ""; for (int i = 0; i < lines.size(); i++) { content = content.concat(lines.get(i).concat(i + 1 == lines.size() ? "" : "\n")); } return newDto(ShowFileContentResponse.class).withContent(content); }

Target:
public ShowFileContentResponse execute() throws GitException { if (file == null) { throw new GitException("No file was set."); } reset(); commandLine.add("show"); commandLine.add(version + ":" + file); start(); String content = lines.stream().collect(Collectors.joining(lineSeparator())); return newDto(ShowFileContentResponse.class).withContent(content); }
Source:
public final SymbolToken getKnownFieldNameSymbol() { SymbolToken token = this.getFieldNameSymbol(); if(this.getFieldName() == null && token.getSid() != 0) { throw new UnknownSymbolException(_fieldId); } return token; }

Target:
public final SymbolToken getKnownFieldNameSymbol() { SymbolToken token = this.getFieldNameSymbol(); if (token.getText() == null && token.getSid() != 0) { throw new UnknownSymbolException(_fieldId); } return token; }
Source:
public MetricRegistry provide() { MetricRegistry registry = new MetricRegistry(); if (configFactory.getBooleanProperty(Configs.METRICS_GRAPHITE_REPORTER)) { Set<MetricAttribute> disabledAttributes = new HashSet<>( Lists.newArrayList( MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.MEAN, MetricAttribute.MEAN_RATE, MetricAttribute.MIN, MetricAttribute.P50, MetricAttribute.P75, MetricAttribute.P95, MetricAttribute.STDDEV ) ); String prefix = Joiner.on(".").join( configFactory.getStringProperty(Configs.GRAPHITE_PREFIX), moduleName, hostnameResolver.resolve().replaceAll("\\.", HermesMetrics.REPLACEMENT_CHAR)); GraphiteReporter .forRegistry(registry) .prefixedWith(prefix) .disabledMetricAttributes(disabledAttributes) .build(new Graphite(new InetSocketAddress( configFactory.getStringProperty(Configs.GRAPHITE_HOST), configFactory.getIntProperty(Configs.GRAPHITE_PORT) ))) .start(configFactory.getIntProperty(Configs.REPORT_PERIOD), TimeUnit.SECONDS); } if (configFactory.getBooleanProperty(Configs.METRICS_CONSOLE_REPORTER)) { ConsoleReporter.forRegistry(registry).build().start( configFactory.getIntProperty(Configs.REPORT_PERIOD), TimeUnit.SECONDS ); } if (configFactory.getBooleanProperty(Configs.METRICS_ZOOKEEPER_REPORTER)) { new ZookeeperCounterReporter(registry, counterStorage, configFactory).start( configFactory.getIntProperty(Configs.REPORT_PERIOD), TimeUnit.SECONDS ); } registerJvmMetrics(registry); return registry; }

Target:
public MetricRegistry provide() { MetricRegistry registry = new MetricRegistry(); if (configFactory.getBooleanProperty(Configs.METRICS_GRAPHITE_REPORTER)) { Set<MetricAttribute> disabledAttributes = Sets.newHashSet( MetricAttribute.M15_RATE, MetricAttribute.M5_RATE, MetricAttribute.MEAN, MetricAttribute.MEAN_RATE, MetricAttribute.MIN, MetricAttribute.STDDEV ); String prefix = Joiner.on(".").join( configFactory.getStringProperty(Configs.GRAPHITE_PREFIX), moduleName, hostnameResolver.resolve().replaceAll("\\.", HermesMetrics.REPLACEMENT_CHAR)); GraphiteReporter .forRegistry(registry) .prefixedWith(prefix) .disabledMetricAttributes(disabledAttributes) .build(new Graphite(new InetSocketAddress( configFactory.getStringProperty(Configs.GRAPHITE_HOST), configFactory.getIntProperty(Configs.GRAPHITE_PORT) ))) .start(configFactory.getIntProperty(Configs.REPORT_PERIOD), TimeUnit.SECONDS); } if (configFactory.getBooleanProperty(Configs.METRICS_CONSOLE_REPORTER)) { ConsoleReporter.forRegistry(registry).build().start( configFactory.getIntProperty(Configs.REPORT_PERIOD), TimeUnit.SECONDS ); } if (configFactory.getBooleanProperty(Configs.METRICS_ZOOKEEPER_REPORTER)) { new ZookeeperCounterReporter(registry, counterStorage, configFactory).start( configFactory.getIntProperty(Configs.REPORT_PERIOD), TimeUnit.SECONDS ); } registerJvmMetrics(registry); return registry; }
Source:
public static TruthValue lookupTruthFunctionAndCompute(final EnumType type, final TruthValue a, final TruthValue b) { switch(type) { case DESIREDED: return desireDed(a, b); case DESIREIND: return desireInd(a, b); case DESIREWEAK: return desireWeak(a, b); case DESIRESTRONG: return desireStrong(a, b); case COMPARISON: return comparison(a, b); case ANALOGY: return analogy(a, b); case ANONYMOUSANALOGY: return anonymousAnalogy(a, b); default: throw new RuntimeException("Encountered unimplemented case!"); } }

Target:
public static TruthValue lookupTruthFunctionAndCompute(final EnumType type, final TruthValue a, final TruthValue b) { switch(type) { case DESIREDED: return desireDed(a, b); case DESIREIND: return desireInd(a, b); case DESIREWEAK: return desireWeak(a, b); case DESIRESTRONG: return desireStrong(a, b); case COMPARISON: return comparison(a, b); case ANALOGY: return analogy(a, b); case ANONYMOUSANALOGY: return anonymousAnalogy(a, b); default: throw new IllegalArgumentException("Encountered unimplemented case!"); } }
Source:
public Response labelsLabelIdPut(String labelId, LabelDTO body) { Label label = null; try { APIAdmin apiAdmin = new APIAdminImpl(); label = LabelMappingUtil.labelDTOToLabelPut(labelId, body); String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); LabelDTO labelDTO = LabelMappingUtil. fromLabelToLabelDTO(apiAdmin.updateLabel(tenantDomain, label)); URI location = new URI(RestApiConstants.RESOURCE_PATH_LABEL + "/" + labelDTO.getId()); return Response.ok(location).entity(labelDTO).build(); } catch (APIManagementException | URISyntaxException e) { String errorMessage = "Error while updating Label : " + labelId; RestApiUtil.handleInternalServerError(errorMessage, log); } return null; }

Target:
public Response labelsLabelIdPut(String labelId, LabelDTO body) { Label label = null; try { APIAdmin apiAdmin = new APIAdminImpl(); label = LabelMappingUtil.labelDTOToLabelPut(labelId, body); String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain(); LabelDTO labelDTO = LabelMappingUtil. fromLabelToLabelDTO(apiAdmin.updateLabel(tenantDomain, label)); URI location = new URI(RestApiConstants.RESOURCE_PATH_LABEL + "/" + labelDTO.getId()); return Response.ok(location).entity(labelDTO).build(); } catch (APIManagementException | URISyntaxException e) { String errorMessage = "Error while updating label : " + labelId; RestApiUtil.handleInternalServerError(errorMessage, e, log); } return null; }
Source:
private Result isReviewed(PullRequest pull) { final Result result = new Result(false); final List<Comment> comments = helper.githubHelper.getPullRequestComments(pull.getNumber()); for (Comment comment : comments) { if (PullHelper.MERGE.matcher(comment.getBody()).matches()) { System.out.printf("issue #%d updated at: %s\n", pull.getNumber(), Util.getTime(pull.getUpdatedAt())); System.out.printf("issue #%d reviewed at: %s\n", pull.getNumber(), Util.getTime(comment.getCreatedAt())); if (pull.getUpdatedAt().compareTo(comment.getCreatedAt()) <= 0 && helper.isAdminUser(comment.getUser().getLogin())) { result.setMergeable(true); result.addDescription("+ Pull request has been reviewed"); break; } } } if (! result.isMergeable()) result.addDescription("- " + NOT_REVIEWED_TAG); return result; }

Target:
private Result isReviewed(PullRequest pull) { final Result result = new Result(false); final List<Comment> comments = helper.getGHHelper().getPullRequestComments(pull.getNumber()); for (Comment comment : comments) { if (PullHelper.MERGE.matcher(comment.getBody()).matches()) { System.out.printf("issue #%d updated at: %s\n", pull.getNumber(), Util.getTime(pull.getUpdatedAt())); System.out.printf("issue #%d reviewed at: %s\n", pull.getNumber(), Util.getTime(comment.getCreatedAt())); if (pull.getUpdatedAt().compareTo(comment.getCreatedAt()) <= 0 && helper.isAdminUser(comment.getUser().getLogin())) { result.setMergeable(true); result.addDescription("+ Pull request has been reviewed"); break; } } } if (! result.isMergeable()) result.addDescription("- " + NOT_REVIEWED_TAG); return result; }
Source:
public static FileOutputFormatBuilder.PathParams configure() { return new FileOutputFormatBuilderImpl(); }

Target:
public static FileOutputFormatBuilder.PathParams<JobConf> configure() { return new FileOutputFormatBuilderImpl<JobConf>(); }
Source:
public void testAddTwice() throws Exception { List<Locatable> input = Arrays.asList( new Interval("1",10,100), new Interval("1",10,100) ); OverlapDetector.create(input); }

Target:
public void testAddTwice() throws Exception { final List<Locatable> input = Arrays.asList( new Interval("1",10,100), new Interval("1",10,100) ); final OverlapDetector<Locatable> detector = OverlapDetector.create(input); final Set<Locatable> overlaps = detector.getOverlaps(new Interval("1", 50, 200)); Assert.assertEquals(overlaps.size(), 1); Assert.assertEquals(overlaps, Collections.singleton(new Interval("1",10,100))); }
Source:
private void authXoauth2withSASLIR() throws IOException, MessagingException { try { attemptXOAuth2(); } catch (NegativeImapResponseException e) { Log.v(LOG_TAG, "Authentication exception, invalidating token and re-trying", e); oauthTokenProvider.invalidateToken(settings.getUsername()); try { attemptXOAuth2(); } catch (NegativeImapResponseException e2) { Log.v(LOG_TAG, "Authentication exception for new token, permanent error assumed", e); oauthTokenProvider.invalidateToken(settings.getUsername()); throw new AuthenticationFailedException(e2.getMessage(), e); } } }

Target:
private void authXoauth2withSASLIR() throws IOException, MessagingException { retryXoauth2WithNewToken = true; try { attemptXOAuth2(); } catch (NegativeImapResponseException e) { oauthTokenProvider.invalidateToken(settings.getUsername()); if (!retryXoauth2WithNewToken) { handlePermanentXoauth2Failure(e); } else { handleTemporaryXoauth2Failure(e); } } }
Source:
public QuickAccessElement[] computeElements(String query, IProgressMonitor monitor) { List<QuickAccessElement> res = new ArrayList<>(); long startTime = System.currentTimeMillis(); WorkbenchLabelProvider labelProvider = new WorkbenchLabelProvider(); try { ResourcesPlugin.getWorkspace().getRoot().accept(resourceProxy -> { if (resourceProxy.isDerived()) { return false; } if (resourceProxy.getType() == IResource.FILE) { String name = resourceProxy.getName(); if (name.regionMatches(true, 0, query, 0, query.length())) { IResource resource = resourceProxy.requestResource(); res.add(new ResourceElement(labelProvider, resource)); } } return !monitor.isCanceled() && System.currentTimeMillis() - startTime < TIMEOUT_MS; }, IResource.NONE); } catch (CoreException e) { IDEWorkbenchPlugin.log(e.getMessage(), e); } labelProvider.dispose(); return res.toArray(new QuickAccessElement[res.size()]); }

Target:
public QuickAccessElement[] computeElements(String query, IProgressMonitor monitor) { SearchPattern searchPattern = new SearchPattern(); searchPattern.setPattern(query); List<QuickAccessElement> res = new ArrayList<>(); long startTime = System.currentTimeMillis(); WorkbenchLabelProvider labelProvider = new WorkbenchLabelProvider(); try { ResourcesPlugin.getWorkspace().getRoot().accept(resourceProxy -> { if (resourceProxy.isDerived() || !resourceProxy.isAccessible()) { return false; } if (resourceProxy.getType() == IResource.FILE) { String name = resourceProxy.getName(); if (searchPattern.matches(name)) { IFile file = (IFile) resourceProxy.requestResource(); res.add(new ResourceElement(labelProvider, file)); } } return !monitor.isCanceled() && System.currentTimeMillis() - startTime < TIMEOUT_MS; }, IResource.NONE); } catch (CoreException e) { IDEWorkbenchPlugin.log(e.getMessage(), e); } labelProvider.dispose(); return res.toArray(new QuickAccessElement[res.size()]); }
Source:
public static void allClientsConnected(final MemcacheClient<?> client) throws Exception{ final CountDownLatch done = new CountDownLatch(1); client.registerForConnectionChanges(new ConnectionChangeListener() { @Override public void connectionChanged(ObservableClient ignored) { if (client.numActiveConnections() == client.numTotalConnections()) { done.countDown(); } } }); done.await(10, TimeUnit.SECONDS); }

Target:
public static void allClientsConnected(final MemcacheClient<?> client) throws Exception{ final CountDownLatch done = new CountDownLatch(1); client.registerForConnectionChanges(new ConnectionChangeListener() { @Override public void connectionChanged(ObservableClient ignored) { if (client.numActiveConnections() == client.numTotalConnections()) { done.countDown(); } } }); if (!done.await(10, TimeUnit.SECONDS)) { throw new RuntimeException("Failed to connect to all cluster nodes before timeout"); } }
Source:
public <V> V coalesceTraversals(Callable<V> callable) throws InvocationTargetException { V finalResult = null; if (delayTraversals) { try { finalResult = callable.call(); } catch (Exception e) { throw new InvocationTargetException(e); } return finalResult; } boolean firstRun = true; while (callable != null) { delayedClasses = new HashMap<Object, IndexingLevel>(); delayedFeatures = new HashMap<Object, IndexingLevel>(); delayedDataTypes = new HashMap<Object, IndexingLevel>(); try { delayTraversals = true; V result = callable.call(); if (firstRun) { firstRun = false; finalResult = result; } while ((!delayedProxyResolutions.isEmpty()) && resolutionDelayingResources.isEmpty()) { final Collection<Entry<EObject, EReference>> entries = delayedProxyResolutions.entries(); final Entry<EObject, EReference> toResolve = entries.iterator().next(); entries.remove(toResolve); comprehension.tryResolveReference(toResolve.getKey(), toResolve.getValue()); } delayTraversals = false; callable = considerRevisit(); } catch (Exception e) { notifyFatalListener( "VIATRA Base encountered an error while traversing the EMF model to gather new information. ", e); throw new InvocationTargetException(e); } } executeTraversalCallbacks(); return finalResult; }

Target:
public <V> V coalesceTraversals(Callable<V> callable) throws InvocationTargetException { V finalResult = null; if (delayTraversals) { try { finalResult = callable.call(); } catch (Exception e) { throw new InvocationTargetException(e); } return finalResult; } boolean firstRun = true; while (callable != null) { try { delayTraversals = true; V result = callable.call(); if (firstRun) { firstRun = false; finalResult = result; } while ((!delayedProxyResolutions.isEmpty()) && resolutionDelayingResources.isEmpty()) { final Collection<Entry<EObject, EReference>> entries = delayedProxyResolutions.entries(); final Entry<EObject, EReference> toResolve = entries.iterator().next(); entries.remove(toResolve); comprehension.tryResolveReference(toResolve.getKey(), toResolve.getValue()); } delayTraversals = false; callable = considerRevisit(); } catch (Exception e) { notifyFatalListener( "VIATRA Base encountered an error while traversing the EMF model to gather new information. ", e); throw new InvocationTargetException(e); } } executeTraversalCallbacks(); return finalResult; }
Source:
public void add(Sha256Hash hash){ hashes = new ImmutableList.Builder<Sha256Hash>().addAll(hashes).add(hash).build(); }

Target:
public BlockLocator add(Sha256Hash hash) { return new BlockLocator(new ImmutableList.Builder<Sha256Hash>().addAll(this.hashes).add(hash).build()); }
Source:
public static String extendTypeAlias(String alias, Path extension) { List<Path.PathElement> elements = extension.getPathElements(); for (int i = 0; i < elements.size() - 1; i++) { alias = appendAlias(alias, elements.get(i).getFieldName()); } return alias; }

Target:
public static String extendTypeAlias(String alias, Path extension) { String result = alias; List<Path.PathElement> elements = extension.getPathElements(); for (int i = 0; i < elements.size() - 1; i++) { result = appendAlias(result, elements.get(i).getFieldName()); } return result; }
Source:
private CommandManager() { executionContextMap = CacheProviderFactory.<NGuid, ExecutionContext>getCacheWrapper(EXECUTION_CONTEXT_MAP_NAME); commandMap = CacheProviderFactory.<NGuid, CommandEntity>getCacheWrapper(COMMAND_MAP_NAME); }

Target:
private CommandManager() { executionContextMap = CacheProviderFactory.<NGuid, ExecutionContext>getCacheWrapper(EXECUTION_CONTEXT_MAP_NAME); }
Source:
protected void handleJAIEXTParams(ParameterBlockJAI parameters, ParameterValueGroup parameters2) { if(JAIExt.isJAIExtOperation("algebric")){ parameters.set(Operator.ABSOLUTE, 0); Collection<GridCoverage2D> sources = (Collection<GridCoverage2D>) parameters2.parameter("sources").getValue(); for(GridCoverage2D source : sources){ handleROINoDataInternal(parameters, source, "algebric", 1, 2); } } }

Target:
protected void handleJAIEXTParams(ParameterBlockJAI parameters, ParameterValueGroup parameters2) { if(JAIExt.isJAIExtOperation(ALGEBRIC)){ parameters.set(Operator.ABSOLUTE, 0); Collection<GridCoverage2D> sources = (Collection<GridCoverage2D>) parameters2.parameter("sources").getValue(); for(GridCoverage2D source : sources){ handleROINoDataInternal(parameters, source, ALGEBRIC, 1, 2); } } }
Source:
public AudioChannel(Clock wallClock, ChannelsManager channelsManager) { super(MEDIA_TYPE, wallClock, channelsManager); this.supportedFormats = new RTPFormats(); Iterator<String> codecs = channelsManager.getCodecs(); while(codecs.hasNext()) { switch (codecs.next()) { case "pcmu": RTPFormat pcmu = new RTPFormat(0, FormatFactory.createAudioFormat("pcmu", 8000, 8, 1), 8000); supportedFormats.add(pcmu); break; case "pcma": RTPFormat pcma = new RTPFormat(8, FormatFactory.createAudioFormat("pcma", 8000, 8, 1), 8000); supportedFormats.add(pcma); break; case "gsm": RTPFormat gsm = new RTPFormat(3, FormatFactory.createAudioFormat("gsm", 8000), 8000); supportedFormats.add(gsm); break; case "g729": RTPFormat g729 = new RTPFormat(18, FormatFactory.createAudioFormat("g729", 8000), 8000); supportedFormats.add(g729); break; case "l16": RTPFormat l16 = new RTPFormat(97, FormatFactory.createAudioFormat("l16", 8000, 16, 1), 8000); supportedFormats.add(l16); break; case "ilbc": RTPFormat ilbc = new RTPFormat(102, FormatFactory.createAudioFormat("ilbc", 8000, 16, 1), 8000); supportedFormats.add(ilbc); break; case "linear": RTPFormat linear = new RTPFormat(150, FormatFactory.createAudioFormat("linear", 8000, 16, 1), 8000); supportedFormats.add(linear); break; default: break; } } RTPFormat dtmf = new RTPFormat(101, FormatFactory.createAudioFormat("telephone-event", 8000), 8000); supportedFormats.add(dtmf); RTPFormat dtmf126 = new RTPFormat(126, FormatFactory.createAudioFormat("telephone-event", 8000), 8000); supportedFormats.add(dtmf126); super.setFormats(this.supportedFormats); }

Target:
public AudioChannel(Clock wallClock, ChannelsManager channelsManager) { super(MEDIA_TYPE, wallClock, channelsManager); this.supportedFormats = new RTPFormats(); String[] codecs = channelsManager.getCodecs(); for(String codec : codecs) { switch (codec) { case "pcmu": supportedFormats.add(AVProfile.getFormat(0)); break; case "pcma": supportedFormats.add(AVProfile.getFormat(8)); break; case "gsm": supportedFormats.add(AVProfile.getFormat(3)); break; case "g729": supportedFormats.add(AVProfile.getFormat(18)); break; case "l16": supportedFormats.add(AVProfile.getFormat(97)); break; case "ilbc": supportedFormats.add(AVProfile.getFormat(102)); break; case "linear": supportedFormats.add(AVProfile.getFormat(150)); break; default: break; } } supportedFormats.add(AVProfile.getFormat(101)); supportedFormats.add(AVProfile.getFormat(126)); super.setFormats(this.supportedFormats); }
Source:
static void computeSha1s(FileInputStream fileInputStream, BoxUploadSession uploadSession, long fileSize) throws NoSuchAlgorithmException, IOException { int totalParts = uploadSession.getTotalParts(); List<String> partSha1s = new ArrayList<>(totalParts); byte[] partBuffer = new byte[uploadSession.getPartSize()]; MessageDigest mdFile = MessageDigest.getInstance("SHA-1"); MessageDigest mdPart = MessageDigest.getInstance("SHA-1"); for (int i = 0; i < totalParts; i++) { partBuffer = new byte[BoxUploadSession.getChunkSize(uploadSession, i, fileSize)]; fileInputStream.read(partBuffer); mdPart.reset(); mdPart.update(partBuffer); partSha1s.add(Base64.encodeToString(mdPart.digest(), Base64.DEFAULT)); mdFile.update(partBuffer); } uploadSession.setPartsSha1(partSha1s); uploadSession.setSha1(Base64.encodeToString(mdFile.digest(), Base64.DEFAULT)); }

Target:
static void computeSha1s(FileInputStream fileInputStream, BoxUploadSession uploadSession, long fileSize) throws NoSuchAlgorithmException, IOException { int totalParts = uploadSession.getTotalParts(); List<String> partSha1s = new ArrayList<>(totalParts); byte[] partBuffer; int partBufferSize = SdkUtils.BUFFER_SIZE; int bytesOfChunkToRead; MessageDigest mdFile = MessageDigest.getInstance("SHA-1"); MessageDigest mdPart = MessageDigest.getInstance("SHA-1"); for (int i = 0; i < totalParts; i++) { bytesOfChunkToRead = BoxUploadSession.getChunkSize(uploadSession, i, fileSize); partBuffer = new byte[partBufferSize]; while (bytesOfChunkToRead > 0) { if (bytesOfChunkToRead < partBufferSize) { partBuffer = new byte[bytesOfChunkToRead]; } fileInputStream.read(partBuffer); bytesOfChunkToRead -= partBufferSize; mdPart.update(partBuffer); mdFile.update(partBuffer); } partSha1s.add(Base64.encodeToString(mdPart.digest(), Base64.DEFAULT)); mdPart.reset(); } uploadSession.setPartsSha1(partSha1s); uploadSession.setSha1(Base64.encodeToString(mdFile.digest(), Base64.DEFAULT)); }