auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp() throws Exception { tmpDir = new File(System.getProperty("java.io.tmpdir") + "/ZeppelinLTest_" + System.currentTimeMillis()); System.setProperty("zeppelin.dep.localrepo", tmpDir.getAbsolutePath() + "/local-repo"); tmpDir.mkdirs(); if (repl == null) { intpGroup = new InterpreterGroup(); intpGroup.put("note", new LinkedList<Interpreter>()); repl = new SparkInterpreter(getSparkTestProperties()); repl.setInterpreterGroup(intpGroup); intpGroup.get("note").add(repl); repl.open(); } final RemoteEventClientWrapper remoteEventClientWrapper = new RemoteEventClientWrapper() { @Override public void onParaInfosReceived(String noteId, String paragraphId, Map<String, String> infos) { if (infos != null) { paraIdToInfosMap.put(paragraphId, infos); } } @Override public void onMetaInfosReceived(Map<String, String> infos) { } }; context = new InterpreterContext("note", "id", null, "title", "text", new AuthenticationInfo(), new HashMap<String, Object>(), new GUI(), new AngularObjectRegistry(intpGroup.getId(), null), new LocalResourcePool("id"), new LinkedList<InterpreterContextRunner>(), new InterpreterOutput(null)) { @Override <START> public RemoteEventClientWrapper getClient() { <END> return remoteEventClientWrapper; } }; repl.interpret("sc", context); }</code><technical_language>reason i mentioned especially RemoveEventClient is part of Interpreter development API want minimize API change release. (doesn't this PR care) Agree, reactor interpreter layer freeze 0.7</technical_language>

Target:
public void setUp() throws Exception { if (repl == null) { intpGroup = new InterpreterGroup(); intpGroup.put("note", new LinkedList<Interpreter>()); repl = new SparkInterpreter(getSparkTestProperties(tmpDir)); repl.setInterpreterGroup(intpGroup); intpGroup.get("note").add(repl); repl.open(); } final RemoteEventClientWrapper remoteEventClientWrapper = new RemoteEventClientWrapper() { @Override public void onParaInfosReceived(String noteId, String paragraphId, Map<String, String> infos) { if (infos != null) { paraIdToInfosMap.put(paragraphId, infos); } } @Override public void onMetaInfosReceived(Map<String, String> infos) { } }; context = new InterpreterContext("note", "id", null, "title", "text", new AuthenticationInfo(), new HashMap<String, Object>(), new GUI(), new AngularObjectRegistry(intpGroup.getId(), null), new LocalResourcePool("id"), new LinkedList<InterpreterContextRunner>(), new InterpreterOutput(null)) { @Override public RemoteEventClientWrapper getClient() { return remoteEventClientWrapper; } }; repl.interpret("sc", context); }
Source:
<code>protected boolean validateLeaseStorageDomain(Guid leaseStorageDomainId) { StorageDomain domain = storageDomainDao.get(leaseStorageDomainId); StorageDomainValidator validator = new StorageDomainValidator(domain); <START> if (!validate(validator.isDomainExistAndActive()) || validate(validator.isDataDomain())) { <END> return false; } if (!getStoragePoolId().equals(domain.getStoragePoolId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_LEASE_STORAGE_IS_NOT_A_PART_OF_POOL); } return true; }</code><technical_language>change !validate in condition</technical_language>

Target:
protected boolean validateLeaseStorageDomain(Guid leaseStorageDomainId) { StorageDomain domain = storageDomainDao.getForStoragePool(leaseStorageDomainId, getStoragePoolId()); StorageDomainValidator validator = new StorageDomainValidator(domain); if (!validate(validator.isDomainExistAndActive()) || !validate(validator.isDataDomain())) { return false; } return true; }
Source:
<code>public DashboardInfo(String runtimeModelId, Collection<String> pages) { <START> super(); <END> this.runtimeModelId = runtimeModelId; this.pages = pages; }</code><technical_language>suggestion</technical_language>

Target:
public DashboardInfo(String runtimeModelId, Collection<String> pages) { this.runtimeModelId = runtimeModelId; this.pages = pages; }
Source:
<code><START> protected void executeQueryCommand() { <END> List<VmTemplate> retval = DbFacade.getInstance().getVmTemplateDAO().getAll(getUserID(), getParameters().isFiltered()); for (VmTemplate template : retval) { AnonymousMethod1(template); } getQueryReturnValue().setReturnValue(retval); }</code><technical_language>please getDbFacade() instead of DbFacade.getInstance()</technical_language>

Target:
protected void executeQueryCommand() { List<VmTemplate> retval = getDbFacade().getVmTemplateDAO().getAll(getUserID(), getParameters().isFiltered()); for (VmTemplate template : retval) { AnonymousMethod1(template); } getQueryReturnValue().setReturnValue(retval); }
Source:
<code>public void testWriteToServerOk() throws Exception { HttpConnection conn = new HttpConnection("POST", new URL(dbResource.getDbURIWithUserInfo()), "application/json"); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); assertEquals(data.getBytes().length, bis.available()); conn.setRequestBody(bis); HttpConnection response = conn.execute(); String responseStr = response.responseAsString(); <START> assertTrue("There should be an ok response: " + responseStr, Pattern.compile("" + <END> ".*\"ok\"\\s*:\\s*true.*", Pattern.DOTALL).matcher(responseStr).matches()); assertEquals(0, bis.available()); assertEquals("Should be a 2XX response code", 2, response.getConnection().getResponseCode () / 100); }</code><technical_language>Unnecessary "" +</technical_language>

Target:
public void testWriteToServerOk() throws Exception { HttpConnection conn = new HttpConnection("POST", new URL(dbResource.getDbURIWithUserInfo()), "application/json"); ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); assertEquals(data.getBytes().length, bis.available()); conn.setRequestBody(bis); HttpConnection response = conn.execute(); String responseStr = response.responseAsString(); String okPattern = ".*\"ok\"\\s*:\\s*true.*"; assertTrue("There should be an ok response: " + responseStr, Pattern.compile(okPattern, Pattern.DOTALL).matcher(responseStr).matches()); assertEquals(0, bis.available()); assertEquals("Should be a 2XX response code", 2, response.getConnection().getResponseCode () / 100); }
Source:
<code>public BootApplicationConfigurationMetadataResolver(ClassLoader parent) { this.parent = parent; JarFile.registerUrlProtocolHandler(); try { Resource[] globalResources = new PathMatchingResourcePatternResolver( ApplicationConfigurationMetadataResolver.class.getClassLoader()).getResources(WHITELIST_PROPERTIES); <START> if (ObjectUtils.isEmpty(globalResources)) { <END> globalResources = new PathMatchingResourcePatternResolver( ApplicationConfigurationMetadataResolver.class.getClassLoader()) .getResources(WHITELIST_LEGACY_PROPERTIES); } loadWhiteLists(globalResources, globalWhiteListedClasses, globalWhiteListedProperties); } catch (IOException e) { throw new RuntimeException("Error reading global white list of configuration properties", e); } }</code><technical_language>this of legacy properties JSON newly named JSON file is in classpath</technical_language>

Target:
public BootApplicationConfigurationMetadataResolver(ClassLoader parent) { this.parent = parent; JarFile.registerUrlProtocolHandler(); try { Resource[] globalLegacyResources = new PathMatchingResourcePatternResolver( ApplicationConfigurationMetadataResolver.class.getClassLoader()) .getResources(WHITELIST_LEGACY_PROPERTIES); Resource[] globalResources = new PathMatchingResourcePatternResolver( ApplicationConfigurationMetadataResolver.class.getClassLoader()) .getResources(WHITELIST_PROPERTIES); loadWhiteLists(concatArrays(globalLegacyResources, globalResources), globalWhiteListedClasses, globalWhiteListedProperties); } catch (IOException e) { throw new RuntimeException("Error reading global white list of configuration properties", e); } }
Source:
<code>public boolean addAll(Collection<? extends E> c) { boolean changed = false; for <START> (Iterator<? <END> extends E> iterator = c.iterator(); iterator.hasNext();) { E element = iterator.next(); changed |= wrappedSet.add(IdentityWrapper.wrap(element)); } return changed; }</code><technical_language>Better: E element : c</technical_language>

Target:
public boolean addAll(Collection<? extends E> c) { boolean changed = false; for (E element : c) { changed |= wrappedSet.add(IdentityWrapper.wrap(element)); } return changed; }
Source:
<code>private FeedbackQuestionAttributes getNewFeedbackQuestionAttributes() { FeedbackTextQuestionDetails questionDetails = new FeedbackTextQuestionDetails("Question text."); return FeedbackQuestionAttributes.builder() .withCourseId("testCourse") .withCreatorEmail("instructor@email.com") .withFeedbackSessionName("testFeedbackSession") .withGiverType(FeedbackParticipantType.INSTRUCTORS) .withRecipientType(FeedbackParticipantType.SELF) .withNumOfEntitiesToGiveFeedbackTo(1) .withQuestionNumber(1) .withQuestionType(FeedbackQuestionType.TEXT) .withQuestionMetaData(new Text(JsonUtils.toJson(questionDetails, <START> FeedbackQuestionType.TEXT.getQuestionDetailsClass()))) <END> .withShowGiverNameTo(new ArrayList<>()) .withShowRecipientNameTo(new ArrayList<>()) .withShowResponseTo(new ArrayList<>()) .buildWithoutRemovingIrrelevantVisibilityOptions(); }</code><technical_language>reason for this question metadata</technical_language>

Target:
private FeedbackQuestionAttributes getNewFeedbackQuestionAttributes() { FeedbackTextQuestionDetails questionDetails = new FeedbackTextQuestionDetails("Question text."); return FeedbackQuestionAttributes.builder() .withCourseId("testCourse") .withCreatorEmail("instructor@email.com") .withFeedbackSessionName("testFeedbackSession") .withGiverType(FeedbackParticipantType.INSTRUCTORS) .withRecipientType(FeedbackParticipantType.SELF) .withNumOfEntitiesToGiveFeedbackTo(1) .withQuestionNumber(1) .withQuestionType(FeedbackQuestionType.TEXT) .withQuestionMetaData(questionDetails) .withShowGiverNameTo(new ArrayList<>()) .withShowRecipientNameTo(new ArrayList<>()) .withShowResponseTo(new ArrayList<>()) .build(); }
Source:
<code>private void initialize() { viewModel = new PreferencesDialogViewModel(dialogService, frame); preferenceTabList.itemsProperty().setValue(viewModel.getPreferenceTabs()); PreferencesSearchHandler searchHandler = new PreferencesSearchHandler(viewModel.getPreferenceTabs()); preferenceTabList.itemsProperty().bindBidirectional(searchHandler.filteredPreferenceTabsProperty()); searchBox.textProperty().addListener((observable, previousText, newText) -> { searchHandler.filterTabs(newText.toLowerCase(Locale.ROOT)); preferenceTabList.getSelectionModel().clearSelection(); preferenceTabList.getSelectionModel().selectFirst(); }); searchBox.setPromptText(Localization.lang("Search") + "..."); searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode()); EasyBind.subscribe(preferenceTabList.getSelectionModel().selectedItemProperty(), tab -> { if (tab == null) { preferencePaneContainer.setContent(null); } else { preferencePaneContainer.setContent(tab.getBuilder()); } }); preferenceTabList.getSelectionModel().selectFirst(); new ViewModelListCellFactory<PreferencesTab>() .withText(PreferencesTab::getTabName) .install(preferenceTabList); <START> DefaultTaskExecutor.runInJavaFXThread(viewModel::setValues); <END> }</code><technical_language>Oh, I formulated in a misleading way. I meant is tab.setValues called tab focus - preference dialog is loaded. I hoping improve loading time of dialog in way. this kind of lazy loading needs a bit of refactoring want override users temporary changes switches tabs. leave this for another PR</technical_language>

Target:
private void initialize() { viewModel = new PreferencesDialogViewModel(dialogService, frame); preferenceTabList.itemsProperty().setValue(viewModel.getPreferenceTabs()); PreferencesSearchHandler searchHandler = new PreferencesSearchHandler(viewModel.getPreferenceTabs()); preferenceTabList.itemsProperty().bindBidirectional(searchHandler.filteredPreferenceTabsProperty()); searchBox.textProperty().addListener((observable, previousText, newText) -> { searchHandler.filterTabs(newText.toLowerCase(Locale.ROOT)); preferenceTabList.getSelectionModel().clearSelection(); preferenceTabList.getSelectionModel().selectFirst(); }); searchBox.setPromptText(Localization.lang("Search") + "..."); searchBox.setLeft(IconTheme.JabRefIcons.SEARCH.getGraphicNode()); EasyBind.subscribe(preferenceTabList.getSelectionModel().selectedItemProperty(), tab -> { if (tab == null) { preferencePaneContainer.setContent(null); } else { preferencePaneContainer.setContent(tab.getBuilder()); } }); preferenceTabList.getSelectionModel().selectFirst(); new ViewModelListCellFactory<PreferencesTab>() .withText(PreferencesTab::getTabName) .install(preferenceTabList); viewModel.setValues(); }
Source:
<code>public Builder withDefaultHint(QueryEvaluationHint engineDefaultHints) { this.engineDefaultHints = engineDefaultHints; <START> this.defaultBackendFactory = engineDefaultHints.getQueryBackendFactory(); <END> return this; }</code><technical_language>This is a good set things. If defaultHint defaultBackend is set, end result depends order... some checking (and possibly logging) is required here, define a clear priority settings, build method ensure that</technical_language>

Target:
public Builder withDefaultHint(QueryEvaluationHint engineDefaultHints) { this.engineDefaultHints = engineDefaultHints; return this; }
Source:
<code>public void clickOnPlusMenuButton() { redrawDriverWait.until(visibilityOf(plusMenuBtn)); <START> new Actions(seleniumWebDriver).moveToElement(plusMenuBtn).click().perform(); <END> }</code><technical_language>ActionFactory</technical_language>

Target:
public void clickOnPlusMenuButton() { redrawDriverWait.until(visibilityOf(plusMenuBtn)); actionsFactory.createAction(seleniumWebDriver).moveToElement(plusMenuBtn).click().perform(); }
Source:
<code><START> public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) { <END> try { String address; int addressType; if (hostAddress instanceof Inet4Address) { address = hostAddress.getHostAddress(); addressType = IPv4; } else if (hostAddress instanceof Inet6Address) { address = hostAddress.getHostAddress(); addressType = IPv6; } else { return false; } return mService.requestRouteToHostAddress(networkType, addressType, address); } catch (Exception e) { return false; } }</code><technical_language>Please mark requestRouteToHost deprecated create a InetAddress for hostAddress mService.requestRouteToHostAddress. requestRouteToHostAddress need distinguish v4 v6. Drop addressType stuff</technical_language>

Target:
public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) { String address = hostAddress.getHostAddress(); try { return mService.requestRouteToHostAddress(networkType, address); } catch (RemoteException e) { return false; } }
Source:
<code>public static QuotaEnforcementTypeEnum map(QuotaModeType type) { switch (type) { case DISABLED: return QuotaEnforcementTypeEnum.DISABLED; case ENABLED: return QuotaEnforcementTypeEnum.HARD_ENFORCEMENT; case AUDIT: return QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT; default: <START> return null; <END> } }</code><technical_language>Throw exception, this: throw new IllegalArgumentException("Unknown quota mode type \"" + type + "\"");</technical_language>

Target:
public static QuotaEnforcementTypeEnum map(QuotaModeType type) { switch (type) { case DISABLED: return QuotaEnforcementTypeEnum.DISABLED; case ENABLED: return QuotaEnforcementTypeEnum.HARD_ENFORCEMENT; case AUDIT: return QuotaEnforcementTypeEnum.SOFT_ENFORCEMENT; default: throw new IllegalArgumentException("Unknown quota mode type \"" + type + "\""); } }
Source:
<code>protected void runInternal() { hasMapListener = mapEventPublisher.hasEventListener(name); hasWanReplication = mapContainer.isWanReplicationEnabled() && !disableWanReplicationEvent; hasBackups = mapContainer.getTotalBackupCount() > 0; hasInvalidation = mapContainer.hasInvalidationListener(); if (hasBackups) { <START> backupRecordAndDataValuePairs = new ArrayList<>(mergingEntries.size()); <END> } if (hasInvalidation) { invalidationKeys = new ArrayList<>(mergingEntries.size()); } for (MapMergeTypes mergingEntry : mergingEntries) { merge(mergingEntry); } }</code><technical_language>mergingEntries.size() * 2</technical_language>

Target:
protected void runInternal() { hasMapListener = mapEventPublisher.hasEventListener(name); hasWanReplication = mapContainer.isWanReplicationEnabled() && !disableWanReplicationEvent; hasBackups = mapContainer.getTotalBackupCount() > 0; hasInvalidation = mapContainer.hasInvalidationListener(); if (hasBackups) { backupRecordAndDataValuePairs = new ArrayList<>(mergingEntries.size() * 2); } if (hasInvalidation) { invalidationKeys = new ArrayList<>(mergingEntries.size()); } for (MapMergeTypes mergingEntry : mergingEntries) { merge(mergingEntry); } }
Source:
<code>public void releaseReference(K object) { Integer count = references.get(object); if (count == null) { throw new IllegalStateException("Object does not have any references: " + object); } else if (count > 1) { references.put(object, count - 1); <START> } else if (count == 1){ <END> references.remove(object); } else if (count <= 0) { throw new IllegalStateException("Invalid reference count: " + count); } }</code><technical_language>space ) {</technical_language>

Target:
public void releaseReference(K object) { Integer count = references.get(object); if (count == null) { throw new IllegalStateException("Object does not have any references: " + object); } else if (count > 1) { references.put(object, count - 1); } else if (count == 1) { references.remove(object); } else { throw new IllegalStateException("Invalid reference count: " + count); } }
Source:
<code>public void handleMessage(Message<?> message) throws MessagingException { try { SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); String[] smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); <START> logger.debug("message ID(s) for the sent message: " + Arrays.toString(smsMessageId)); <END> } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } }</code><technical_language>List<String> smsMessageId redundant wrap array String</technical_language>

Target:
public void handleMessage(Message<?> message) throws MessagingException { try { SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); List<String> smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); logger.debug("message ID(s) for the sent message: " + smsMessageId); } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } }
Source:
<code>public void testStableSort() { page.click(By.id("button_sortid")); page.click(By.id("button_sortid")); page.click(By.id("button_sortname")); String[] idList = { "15", "0", "-13.5", "2", "-2", "-1.3", "10.01", "24", "1", "10.7", "3", "33", "10.35", "-0.001", "10.3" }; StringBuilder searchString = new StringBuilder(); <START> for (String element : idList) { <END> searchString.append(element).append("{*}"); } page.verifyContains(searchString.toString()); page.click(By.id("button_sortname")); String[] reversedIdList = { "10.3", "-0.001", "10.35", "33", "3", "10.7", "1", "-2", "-1.3", "10.01", "24", "2", "-13.5", "0", "15" }; searchString = new StringBuilder(); for (String element : reversedIdList) { searchString.append(element).append("{*}"); } page.verifyContains(searchString.toString()); }</code><technical_language>Naming</technical_language>

Target:
public void testStableSort() { page.click(By.id("button_sortid")); page.click(By.id("button_sortid")); page.click(By.id("button_sortname")); String[] idList = { "15", "0", "-13.5", "2", "-2", "-1.3", "10.01", "24", "1", "10.7", "3", "33", "10.35", "-0.001", "10.3" }; StringBuilder searchString = new StringBuilder(); for (String id : idList) { searchString.append(id).append("{*}"); } page.verifyContains(searchString.toString()); page.click(By.id("button_sortname")); String[] reversedIdList = { "10.3", "-0.001", "10.35", "33", "3", "10.7", "1", "-2", "-1.3", "10.01", "24", "2", "-13.5", "0", "15" }; searchString = new StringBuilder(); for (String id : reversedIdList) { searchString.append(id).append("{*}"); } page.verifyContains(searchString.toString()); }
Source:
<code>public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } Commit other = (Commit) o; <START> return this.commitMetadata.getCommitId().equals(other.commitMetadata.getCommitId()); <END> }</code><technical_language>return this.getId().equals(other.getId());</technical_language>

Target:
public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } Commit other = (Commit) o; return this.getId().equals(other.getId()); }
Source:
<code>public void end(Xid xid, int flags) throws XAException { <START> log.infof("end xid:[%s], flag: %s", xid, flags); <END> }</code><technical_language>trace</technical_language>

Target:
public void end(Xid xid, int flags) throws XAException { log.tracef("end xid:[%s], flag: %s", xid, flags); }
Source:
<code>private DiffObjectCount count(RevTree left, RevTree right) { <START> PreOrderDiffWalk visitor = new PreOrderDiffWalk(left, right, odb, odb, true); <END> DiffCountConsumer consumer = new DiffCountConsumer(odb); visitor.walk(consumer); DiffObjectCount count = consumer.get(); return count; }</code><technical_language>setting order some big performance issues -- is this necessary (unclear if is)</technical_language>

Target:
private DiffObjectCount count(RevTree left, RevTree right) { PreOrderDiffWalk visitor = new PreOrderDiffWalk(left, right, odb, odb); DiffCountConsumer consumer = new DiffCountConsumer(odb); visitor.walk(consumer); DiffObjectCount count = consumer.get(); return count; }
Source:
<code>public void onChatMessage(ChatMessage chatMessage) { Player player = playerService.getPlayerForUsername(chatMessage.getUsername()); ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); if (player != null && player.getSocialStatus() == FOE && chatPrefs.getHideFoeMessages()) { return; } super.onChatMessage(chatMessage); if (!hasFocus()) { audioService.playPrivateMessageSound(); showNotificationIfNecessary(chatMessage); setUnread(true); incrementUnreadMessagesCount(1); boolean chatFocused = preferencesService.getPreferences().getMainWindow().getLastView().equals(NavigationItem.CHAT.name()); <START> eventBus.post(new UnreadPrivateMessageEvent(chatMessage, chatFocused)); <END> } }</code><technical_language>event "hey, a new private message", chat is focused part of event, checked receiver (if of interest). Also, while checking in preferences work, semantically incorrect interested in preferences in current application state. considered a coincidence preferences reflect current application state. receiver of event some mechanism figure out chat is active not</technical_language>

Target:
public void onChatMessage(ChatMessage chatMessage) { Player player = playerService.getPlayerForUsername(chatMessage.getUsername()); ChatPrefs chatPrefs = preferencesService.getPreferences().getChat(); if (player != null && player.getSocialStatus() == FOE && chatPrefs.getHideFoeMessages()) { return; } super.onChatMessage(chatMessage); if (!hasFocus()) { audioService.playPrivateMessageSound(); showNotificationIfNecessary(chatMessage); setUnread(true); incrementUnreadMessagesCount(1); eventBus.post(new UnreadPrivateMessageEvent(chatMessage)); } }
Source:
<code>private WrappedValue<V> getInternal(K key) { V value = null; EntityTag eTag = null; if (service.isRunning()) { String target = buildUrl(service.cacheName, key); try { Invocation get = service.getHttpClient().target(target).request().accept(service.getContentType()) .buildGet(); Response response = get.invoke(); eTag = response.getEntityTag(); <START> value = decodeByteArray(response.readEntity(byte[].class)); <END> } catch (NotFoundException e) { log.warn("RESTEasyHTTPOperations.get::Key: " + key + " does not exist in cache: " + service.cacheName); } catch (Exception e) { throw new RuntimeException("RESTEasyHTTPOperations::get request threw exception: " + target, e); } } return new WrappedValue<V>(eTag, value); }</code><technical_language>Minor: decode this lazily, if subsequent operation (in getAndPut/getAndRemove) succeeds</technical_language>

Target:
private WrappedValue<V> getInternal(K key) { V value = null; EntityTag eTag = null; if (service.isRunning()) { String target = buildUrl(service.cacheName, key); Response response = null; try { Invocation get = service.getHttpClient().target(target).request().accept(service.getContentType()) .buildGet(); response = get.invoke(); if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { log.warn("RESTEasyHTTPOperations.getInternal::Key: " + key + " does not exist in cache: " + service.cacheName); } else { eTag = response.getEntityTag(); value = decodeByteArray(response.readEntity(byte[].class)); } } catch (Exception e) { throw new RuntimeException("RESTEasyHTTPOperations::get request threw exception: " + target, e); } finally { if (response != null) { response.close(); } } } return new WrappedValue<V>(eTag, value); }
Source:
<code>public AnalyzedAlterTableDropCheckConstraint analyze(Table<?> table, String name, CoordinatorTxnCtx txnCtx) { DocTableInfo tableInfo = (DocTableInfo) schemas.resolveTableInfo( table.getName(), Operation.ALTER, txnCtx.sessionContext().user(), txnCtx.sessionContext().searchPath()); List<CheckConstraint<Symbol>> checkConstraints = tableInfo.checkConstraints(); for (int i = 0; i < checkConstraints.size(); i++) { if (checkConstraints.get(i).name().equals(name)) { return new AnalyzedAlterTableDropCheckConstraint(tableInfo, name); } } throw new IllegalArgumentException(String.format( Locale.ENGLISH, <START> "Cannot find a CHECK CONSTRAINT named [%s], available names are: %s", <END> name, checkConstraints .stream() .map(CheckConstraint::name) .collect(Collectors.toList()))); }</code><technical_language>suggestion "Cannot find a CHECK CONSTRAINT named [%s], constraints are: %s",</technical_language>

Target:
public AnalyzedAlterTableDropCheckConstraint analyze(Table<?> table, String name, CoordinatorTxnCtx txnCtx) { DocTableInfo tableInfo = (DocTableInfo) schemas.resolveTableInfo( table.getName(), Operation.ALTER, txnCtx.sessionContext().user(), txnCtx.sessionContext().searchPath()); List<CheckConstraint<Symbol>> checkConstraints = tableInfo.checkConstraints(); for (int i = 0; i < checkConstraints.size(); i++) { if (name.equals(checkConstraints.get(i).name())) { return new AnalyzedAlterTableDropCheckConstraint(tableInfo, name); } } throw new IllegalArgumentException(String.format( Locale.ENGLISH, "Cannot find a CHECK CONSTRAINT named [%s], available constraints are: %s", name, Lists2.map(checkConstraints, CheckConstraint::name))); }
Source:
<code>public BridgeType(String bindingId, String thingTypeId, String label) throws IllegalArgumentException { <START> this(new ThingTypeUID(bindingId, thingTypeId), null, label, null, false, null, null, null, null); <END> }</code><technical_language>default is true</technical_language>

Target:
public BridgeType(String bindingId, String thingTypeId, String label) throws IllegalArgumentException { this(new ThingTypeUID(bindingId, thingTypeId), null, label, null, true, null, null, null, null); }
Source:
<code>public Collection<Class<?>> traverseBundlesForOsgiServices(final Collection<Bundle> bundles) { Collection<Class<?>> allClasses = getClasses(bundles); Set<Class<?>> osgiClasses = new HashSet<Class<?>>(); for (Class<?> clazz : allClasses) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(OsgiService.class)) { Class<?> fieldClass = field.getType(); osgiClasses.add(fieldClass); } } Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); Annotation[][] annotations = constructor.getParameterAnnotations(); int j = 0; for (int i = (parameterTypes.length - annotations.length); i < parameterTypes.length; i++) { for (Annotation annotation : annotations[j]) { if (annotation.annotationType().equals(OsgiService.class)) { <START> osgiClasses.add(parameterTypes[j]); <END> break; } } j++; } } } return osgiClasses; }</code><technical_language>this 'j' here</technical_language>

Target:
public Collection<Class<?>> traverseBundlesForOsgiServices(final Collection<Bundle> bundles) { Collection<Class<?>> allClasses = getClasses(bundles); Set<Class<?>> osgiClasses = new HashSet<Class<?>>(); for (Class<?> clazz : allClasses) { Set<Class<?>> osgiServicesForClass = readOsgiServicesForClass(clazz); osgiServicesForClass.addAll(osgiServicesForClass); } return osgiClasses; }
Source:
<code>public Optional<TimelineAlgorithmResult> getTimelinePrediction(final OneDaysSensorData oneDaysSensorData,final TimelineLog log,final long accountId,final boolean feedbackChanged) { try { final double [][] x = getSensorData(oneDaysSensorData); final Optional<NeuralNetAlgorithmOutput> outputOptional = endpoint.getNetOutput(DEFAULT_SLEEP_NET_ID,x); if (!outputOptional.isPresent()) { return Optional.absent(); } final NeuralNetAlgorithmOutput algorithmOutput = outputOptional.get(); final List<Sample> light = oneDaysSensorData.allSensorSampleList.get(Sensor.LIGHT); if (light.isEmpty()) { return Optional.absent(); } final TreeMap<Long,Integer> offsetMap = Maps.newTreeMap(); for (final Sample s : light) { offsetMap.put(s.dateTime,s.offsetMillis); } final long t0 = light.get(0).dateTime; final Optional<SleepProbabilityInterpreter.EventIndices> indicesOptional = SleepProbabilityInterpreter.getEventIndices(algorithmOutput.output[1],x[SensorIndices.MY_MOTION_DURATION.index()]); if (!indicesOptional.isPresent()) { <START> LOGGER.warn("status=no_event_indices"); <END> return Optional.absent(); } return Optional.of(new TimelineAlgorithmResult(AlgorithmType.NEURAL_NET,getAllEvents(offsetMap,t0,indicesOptional.get()))); } catch (Exception e) { e.printStackTrace(); } return Optional.absent(); }</code><technical_language>missing contextual info who/what generated this</technical_language>

Target:
public Optional<TimelineAlgorithmResult> getTimelinePrediction(final OneDaysSensorData oneDaysSensorData,final TimelineLog log,final long accountId,final boolean feedbackChanged) { try { final double [][] x = getSensorData(oneDaysSensorData); final Optional<NeuralNetAlgorithmOutput> outputOptional = endpoint.getNetOutput(DEFAULT_SLEEP_NET_ID,x); if (!outputOptional.isPresent()) { return Optional.absent(); } final NeuralNetAlgorithmOutput algorithmOutput = outputOptional.get(); final List<Sample> light = oneDaysSensorData.allSensorSampleList.get(Sensor.LIGHT); if (light.isEmpty()) { return Optional.absent(); } final TreeMap<Long,Integer> offsetMap = Maps.newTreeMap(); for (final Sample s : light) { offsetMap.put(s.dateTime,s.offsetMillis); } final long t0 = light.get(0).dateTime; final Optional<SleepProbabilityInterpreter.EventIndices> indicesOptional = SleepProbabilityInterpreter.getEventIndices(algorithmOutput.output[1],x[SensorIndices.MY_MOTION_DURATION.index()]); if (!indicesOptional.isPresent()) { LOGGER.warn("action=return_no_indices reason=no_event_indices_from_sleep_probability_interpreter"); return Optional.absent(); } return Optional.of(new TimelineAlgorithmResult(AlgorithmType.NEURAL_NET,getAllEvents(offsetMap,t0,indicesOptional.get()))); } catch (Exception e) { LOGGER.error("action=caught_exception exception=Exception error=invalid_index_calculation"); LOGGER.debug(e.getMessage()); } return Optional.absent(); }
Source:
<code>void shutdown() throws InterruptedException { long startTimeMs = time.milliseconds(); try { running = false; compactionManager.disable(); diskIOScheduler.disable(); final AtomicInteger numFailures = new AtomicInteger(0); List<Thread> shutdownThreads = new ArrayList<>(); for (final Map.Entry<PartitionId, BlobStore> partitionAndStore : stores.entrySet()) { <START> if (stoppedReplicas.contains(partitionAndStore.getKey().toPathString())) { <END> continue; } Thread thread = Utils.newThread("store-shutdown-" + partitionAndStore.getKey(), () -> { try { partitionAndStore.getValue().shutdown(); } catch (Exception e) { numFailures.incrementAndGet(); metrics.totalStoreShutdownFailures.inc(); logger.error("Exception while shutting down store on disk {}", partitionAndStore.getKey(), disk, e); } }, false); thread.start(); shutdownThreads.add(thread); } for (Thread shutdownThread : shutdownThreads) { shutdownThread.join(); } if (numFailures.get() > 0) { logger.error( "Could not shutdown " + numFailures.get() + " out of " + stores.size() + " stores on the disk " + disk); } compactionManager.awaitTermination(); longLivedTaskScheduler.shutdown(); if (!longLivedTaskScheduler.awaitTermination(30, TimeUnit.SECONDS)) { logger.error("Could not terminate long live tasks after DiskManager shutdown"); } } finally { metrics.diskShutdownTimeMs.update(time.milliseconds() - startTimeMs); } }</code><technical_language>Instead of this check (which differ if blob store started failed removed stopped list), do if (!partitionAndStore.getValue().isStarted()) { continue; }</technical_language>

Target:
void shutdown() throws InterruptedException { long startTimeMs = time.milliseconds(); try { running = false; compactionManager.disable(); diskIOScheduler.disable(); final AtomicInteger numFailures = new AtomicInteger(0); List<Thread> shutdownThreads = new ArrayList<>(); for (final Map.Entry<PartitionId, BlobStore> partitionAndStore : stores.entrySet()) { if (!partitionAndStore.getValue().isStarted()) { continue; } Thread thread = Utils.newThread("store-shutdown-" + partitionAndStore.getKey(), () -> { try { partitionAndStore.getValue().shutdown(); } catch (Exception e) { numFailures.incrementAndGet(); metrics.totalStoreShutdownFailures.inc(); logger.error("Exception while shutting down store on disk {}", partitionAndStore.getKey(), disk, e); } }, false); thread.start(); shutdownThreads.add(thread); } for (Thread shutdownThread : shutdownThreads) { shutdownThread.join(); } if (numFailures.get() > 0) { logger.error( "Could not shutdown " + numFailures.get() + " out of " + stores.size() + " stores on the disk " + disk); } compactionManager.awaitTermination(); longLivedTaskScheduler.shutdown(); if (!longLivedTaskScheduler.awaitTermination(30, TimeUnit.SECONDS)) { logger.error("Could not terminate long live tasks after DiskManager shutdown"); } } finally { metrics.diskShutdownTimeMs.update(time.milliseconds() - startTimeMs); } }
Source:
<code><START> CloudConnectionConstants(final String value) { <END> this.value = value; }</code><technical_language>default method visibility OK</technical_language>

Target:
private CloudConnectionConstants(final String value) { this.value = value; }
Source:
<code>public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscoveryEvent, final BeanManager beanManager) { Contracts.assertNotNull( beforeBeanDiscoveryEvent, "The BeforeBeanDiscovery event cannot be null" ); Contracts.assertNotNull( beanManager, "The BeanManager cannot be null" ); <START> AnnotatedType<ValidationExtension> annotatedType = beanManager.createAnnotatedType( ValidationExtension.class ); <END> beforeBeanDiscoveryEvent.addAnnotatedType( annotatedType ); }</code><technical_language>extension is added annotated type? this interceptor type instead</technical_language>

Target:
public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeBeanDiscoveryEvent, final BeanManager beanManager) { Contracts.assertNotNull( beforeBeanDiscoveryEvent, "The BeforeBeanDiscovery event cannot be null" ); Contracts.assertNotNull( beanManager, "The BeanManager cannot be null" ); AnnotatedType<ValidationInterceptor> annotatedType = beanManager.createAnnotatedType( ValidationInterceptor.class ); beforeBeanDiscoveryEvent.addAnnotatedType( annotatedType ); }
Source:
<code>private synchronized void registerDirectoryInternal(AbstractWatchService service, Kind<?>[] kinds, Path directory) { if (watchService == null) { try { watchService = FileSystems.getDefault().newWatchService(); qr = new Thread(this, "Dir Watcher"); qr.start(); } catch (IOException e) { e.printStackTrace(); <START> logger.error("Cannot activate watch service", e.getMessage()); <END> return; } } WatchKey registrationKey = null; try { registrationKey = directory.register(this.watchService, kinds); } catch (IOException e) { e.printStackTrace(); logger.debug("The directory '{}' was not registered in the watch service", directory, e); } if (registrationKey != null) { registeredKeys.put(registrationKey, directory); keyToService.put(registrationKey, service); } else { logger.debug("The directory '{}' was not registered in the watch service", directory); } }</code><technical_language>'{}' is missing in string</technical_language>

Target:
private synchronized void registerDirectoryInternal(AbstractWatchService service, Kind<?>[] kinds, Path directory) { if (watchService == null) { try { watchService = FileSystems.getDefault().newWatchService(); qr = new Thread(this, "Dir Watcher"); qr.start(); } catch (IOException e) { logger.debug("The directory '{}' was not registered in the watch service", directory, e); return; } } WatchKey registrationKey = null; try { registrationKey = directory.register(this.watchService, kinds); } catch (IOException e) { e.printStackTrace(); logger.debug("The directory '{}' was not registered in the watch service", directory, e); } if (registrationKey != null) { registeredKeys.put(registrationKey, directory); keyToService.put(registrationKey, service); } else { logger.debug("The directory '{}' was not registered in the watch service", directory); } }
Source:
<code>public BaseServer(@Nonnull ServerContext context) { this.serverContext = context; executor = Executors.newFixedThreadPool(serverContext.getBaseServerThreadCount(), <START> new ServerThreadFactory("baseServer-", new ServerThreadFactory.ExceptionHandler())); <END> }</code><technical_language>This code path right? throw unsupported exception instead of a default implementation removing later? error-prone way</technical_language>

Target:
public BaseServer(@Nonnull ServerContext context) { serverContext = context; executor = serverContext.getExecutorService(serverContext.getBaseServerThreadCount(), "baseServer-"); }
Source:
<code>public ValueMatcher makeMatcher(ColumnSelectorFactory factory){ if (filters.size() == 0) { <START> return new BooleanValueMatcher(false); <END> } final ValueMatcher[] matchers = new ValueMatcher[filters.size()]; for (int i = 0; i < filters.size(); i++) { matchers[i] = filters.get(i).makeMatcher(factory); } return makeMatcher(matchers); }</code><technical_language>I this changes behavior. empty filter return true, returns false</technical_language>

Target:
public ValueMatcher makeMatcher(ColumnSelectorFactory factory) { final ValueMatcher[] matchers = new ValueMatcher[filters.size()]; for (int i = 0; i < filters.size(); i++) { matchers[i] = filters.get(i).makeMatcher(factory); } return makeMatcher(matchers); }
Source:
<code>public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { <START> if ((i.getValue().equals(value) || i.getValue() == value) && i.getChecked() == false) { <END> i.setChecked(true); } }); return values; }); }</code><technical_language>do equality check here? done equals</technical_language>

Target:
public void checkSelectFilter(final String label, final String value) { selectInputs.computeIfPresent(label, (key, values) -> { values.forEach(i -> { if (i.getValue().equals(value) && i.getChecked() == false) { i.setChecked(true); } }); return values; }); }
Source:
<code>public void testNotification() throws InterruptedException { prepareLooper(); final CountDownLatch latch = new CountDownLatch(1); final MediaLibrarySessionCallback sessionCallback = new MediaLibrarySessionCallback() { @Override public SessionCommandGroup2 onConnect(@NonNull MediaSession2 session, @NonNull ControllerInfo controller) { if (Process.myUid() == controller.getUid()) { mSession = session; mPlayer = (MockPlayer) session.getPlayerConnector(); assertEquals(mContext.getPackageName(), controller.getPackageName()); assertFalse(controller.isTrusted()); latch.countDown(); } return super.onConnect(session, controller); } }; TestServiceRegistry.getInstance().setSessionCallback(sessionCallback); MediaController2 controller = createController(TestUtils.getServiceToken(mContext, MockMediaSessionService2.ID)); showToast("Notification will be shown"); mPlayer.notifyPlaybackState(MediaPlayerConnector.PLAYER_STATE_PLAYING); Thread.sleep(NOTIFICATION_SHOW_TIME_MS); showToast("Notification will be <START> removed"); <END> mPlayer.notifyPlaybackState(MediaPlayerConnector.PLAYER_STATE_ERROR); Thread.sleep(NOTIFICATION_SHOW_TIME_MS); }</code><technical_language>This is 'removed', notification swiped away</technical_language>

Target:
public void testNotification() throws InterruptedException { prepareLooper(); final CountDownLatch latch = new CountDownLatch(1); final MediaLibrarySessionCallback sessionCallback = new MediaLibrarySessionCallback() { @Override public SessionCommandGroup2 onConnect(@NonNull MediaSession2 session, @NonNull ControllerInfo controller) { if (Process.myUid() == controller.getUid()) { mSession = session; mPlayer = (MockPlayer) session.getPlayerConnector(); assertEquals(mContext.getPackageName(), controller.getPackageName()); assertFalse(controller.isTrusted()); latch.countDown(); } return super.onConnect(session, controller); } }; TestServiceRegistry.getInstance().setSessionCallback(sessionCallback); MediaController2 controller = createController(TestUtils.getServiceToken(mContext, MockMediaSessionService2.ID)); showToast("Notification will be shown"); mPlayer.notifyPlaybackState(MediaPlayerConnector.PLAYER_STATE_PLAYING); Thread.sleep(NOTIFICATION_SHOW_TIME_MS); showToast("Notification can be removable shortly"); mPlayer.notifyPlaybackState(MediaPlayerConnector.PLAYER_STATE_ERROR); Thread.sleep(NOTIFICATION_SHOW_TIME_MS); showToast("Notification will be removed"); }
Source:
<code>private void checkDuplicate(UDF udf) { List<QueryParam> qps = QueryParam.params(UDF.NAME, udf.getName(), UDF.CLASSNAME, udf.getClassName(), UDF.TYPE, udf.getType().toString()); Collection<UDF> existing = catalogService.listUDFs(qps); if (!existing.isEmpty()) { <START> LOG.warn("UDF with same (name, classname, type) already exists", udf); <END> throw EntityAlreadyExistsException.byName(udf.getName()); } }</code><technical_language>missing {}? of add space exists udf</technical_language>

Target:
private void checkDuplicate(UDF udf) { List<QueryParam> qps = QueryParam.params(UDF.NAME, udf.getName(), UDF.CLASSNAME, udf.getClassName(), UDF.TYPE, udf.getType().toString()); Collection<UDF> existing = catalogService.listUDFs(qps); if (!existing.isEmpty()) { LOG.warn("UDF with same (name, classname, type) already exists, udf: {}", udf); throw EntityAlreadyExistsException.byName(udf.getName()); } }
Source:
<code>public void canDecodeExceptionOfKnownType() throws JsonProcessingException { <START> SerializableError serializableError = SerializableError.of(EXCEPTION_MESSAGE, KNOWN_ERROR_NAME); <END> Response response = createResponseForEntity(serializableError); Exception exception = decoder.decode(SOME_METHOD_KEY, response); assertThat(exception).isInstanceOf(AtlasDbRemoteException.class) .satisfies(remoteException -> assertHasErrorName(remoteException, KNOWN_ERROR_NAME)); }</code><technical_language>tests for ERROR_NAME, worth refactoring</technical_language>

Target:
public void canDecodeExceptionOfKnownType() throws JsonProcessingException { assertCanSerializeAndDeserializeErrorWithName(KNOWN_ERROR_NAME); }
Source:
<code>public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { try { getUserFromPreferences( (name, email) -> { <START> if (isNullOrEmpty(name) && isNullOrEmpty(email)) { <END> try { getUserFromUserManager( (uName, uEmail) -> prepareAndProvisionGitConfiguration(uName, uEmail, k8sEnv, identity)); } catch (NotFoundException | ServerException e) { reportWarning( k8sEnv, Warnings.EXCEPTION_IN_USER_MANAGER_DURING_GIT_PROVISION_WARNING_CODE, format( Warnings.EXCEPTION_IN_USER_MANAGER_DURING_GIT_PROVISION_MESSAGE_FMT, e.getMessage())); } return; } prepareAndProvisionGitConfiguration(name, email, k8sEnv, identity); }); } catch (ServerException e) { reportWarning( k8sEnv, Warnings.EXCEPTION_IN_USER_PREFERENCES_MANAGER_DURING_GIT_PROVISION_WARNING_CODE, format( Warnings.EXCEPTION_IN_USER_PREFERENCES_MANAGER_DURING_GIT_PROVISION_MESSAGE_FMT, e.getMessage())); } catch (JsonSyntaxException e) { reportWarning( k8sEnv, Warnings.JSON_IS_NOT_A_VALID_REPRESENTATION_FOR_AN_OBJECT_OF_TYPE_WARNING_CODE, format( Warnings.JSON_IS_NOT_A_VALID_REPRESENTATION_FOR_AN_OBJECT_OF_TYPE_MESSAGE_FMT, e.getMessage())); } }</code><technical_language>clearer invert this logic: java if (!isNullOrEmpty(name) || !isNullOrEmpty(email)) { prepareAndProvisionGitConfiguration(name, email, k8sEnv, identity); } else { // provision user manager }</technical_language>

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { try { Pair<String, String> userAndEmail = getUserFromPreferences(); if (userAndEmail == null) { userAndEmail = getUserFromUserManager(); } prepareAndProvisionGitConfiguration( userAndEmail.first, userAndEmail.second, k8sEnv, identity); } catch (ServerException | NotFoundException e) { reportWarning( k8sEnv, Warnings.EXCEPTION_IN_USER_MANAGEMENT_DURING_GIT_PROVISION_WARNING_CODE, format( Warnings.EXCEPTION_IN_USER_MANAGEMENT_DURING_GIT_PROVISION_MESSAGE_FMT, e.getMessage())); } catch (JsonSyntaxException e) { reportWarning( k8sEnv, Warnings.JSON_IS_NOT_A_VALID_REPRESENTATION_FOR_AN_OBJECT_OF_TYPE_WARNING_CODE, format( Warnings.JSON_IS_NOT_A_VALID_REPRESENTATION_FOR_AN_OBJECT_OF_TYPE_MESSAGE_FMT, e.getMessage())); } }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RequestCodes.PICTURE_LIBRARY: case RequestCodes.VIDEO_LIBRARY: <START> if (resultCode == Activity.RESULT_OK) { <END> if (data != null) { Uri imageUri = data.getData(); String mimeType = getContentResolver().getType(imageUri); fetchMedia(imageUri, mimeType); } } break; case RequestCodes.TAKE_PHOTO: if (resultCode == Activity.RESULT_OK) { if (data != null) { Uri uri = Uri.parse(mMediaCapturePath); mMediaCapturePath = null; queueFileForUpload(uri, getContentResolver().getType(uri)); } } break; case RequestCodes.TAKE_VIDEO: if (resultCode == Activity.RESULT_OK) { Uri uri = MediaUtils.getLastRecordedVideoUri(this); queueFileForUpload(uri, getContentResolver().getType(uri)); } break; } }</code><technical_language>This is picky, simplify this if (resultCode == Activity.RESULT_OK && data != null)</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case RequestCodes.PICTURE_LIBRARY: case RequestCodes.VIDEO_LIBRARY: if (resultCode == Activity.RESULT_OK && data != null) { Uri imageUri = data.getData(); String mimeType = getContentResolver().getType(imageUri); fetchMedia(imageUri, mimeType); } break; case RequestCodes.TAKE_PHOTO: if (resultCode == Activity.RESULT_OK) { Uri uri = Uri.parse(mMediaCapturePath); mMediaCapturePath = null; queueFileForUpload(uri, getContentResolver().getType(uri)); } break; case RequestCodes.TAKE_VIDEO: if (resultCode == Activity.RESULT_OK) { Uri uri = MediaUtils.getLastRecordedVideoUri(this); queueFileForUpload(uri, getContentResolver().getType(uri)); } break; } }