auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void contextChange(MetricsContext metricsContext) { <START> Objects.requireNonNull(metricsContext.metadata().get(MetricsContext.NAMESPACE)); <END> synchronized (LOCK) { if (!mbeans.isEmpty()) { throw new IllegalStateException("JMX MetricsContext can only be updated before JMX metrics are created"); } prefix = metricsContext.metadata().get(MetricsContext.NAMESPACE); } }</code><technical_language>nit: read Map</technical_language>

Target:
public void contextChange(MetricsContext metricsContext) { String namespace = metricsContext.contextLabels().get(MetricsContext.NAMESPACE); Objects.requireNonNull(namespace); synchronized (LOCK) { if (!mbeans.isEmpty()) { throw new IllegalStateException("JMX MetricsContext can only be updated before JMX metrics are created"); } prefix = namespace; } }
Source:
<code>private boolean ensureDestinationImageMap() { if (diskInfoDestinationMap.isEmpty()) { if (getParameters().getStorageDomainId() != null && !Guid.Empty.equals(getParameters().getStorageDomainId())) { Guid storageId = getParameters().getStorageDomainId(); <START> for (DiskImage image : getVmTemplate().getDiskMap().values()) { <END> diskInfoDestinationMap.put(image.getId(), ImagesHandler.getDiskImageWithStorageId(storageId, image.getQuotaId())); } } else { ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), diskInfoDestinationMap, destStorages); } } if (getVmTemplate().getDiskMap().values().size() != diskInfoDestinationMap.size()) { log.errorFormat("Can not found any default active domain for one of the disks of template with id : {0}", getVmTemplate().getId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); return false; } return true; }</code><technical_language>put image</technical_language>

Target:
private boolean ensureDestinationImageMap() { if (diskInfoDestinationMap.isEmpty()) { if (getParameters().getStorageDomainId() != null && !Guid.Empty.equals(getParameters().getStorageDomainId())) { Guid storageId = getParameters().getStorageDomainId(); ArrayList<Guid> storageIds = new ArrayList<Guid>(); storageIds.add(storageId); for (DiskImage image : getVmTemplate().getDiskMap().values()) { image.setstorage_ids(storageIds); diskInfoDestinationMap.put(image.getId(), image); } } else { ImagesHandler.fillImagesMapBasedOnTemplate(getVmTemplate(), diskInfoDestinationMap, destStorages); } } if (getVmTemplate().getDiskMap().values().size() != diskInfoDestinationMap.size()) { log.errorFormat("Can not found any default active domain for one of the disks of template with id : {0}", getVmTemplate().getId()); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_MISSED_STORAGES_FOR_SOME_DISKS); return false; } return true; }
Source:
<code>private void checkStatements(VariableDeclarationTree variableDeclaration, StatementTree lastStatement) { SeparatedList<BindingElementTree> variables = variableDeclaration.variables(); if (variables.size() == 1 && variables.get(0).is(Kind.INITIALIZED_BINDING_ELEMENT)) { InitializedBindingElementTree initializedBindingElementTree = (InitializedBindingElementTree) variables.get(0); if (initializedBindingElementTree.left().is(Kind.BINDING_IDENTIFIER)) { String name = ((IdentifierTree) initializedBindingElementTree.left()).name(); <START> if (lastStatementReturnsVariable(lastStatement, name)) { <END> addIssue(initializedBindingElementTree.right(), String.format(MESSAGE, "return", name)); } else if (lastStatementThrowsVariable(lastStatement, name)) { addIssue(initializedBindingElementTree.right(), String.format(MESSAGE, "throw", name)); } } } }</code><technical_language>I rename methods returnsVariableInStatement throwsVariableInStatement, in order difference of naming begining of name in middle</technical_language>

Target:
private void checkStatements(VariableDeclarationTree variableDeclaration, StatementTree lastStatement) { SeparatedList<BindingElementTree> variables = variableDeclaration.variables(); if (variables.size() == 1 && variables.get(0).is(Kind.INITIALIZED_BINDING_ELEMENT)) { InitializedBindingElementTree initializedBindingElementTree = (InitializedBindingElementTree) variables.get(0); if (initializedBindingElementTree.left().is(Kind.BINDING_IDENTIFIER)) { String name = ((IdentifierTree) initializedBindingElementTree.left()).name(); if (returnsVariableInLastStatement(lastStatement, name)) { addIssue(initializedBindingElementTree.right(), String.format(MESSAGE, "return", name)); } else if (throwsVariableInLastStatement(lastStatement, name)) { addIssue(initializedBindingElementTree.right(), String.format(MESSAGE, "throw", name)); } } } }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { Set<IProject> toProcessNow = new HashSet<IProject>(); while (!monitor.isCanceled()) { synchronized (this.toProcess) { <START> if (this.toProcess.isEmpty()) { <END> CumulativeMappingDiscoveryJob.getInstance().schedule(); return Status.OK_STATUS; } else { for (IProject project : this.toProcess) { toProcessNow.add(project); } this.toProcess.removeAll(toProcessNow); } } if (!toProcessNow.isEmpty()) { CumulativeMappingDiscoveryJob.getInstance().addProjects(toProcessNow); ProjectConfigurationManager configurationManager = (ProjectConfigurationManager) MavenPlugin .getProjectConfigurationManager(); MavenUpdateRequest request = new MavenUpdateRequest( toProcessNow.toArray(new IProject[toProcessNow.size()]), false, false); Map<String, IStatus> updateStatus = configurationManager.updateProjectConfiguration(request, true, false, false, monitor); } } return new Status(IStatus.CANCEL, Activator.getDefault().getBundle().getSymbolicName(), "Cancelled by user"); }</code><technical_language>if project configuration update performs faster importer is able add another projects this job</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { Set<IProject> toProcessNow = new HashSet<IProject>(); while (!monitor.isCanceled()) { synchronized (this.toProcess) { if (this.toProcess.isEmpty()) { CumulativeMappingDiscoveryJob.getInstance().schedule(); return Status.OK_STATUS; } else { toProcessNow.addAll(this.toProcess); this.toProcess.removeAll(toProcessNow); } } if (!toProcessNow.isEmpty()) { CumulativeMappingDiscoveryJob.getInstance().addProjects(toProcessNow); ProjectConfigurationManager configurationManager = (ProjectConfigurationManager) MavenPlugin .getProjectConfigurationManager(); MavenUpdateRequest request = new MavenUpdateRequest( toProcessNow.toArray(new IProject[toProcessNow.size()]), false, false); Map<String, IStatus> updateStatus = configurationManager.updateProjectConfiguration(request, true, false, false, monitor); } } return new Status(IStatus.CANCEL, Activator.getDefault().getBundle().getSymbolicName(), "Cancelled by user"); }
Source:
<code>private void initNetworkList(Guid dataCenterId) { <START> if ((getNetwork().getItems() == null && getNetwork().getSelectedItem() == null) <END> || getNetwork().getIsChangable()) { startProgress(); IdQueryParameters queryParams = new IdQueryParameters(dataCenterId); Frontend.getInstance().runQuery(QueryType.GetAllNetworks, queryParams, new AsyncQuery<QueryReturnValue>(returnValue -> { Collection<Network> networks = returnValue.getReturnValue(); getNetwork().setItems(networks); updateNetworks(networks); stopProgress(); })); } }</code><technical_language>I understand code, this method ('initNetworkList') invoked in case selected 'dc' changed. In this case sense re-initialize network list (and code is breaking this logic). I bug, discover this method is called 'dc' 'network' selected (and I guess new change dc done)</technical_language>

Target:
private void initNetworkList(Guid dataCenterId) { startProgress(); IdQueryParameters queryParams = new IdQueryParameters(dataCenterId); Frontend.getInstance().runQuery(QueryType.GetAllNetworks, queryParams, new AsyncQuery<QueryReturnValue>(returnValue -> { Collection<Network> networks = returnValue.getReturnValue(); getNetwork().setItems(networks); updateNetworks(networks); stopProgress(); })); }
Source:
<code>public Collection<Object> handleMessage(IncomingMessageEnvelope ime, MessageCollector collector, TaskCoordinator coordinator) { Object tmpMessage, message = null; InputTransformer transformer = inputOpSpec.getTransformer(); if (transformer != null) { tmpMessage = transformer.apply(ime); if (tmpMessage instanceof KV && ime.getTimestamp() > 0L) { Object kvValue = ((KV) tmpMessage).getValue(); if (kvValue != null && kvValue instanceof IndexedRecord) { IndexedRecord retRec = checkAndAddField((IndexedRecord) kvValue, "eventTime", Instant.ofEpochMilli(ime.getTimestamp()).toString()); retRec = checkAndAddField(retRec, "arrivalTime", Instant.now().toString()); <START> message = new KV<>(((KV) tmpMessage).getKey(), retRec); <END> } } else { message = tmpMessage; } } else { message = this.inputOpSpec.isKeyed() ? KV.of(ime.getKey(), ime.getMessage()) : ime.getMessage(); } if (message != null) { return Collections.singletonList(message); } return Collections.emptyList(); }</code><technical_language>add special logic for avro</technical_language>

Target:
public Collection<Object> handleMessage(IncomingMessageEnvelope ime, MessageCollector collector, TaskCoordinator coordinator) { Object message; InputTransformer transformer = inputOpSpec.getTransformer(); if (transformer != null) { message = transformer.apply(ime); } else { message = this.inputOpSpec.isKeyed() ? KV.of(ime.getKey(), ime.getMessage()) : ime.getMessage(); } if (message != null) { return Collections.singletonList(message); } return Collections.emptyList(); }
Source:
<code>private void sendWithdrawEmail(Study study, String externalId, Account account, Withdrawal withdrawal, long withdrewOn) { if (account.getEmail() == null) { return; } Boolean consentNotificationEmailVerified = study.isConsentNotificationEmailVerified(); <START> if (consentNotificationEmailVerified != null && !consentNotificationEmailVerified) { <END> return; } MimeTypeEmailProvider consentEmail = new WithdrawConsentEmailProvider(study, externalId, account, withdrawal, withdrewOn); sendMailService.sendEmail(consentEmail); }</code><technical_language>if (consentNotificationEmailVerified != Boolean.TRUE)</technical_language>

Target:
private void sendWithdrawEmail(Study study, String externalId, Account account, Withdrawal withdrawal, long withdrewOn) { if (account.getEmail() == null) { return; } if (study.isConsentNotificationEmailVerified() == Boolean.FALSE) { return; } MimeTypeEmailProvider consentEmail = new WithdrawConsentEmailProvider(study, externalId, account, withdrawal, withdrewOn); sendMailService.sendEmail(consentEmail); }
Source:
<code>public String tIpv6address() { int startIdx = ptr; try { <START> while (hasMoreChars()) { <END> char nextChar = lookAhead(0); if ( isIPV6addressChar(nextChar) ) { consume(1); } else { break; } } return String.valueOf(buffer, startIdx, ptr - startIdx); } catch (ParseException ex) { return null; } }</code><technical_language>square bracket finish ip address processing</technical_language>

Target:
public String tIpv6address() { try { String hostName = String.valueOf(buffer, ptr, buffer.length - ptr ); HostNameParser hnp = new HostNameParser(hostName); HostPort hp = hnp.hostPort(true); int length = hp.getHost().hostname.length(); consume(length); return hp.getHost().hostname; } catch (ParseException ex) { return null; } }
Source:
<code>private boolean restoreInitialState() { Guid statelessVmSnapshotId = getVmSnapshotIdForType(SnapshotType.STATELESS); if (statelessVmSnapshotId == null) { return true; } List<DiskImage> statelessDiskSnapshots = getDiskSnapshotsForVmSnapshot(statelessVmSnapshotId); Guid activeVmSnapshotId = getVmSnapshotIdForType(SnapshotType.ACTIVE); List<DiskImage> activeDiskSnapshots = getDiskSnapshotsForVmSnapshot(activeVmSnapshotId); Set<Guid> disksWithStatelessSnapshot = new HashSet<>(); for (DiskImage statelessDiskSnapshot : statelessDiskSnapshots) { disksWithStatelessSnapshot.add(statelessDiskSnapshot.getId()); <START> } <END> for (DiskImage activeDiskSnapshot : activeDiskSnapshots) { if (!disksWithStatelessSnapshot.contains(activeDiskSnapshot.getId())) { VdcReturnValueBase returnValue = runInternalAction ( VdcActionType.DetachDiskFromVm, new AttachDetachVmDiskParameters( getVmId(), activeDiskSnapshot.getId(), false, false)); if (!returnValue.getSucceeded()) { return false; } } } if (!statelessDiskSnapshots.isEmpty()) { return runInternalActionWithTasksContext(VdcActionType.RestoreAllSnapshots, buildRestoreAllSnapshotsParameters(statelessDiskSnapshots), getLock()).getSucceeded(); } return true; }</code><technical_language>Please Entities.getIds(...)</technical_language>

Target:
private boolean restoreInitialState() { Guid statelessVmSnapshotId = getVmSnapshotIdForType(SnapshotType.STATELESS); if (statelessVmSnapshotId == null) { return true; } List<DiskImage> statelessDiskSnapshots = getDiskSnapshotsForVmSnapshot(statelessVmSnapshotId); Guid activeVmSnapshotId = getVmSnapshotIdForType(SnapshotType.ACTIVE); List<DiskImage> activeDiskSnapshots = getDiskSnapshotsForVmSnapshot(activeVmSnapshotId); List<Guid> disksWithStatelessSnapshot = Entities.getIds(statelessDiskSnapshots); for (DiskImage activeDiskSnapshot : activeDiskSnapshots) { if (!disksWithStatelessSnapshot.contains(activeDiskSnapshot.getId())) { VdcReturnValueBase returnValue = runInternalAction ( VdcActionType.DetachDiskFromVm, new AttachDetachVmDiskParameters( getVmId(), activeDiskSnapshot.getId(), false, false)); if (!returnValue.getSucceeded()) { log.error("Could not restore stateless VM due to a failure to detach Disk {}", getVmId(), activeDiskSnapshot.getId()); return false; } } } if (!statelessDiskSnapshots.isEmpty()) { return runInternalActionWithTasksContext(VdcActionType.RestoreAllSnapshots, buildRestoreAllSnapshotsParameters(statelessDiskSnapshots), getLock()).getSucceeded(); } return true; }
Source:
<code>public void testGetAllForStorageDomainWithPermissionsForUnpriviligedUser() { List<VmTemplate> result = dao.getAllForStorageDomain(STORAGE_DOMAIN_ID, UNPRIVILEGED_USER_ID, true); assertNotNull(result); <START> assertTrue(result.size() == 0); <END> }</code><technical_language>check result.isEmpty</technical_language>

Target:
public void testGetAllForStorageDomainWithPermissionsForUnpriviligedUser() { List<VmTemplate> result = dao.getAllForStorageDomain(STORAGE_DOMAIN_ID, UNPRIVILEGED_USER_ID, true); assertNotNull(result); assertTrue(result.isEmpty()); }
Source:
<code>SetQuotaCommand(String[] args, int pos, Configuration conf) { super(conf); CommandFormat c = new CommandFormat(2, Integer.MAX_VALUE); List<String> parameters = c.parse(args, pos); String str = parameters.get(0).trim(); try { this.quota = StringUtils.TraditionalBinaryPrefix .string2long(parameters.remove(0)); } catch(NumberFormatException e){ throw new IllegalArgumentException("\"" + str + "\" is not a valid value for a quota."); } if (HdfsConstants.QUOTA_DONT_SET == this.quota) { <START> System.out.print("WARN: \"" + this.quota + <END> "\" means QUOTA_DONT_SET, quota will not be set, " + "it keep the old values. \n"); } this.args = parameters.toArray(new String[parameters.size()]); }</code><technical_language>IMO, System.err.print. Another side, is throw exception need execute logic if meet invalid parameter</technical_language>

Target:
SetQuotaCommand(String[] args, int pos, Configuration conf) { super(conf); CommandFormat c = new CommandFormat(2, Integer.MAX_VALUE); List<String> parameters = c.parse(args, pos); String str = parameters.get(0).trim(); try { this.quota = StringUtils.TraditionalBinaryPrefix .string2long(parameters.remove(0)); } catch(NumberFormatException e){ throw new IllegalArgumentException("\"" + str + "\" is not a valid value for a quota."); } if (HdfsConstants.QUOTA_DONT_SET == this.quota) { throw new IllegalArgumentException("WARN: \"" + this.quota + "\" means QUOTA_DONT_SET, quota will not be set, " + "it keep the old values."); } this.args = parameters.toArray(new String[parameters.size()]); }
Source:
<code>public void shouldCapture() throws Exception { when(response.getStatus()).thenReturn(HttpStatus.SC_OK); <START> Either<GatewayError, GatewayClient.Response> stupidEitherThing = right(new TestResponse(response)); <END> when(client.postRequestFor(anyString(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(stupidEitherThing); Either<GatewayError, EpdqCaptureResponse> stupidEitherThing2 = right(XMLUnmarshaller.unmarshall(load(EPDQ_CAPTURE_SUCCESS_RESPONSE), EpdqCaptureResponse.class)); when(client.unmarshallResponse(any(TestResponse.class), any(Class.class))).thenReturn(stupidEitherThing2); GatewayResponse<BaseCaptureResponse> response = epdqCaptureHandler.capture(buildTestCaptureRequest()); assertTrue(response.isSuccessful()); assertThat(response.getBaseResponse().get().getTransactionId(), is("3014644340")); }</code><technical_language>A name stupidEitherThing</technical_language>

Target:
public void shouldCapture() throws Exception { when(response.getStatus()).thenReturn(HttpStatus.SC_OK); Either<GatewayError, GatewayClient.Response> response = right(new TestResponse(this.response)); when(client.postRequestFor(anyString(), any(GatewayAccountEntity.class), any(GatewayOrder.class))).thenReturn(response); Either<GatewayError, EpdqCaptureResponse> unmarshalledResponse = right(XMLUnmarshaller.unmarshall(load(EPDQ_CAPTURE_SUCCESS_RESPONSE), EpdqCaptureResponse.class)); when(client.unmarshallResponse(any(TestResponse.class), any(Class.class))).thenReturn(unmarshalledResponse); GatewayResponse<BaseCaptureResponse> gatewayResponse = epdqCaptureHandler.capture(buildTestCaptureRequest()); assertTrue(gatewayResponse.isSuccessful()); assertThat(gatewayResponse.getBaseResponse().get().getTransactionId(), is("3014644340")); }
Source:
<code>public static void run(Runnable runnable) { <START> try { <END> MessagingFactory.INTERNAL_THREAD_POOL.submit(runnable); } catch (RejectedExecutionException | NullPointerException e) { e.printStackTrace(); } }</code><technical_language>Is logger? check service team ask if this behaviour change is OK them</technical_language>

Target:
public static void run(Runnable runnable) { MessagingFactory.INTERNAL_THREAD_POOL.submit(runnable); }
Source:
<code>public void onReceive(Context context, final Intent intent) { ContextManager.setContext(context); DependencyInjectionService.getInstance().inject(this); if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) { handleRegistration(intent); } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { new Thread(new Runnable() { @Override public void run() { if(intent.hasExtra("web_update")) if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > FULL_SYNC_TIME_INTERVAL) new ActFmSyncProvider().synchronize(ContextManager.getContext()); else <START> handleWebUpdate(intent); <END> else handleMessage(intent); } }).start(); } }</code><technical_language>I hoping kill handleWebUpdate, code is infrequently used! but... this do for now</technical_language>

Target:
public void onReceive(Context context, final Intent intent) { ContextManager.setContext(context); DependencyInjectionService.getInstance().inject(this); if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) { handleRegistration(intent); } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { new Thread(new Runnable() { @Override public void run() { if(intent.hasExtra("web_update")) if (DateUtilities.now() - actFmPreferenceService.getLastSyncDate() > MIN_MILLIS_BETWEEN_FULL_SYNCS) new ActFmSyncProvider().synchronize(ContextManager.getContext()); else handleWebUpdate(intent); else handleMessage(intent); } }).start(); } }
Source:
<code>private void startServer(DataNodeId dataNodeId, String sslEnabledDatacenters) throws IOException, InstantiationException { Properties props = new Properties(); props.setProperty("host.name", dataNodeId.getHostname()); props.setProperty("port", Integer.toString(dataNodeId.getPort())); props.setProperty("store.data.flush.interval.seconds", "1"); props.setProperty("store.deleted.message.retention.days", "0"); props.setProperty("store.enable.hard.delete", "true"); props.setProperty("replication.token.flush.interval.seconds", "5"); props.setProperty("replication.wait.time.between.replicas.ms", "50"); props.setProperty("replication.validate.message.stream", "true"); props.setProperty("replication.ssl.enabled.datacenters", sslEnabledDatacenters == null ? "" : sslEnabledDatacenters); VerifiableProperties propverify = new VerifiableProperties(props); AmbryServer server = new AmbryServer(propverify, clusterMap, notificationSystem); try { <START> server.startup(); <END> } catch (InstantiationException e) { server.shutdown(); throw e; } serverList.add(server); }</code><technical_language>add server serverlist avoid catch() here</technical_language>

Target:
private void startServer(DataNodeId dataNodeId, String sslEnabledDatacenters) throws IOException, InstantiationException { Properties props = new Properties(); props.setProperty("host.name", dataNodeId.getHostname()); props.setProperty("port", Integer.toString(dataNodeId.getPort())); props.setProperty("store.data.flush.interval.seconds", "1"); props.setProperty("store.deleted.message.retention.days", "0"); props.setProperty("store.enable.hard.delete", "true"); props.setProperty("replication.token.flush.interval.seconds", "5"); props.setProperty("replication.wait.time.between.replicas.ms", "50"); props.setProperty("replication.validate.message.stream", "true"); props.setProperty("replication.ssl.enabled.datacenters", sslEnabledDatacenters); VerifiableProperties propverify = new VerifiableProperties(props); AmbryServer server = new AmbryServer(propverify, clusterMap, notificationSystem); serverList.add(server); server.startup(); }
Source:
<code>public static ExportEvent progress(FormDefinition form, double percentage) { int base100Percentage = new Double(percentage * 100).intValue(); <START> String statusLine = String.format("Exported %s%% of the submissions", base100Percentage); <END> return new ExportEvent(form.getFormId(), statusLine); }</code><technical_language>of statements true: ![screen shot 2018-05-17 1 41 11 pm](<LINK_0></technical_language>

Target:
public static ExportEvent progress(FormDefinition form, double percentage) { int base100Percentage = new Double(percentage * 100).intValue(); String statusLine = String.format("Exported %s%% of the submissions", base100Percentage); return new ExportEvent(form.getFormId(), statusLine, false); }
Source:
<code>public static void main(String[] args) throws Exception { CommandLineTools.runUpgradeCheck(args); if (args.length == 0) { process("<stdin>", new BufferedReader( new InputStreamReader(System.in, Constants.ENCODING))); } else { <START> validate(args); <END> } }</code><technical_language>a next step is get return of validate() call set System.exit() accordingly. happen a follow up</technical_language>

Target:
public static void main(String[] args) throws Exception { CommandLineTools.runUpgradeCheck(args); boolean result = true; if (args.length == 0) { result = validate(new BufferedReader( new InputStreamReader(System.in, Constants.ENCODING)), "<stdin>"); } else { boolean[] results = validate(args); int count = 0; for (int i = 0; i < results.length; i++) { if (results[i]) { count++; } } result = (count == results.length); } if (result) { System.exit(0); } else { System.exit(1); } }
Source:
<code>public void dispose() { <START> nodeMap.clear(); <END> edgeMap.clear(); }</code><technical_language>I recall this is safe. need iterator modify collection while iterating it</technical_language>

Target:
public void dispose() { nodeMap.clear(); edgeMap.clear(); reverseEdgeMap.clear(); }
Source:
<code>public void setArgsType(String argsType) { try { setArgsType(ArgsTypeOption.valueOf(argsType.toUpperCase(Locale.ROOT))); } catch (IllegalArgumentException e) { <START> LOG.error('"' + argsType + "\" is not a valid Arguments Specification Type."); <END> throw e; } }</code><technical_language>Core log problem (in case this error, bad input issue code)</technical_language>

Target:
public void setArgsType(String argsType) throws ApiException { try { setArgsType(ArgsTypeOption.valueOf(argsType.toUpperCase(Locale.ROOT))); } catch (IllegalArgumentException e) { LOG.debug('"' + argsType + "\" is not a valid Arguments Specification Type."); throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, e.getMessage()); } }
Source:
<code>public Optional<OTAHistory> insertOTAEvent(final OTAHistory historyEntry) { final Map<String, AttributeValue> item = new HashMap<>(); item.put(DEVICE_ID_ATTRIBUTE_NAME, new AttributeValue().withS(historyEntry.device_id)); <START> item.put(EVENT_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(historyEntry.event_time)); <END> item.put(CURRENT_FW_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(historyEntry.current_fw_version.toString())); item.put(NEW_FW_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(historyEntry.new_fw_version.toString())); item.put(FILE_LIST_ATTRIBUTE_NAME, new AttributeValue().withSS(historyEntry.file_list)); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, item); try { final PutItemResult result = this.dynamoDBClient.putItem(putItemRequest); return Optional.of(historyEntry); }catch (AmazonServiceException awsEx){ LOGGER.error("OTA Event insert failed. AWS service error {}", awsEx.getMessage()); }catch (AmazonClientException awcEx){ LOGGER.error("OTA Event insert failed. Client error.", awcEx.getMessage()); } return Optional.absent(); }</code><technical_language>Convert String datetime format. a SenseEventsDAO a static method converts string datetime vice-versa</technical_language>

Target:
public Optional<OTAHistory> insertOTAEvent(final OTAHistory historyEntry) { final Map<String, AttributeValue> item = new HashMap<>(); item.put(DEVICE_ID_ATTRIBUTE_NAME, new AttributeValue().withS(historyEntry.deviceId)); item.put(EVENT_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(dateTimeToString(historyEntry.eventTime))); item.put(CURRENT_FW_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(historyEntry.currentFWVersion.toString())); item.put(NEW_FW_VERSION_ATTRIBUTE_NAME, new AttributeValue().withN(historyEntry.newFWVersion.toString())); item.put(FILE_LIST_ATTRIBUTE_NAME, new AttributeValue().withSS(historyEntry.fileList)); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, item); try { final PutItemResult result = this.dynamoDBClient.putItem(putItemRequest); return Optional.of(historyEntry); }catch (AmazonServiceException awsEx){ LOGGER.error("OTA Event insert failed. AWS service error {}", awsEx.getMessage()); }catch (AmazonClientException awcEx){ LOGGER.error("OTA Event insert failed. Client error.", awcEx.getMessage()); } return Optional.absent(); }
Source:
<code>private static LeaderTimeGetter getLeaderTimeGetter( String timelockNamespace, Optional<TimeLockRequestBatcherProviders> timelockRequestBatcherProviders, AtlasDbDialogueServiceProvider serviceProvider, LeaderElectionReportingTimelockService namespacedConjureTimelockService) { return timelockRequestBatcherProviders .map(TimeLockRequestBatcherProviders::leaderTimeBatcherProvider) .map(provider -> provider.getBatcher(getMultiClientTimelockServiceSupplier(serviceProvider))) <START> .<LeaderTimeGetter>map(batcher -> new NamespacedCoalescingLeaderTimeGetter(timelockNamespace, batcher)) <END> .orElseGet(() -> new LegacyLeaderTimeGetter(namespacedConjureTimelockService)); }</code><technical_language>wow, needs this type hint work? Funky</technical_language>

Target:
private static LeaderTimeGetter getLeaderTimeGetter( String timelockNamespace, Optional<TimeLockRequestBatcherProviders> timelockRequestBatcherProviders, AtlasDbDialogueServiceProvider serviceProvider, LeaderElectionReportingTimelockService namespacedConjureTimelockService) { if (!timelockRequestBatcherProviders.isPresent()) { return new LegacyLeaderTimeGetter(namespacedConjureTimelockService); } LeaderTimeCoalescingBatcher batcher = timelockRequestBatcherProviders .get() .leaderTimeBatcherProvider() .getBatcher(getMultiClientTimelockServiceSupplier(serviceProvider)); return new NamespacedCoalescingLeaderTimeGetter(timelockNamespace, batcher); }
Source:
<code>protected void setDns(Instance instance, Map<String, Object> labels, Map<Object, Object> data) { if (instance.getSystemContainer() != null) { return; } if (InstanceConstants.KIND_CONTAINER.equals(instance.getKind())) { boolean addDns = true; if (labels.containsKey(SystemLabels.LABEL_USE_RANCHER_DNS) <START> && !Boolean.valueOf(labels.get(SystemLabels.LABEL_USE_RANCHER_DNS).toString())) { <END> addDns = false; } if (addDns) { String networkMode = DataAccessor.fields(instance).withKey(DockerInstanceConstants.FIELD_NETWORK_MODE) .as(String.class); if (DockerNetworkConstants.NETWORK_MODE_MANAGED.equals(networkMode)) { List<String> dns = DataAccessor.fieldStringList(instance, DockerInstanceConstants.FIELD_DNS); dns.add(NetworkConstants.INTERNAL_DNS_IP); data.put(DockerInstanceConstants.FIELD_DNS, dns); data.put(InstanceConstants.FIELD_DNS_INTERNAL, Joiner.on(",").join(dns)); } List<String> dnsSearch = DataAccessor.fieldStringList(instance, DockerInstanceConstants.FIELD_DNS_SEARCH); dnsSearch.add(NetworkConstants.INTERNAL_DNS_SEARCH_DOMAIN); data.put(DockerInstanceConstants.FIELD_DNS_SEARCH, dnsSearch); data.put(InstanceConstants.FIELD_DNS_SEARCH_INTERNAL, Joiner.on(",").join(dnsSearch)); } } }</code><technical_language>this NPE</technical_language>

Target:
protected void setDns(Instance instance, Map<String, Object> labels, Map<Object, Object> data) { if (instance.getSystemContainer() != null) { return; } if (InstanceConstants.KIND_CONTAINER.equals(instance.getKind())) { boolean addDns = true; Object lblValue = labels.get(SystemLabels.LABEL_USE_RANCHER_DNS); if (lblValue != null && !Boolean.valueOf(lblValue.toString())) { addDns = false; } if (addDns) { String networkMode = DataAccessor.fields(instance).withKey(DockerInstanceConstants.FIELD_NETWORK_MODE) .as(String.class); if (DockerNetworkConstants.NETWORK_MODE_MANAGED.equals(networkMode)) { List<String> dns = DataAccessor.fieldStringList(instance, DockerInstanceConstants.FIELD_DNS); dns.add(NetworkConstants.INTERNAL_DNS_IP); data.put(DockerInstanceConstants.FIELD_DNS, dns); data.put(InstanceConstants.FIELD_DNS_INTERNAL, Joiner.on(",").join(dns)); } List<String> dnsSearch = DataAccessor.fieldStringList(instance, DockerInstanceConstants.FIELD_DNS_SEARCH); dnsSearch.add(NetworkConstants.INTERNAL_DNS_SEARCH_DOMAIN); data.put(DockerInstanceConstants.FIELD_DNS_SEARCH, dnsSearch); data.put(InstanceConstants.FIELD_DNS_SEARCH_INTERNAL, Joiner.on(",").join(dnsSearch)); } } }
Source:
<code>protected String computeMetricName(Message<?> message) { <START> return fvcSinkProperties.getComputedNameExpression().getValue(evaluationContext, <END> message, CharSequence.class).toString(); }</code><technical_language>EvaluationContext set thanks SpelExpressionConverterConfiguration</technical_language>

Target:
protected String computeMetricName(Message<?> message) { return fvcSinkProperties.getComputedNameExpression().getValue(message, CharSequence.class).toString(); }
Source:
<code>private static boolean isTinymceStyleDiv(Node attribute) { if (!"style".equalsIgnoreCase(attribute.getNodeName())) { <START> return false; <END> } String value = attribute.getNodeValue(); return value.contains("position: static") && value.contains("height: 0px") && value.contains("width: 0px;") && value.contains("padding: 0px;") && value.contains("margin: 0px;"); }</code><technical_language>this return false this is called a div node a style node</technical_language>

Target:
private static boolean isTinymceStyleDiv(Node attribute) { if (!"style".equalsIgnoreCase(attribute.getNodeName())) { return false; } String value = attribute.getNodeValue(); return value.contains("position: static") && value.contains("height: 0px") && value.contains("width: 0px") && value.contains("padding: 0px") && value.contains("margin: 0px"); }
Source:
<code>static File addLocalMavenRepoInitScriptCommandLineOption(@NotNull List<String> args, @NotNull File repoPath) { try { <START> File file = FileUtil.createTempFile("asLocalRepo", SdkConstants.DOT_GRADLE); <END> file.deleteOnExit(); String[] lines = { "allprojects {", " buildscript {", " repositories {", " maven { url '" + repoPath.getPath() + "'}", " }", " }", "}", }; String contents = StringUtil.join(lines, SystemProperties.getLineSeparator()); FileUtil.writeToFile(file, contents); ContainerUtil.addAll(args, GradleConstants.INIT_SCRIPT_CMD_OPTION, file.getAbsolutePath()); return file; } catch (IOException e) { LOG.warn("Failed to set up 'local repo' Gradle init script", e); } return null; }</code><technical_language>This sitting in build/intermediates too. luxury of knowing directory this early point (because Gradle model synced yet)</technical_language>

Target:
static File addLocalMavenRepoInitScriptCommandLineOption(@NotNull List<String> args, @NotNull File repoPath) { try { File file = FileUtil.createTempFile("asLocalRepo", SdkConstants.DOT_GRADLE); file.deleteOnExit(); String contents ="allprojects {\n" + " buildscript {\n" + " repositories {\n" + " maven { url '" + GradleImport.escapeGroovyStringLiteral(repoPath.getPath()) + "'}\n" + " }\n" + " }\n" + "}\n"; FileUtil.writeToFile(file, contents); ContainerUtil.addAll(args, GradleConstants.INIT_SCRIPT_CMD_OPTION, file.getAbsolutePath()); return file; } catch (IOException e) { LOG.warn("Failed to set up 'local repo' Gradle init script", e); } return null; }
Source:
<code>protected String typeAheadNameTemplateNullSafe(String name) { if <START> (name != null && !name.trim().isEmpty()) { <END> return templates.typeAheadName(name).asString(); } else { return templates.typeAheadEmptyContent().asString(); } }</code><technical_language>Please org.ovirt.engine.ui.uicompat.external.StringUtils#isNotEmpty</technical_language>

Target:
protected String typeAheadNameTemplateNullSafe(String name) { if (StringUtils.isNotEmpty(name)) { return templates.typeAheadName(name).asString(); } else { return templates.typeAheadEmptyContent().asString(); } }
Source:
<code>public void execute(Tuple tuple) { tuplesReceived++; String streamID = tuple.getSourceStreamId(); LOG.info("Received a tuple: " + tuple + " ; from: " + streamID); if (streamID.equals(Constants.INTEGRATION_TEST_CONTROL_STREAM_ID)) { terminalsToReceive--; if (terminalsToReceive == 0) { if (IBatchBolt.class.isInstance(delegateBolt)) { LOG.fine("Invoke bolt to do finishBatch!"); ((IBatchBolt) delegateBolt).finishBatch(); } LOG.info("Populating the terminals to downstream"); collector.emit(Constants.INTEGRATION_TEST_CONTROL_STREAM_ID, tuple, new Values(Constants.INTEGRATION_TEST_TERMINAL)); } else { LOG.info(String.format( <START> "Received a terminals, waiting to receive %s more", terminalsToReceive)); <END> } } else { currentTupleProcessing = tuple; delegateBolt.execute(tuple); collector.ack(tuple); } }</code><technical_language>Received a terminal Received terminals</technical_language>

Target:
public void execute(Tuple tuple) { tuplesReceived++; String streamID = tuple.getSourceStreamId(); LOG.info("Received a tuple: " + tuple + " ; from: " + streamID); if (streamID.equals(Constants.INTEGRATION_TEST_CONTROL_STREAM_ID)) { terminalsToReceive--; if (terminalsToReceive == 0) { if (IBatchBolt.class.isInstance(delegateBolt)) { LOG.fine("Invoke bolt to do finishBatch!"); ((IBatchBolt) delegateBolt).finishBatch(); } LOG.info("Received the last terminal, populating the terminals to downstream"); collector.emit(Constants.INTEGRATION_TEST_CONTROL_STREAM_ID, tuple, new Values(Constants.INTEGRATION_TEST_TERMINAL)); } else { LOG.info(String.format( "Received a terminal, need to receive %s more", terminalsToReceive)); } } else { currentTupleProcessing = tuple; delegateBolt.execute(tuple); collector.ack(tuple); } }
Source:
<code>public static String generateSetupId() { <START> String setupId = <END> "" + ALPHA_NUMERIC_STRING.charAt((int) (Math.random() * ALPHA_NUMERIC_STRING.length())) + ALPHA_NUMERIC_STRING.charAt((int) (Math.random() * ALPHA_NUMERIC_STRING.length())) + ALPHA_NUMERIC_STRING.charAt((int) (Math.random() * ALPHA_NUMERIC_STRING.length())) + ALPHA_NUMERIC_STRING.charAt((int) (Math.random() * ALPHA_NUMERIC_STRING.length())); return setupId; }</code><technical_language>calling randomAlphaNumeric here</technical_language>

Target:
public static String generateSetupId() { return randomAlphaNumeric(4); }
Source:
<code>public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); <START> API.getInstance().registerApiImplementor(new CodeDxAPI(this)); <END> if (getView() != null) { extensionHook.getHookMenu().addReportMenuItem(getUploadMenu()); extensionHook.getHookMenu().addReportMenuItem(getExportMenu()); } }</code><technical_language>This needs removed add-on is uninstalled, if targeting ZAP 2.6.0 is a problem call extensionHook.addApiImplementor instead (which allows core automatically remove it), need override unload call removeApiImplementor</technical_language>

Target:
public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); cdxAPIImpl = new CodeDxAPI(this); API.getInstance().registerApiImplementor(cdxAPIImpl); if (getView() != null) { extensionHook.getHookMenu().addReportMenuItem(getUploadMenu()); extensionHook.getHookMenu().addReportMenuItem(getExportMenu()); } }
Source:
<code>public void shouldReturnEmptyArray_whenGetSubcommandSpecified() { List<Slowlog> actualResult = jedis.slowlogGet(); <START> assertThat(actualResult.size()).isEqualTo(0); <END> }</code><technical_language>assertThat(actualResult).isEmpty() (and for below) . This preferable if result is empty, error message display contents of array length. I notice this in review</technical_language>

Target:
public void shouldReturnEmptyArray_whenGetSubcommandSpecified() { List<Slowlog> actualResult = jedis.slowlogGet(); assertThat(actualResult.isEmpty()); }
Source:
<code>protected void executeCommand() { <START> beforeUpdate(); <END> removeQuotaFromCache(); setQuotaParameter(); QuotaDAO dao = getQuotaDAO(); dao.update(getParameters().getQuota()); getReturnValue().setSucceeded(true); afterUpdate(); }</code><technical_language>I provide a message. is need for another roundtrip for DB</technical_language>

Target:
protected void executeCommand() { removeQuotaFromCache(); setQuotaParameter(); QuotaDAO dao = getQuotaDAO(); dao.update(getParameters().getQuota()); getReturnValue().setSucceeded(true); afterUpdate(); }
Source:
<code><START> public byte[] getSourceIpAddress() { <END> @SuppressWarnings("null") @NonNull byte[] ip = Arrays.copyOf(fSourceIpAddress, fSourceIpAddress.length); return ip; }</code><technical_language>please replace INetAddress</technical_language>

Target:
public Inet4Address getSourceIpAddress() { return fSourceIpAddress; }
Source:
<code>protected void initGroups(Class<? extends ITestOrConfiguration> annotationClass) { ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); <START> ITestOrConfiguration classAnnotation; <END> Object object = getInstance(); if (object == null) { classAnnotation = getAnnotationFinder() .findAnnotation(getConstructorOrMethod().getDeclaringClass(), annotationClass); } else { classAnnotation = getAnnotationFinder().findAnnotation(object.getClass(), annotationClass); } setGroups( getStringArray( null != annotation ? annotation.getGroups() : null, null != classAnnotation ? classAnnotation.getGroups() : null)); initRestOfGroupDependencies(annotationClass); }</code><technical_language>I code easier understand that: java Object object = getInstance(); if (object == null) { clazz = getConstructorOrMethod().getDeclaringClass(); } else { clazz = object.getClass(); } ITestOrConfigurationclassAnnotation = getAnnotationFinder().findAnnotation(clazz, annotationClass);</technical_language>

Target:
protected void initGroups(Class<? extends ITestOrConfiguration> annotationClass) { ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); Object object = getInstance(); Class<?> clazz = getConstructorOrMethod().getDeclaringClass(); if (object != null) { clazz = object.getClass(); } ITestOrConfiguration classAnnotation = getAnnotationFinder().findAnnotation(clazz, annotationClass); setGroups( getStringArray( null != annotation ? annotation.getGroups() : null, null != classAnnotation ? classAnnotation.getGroups() : null)); initRestOfGroupDependencies(annotationClass); }
Source:
<code>public static void writeObjectToConfAsBase64(String key, Object obj, Configuration conf) throws IOException { <START> try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { <END> try (GZIPOutputStream gos = new GZIPOutputStream(baos)) { try (ObjectOutputStream oos = new ObjectOutputStream(gos)) { oos.writeObject(obj); } } conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), StandardCharsets.UTF_8)); } }</code><technical_language>consolidate a single try e.g.: try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); ObjectOutputStream oos = new ObjectOutputStream(gos)) { oos.writeObject(obj); conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), "UTF-8")); }</technical_language>

Target:
public static void writeObjectToConfAsBase64(String key, Object obj, Configuration conf) throws IOException { try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try(GZIPOutputStream gos = new GZIPOutputStream(baos); ObjectOutputStream oos = new ObjectOutputStream(gos)) { oos.writeObject(obj); } conf.set(key, new String(Base64.encodeBase64(baos.toByteArray()), StandardCharsets.UTF_8)); } }
Source:
<code>public Object[] getChildren(Object parentElement) { RepositoryTreeNode node = (RepositoryTreeNode) parentElement; Repository repo = node.getRepository(); switch (node.getType()) { case BRANCHES: List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); Repository rep = node.getRepository(); <START> for (Map.Entry<String, Ref> ref : rep.getAllRefs().entrySet()) { <END> refs.add(new RepositoryTreeNode<Ref>(node, RepositoryTreeNodeType.REF, repo, ref.getValue())); } return refs.toArray(); case REPO: List<RepositoryTreeNode<Repository>> branches = new ArrayList<RepositoryTreeNode<Repository>>(); branches.add(new RepositoryTreeNode<Repository>(node, RepositoryTreeNodeType.BRANCHES, node.getRepository(), node.getRepository())); branches.add(new RepositoryTreeNode<Repository>(node, RepositoryTreeNodeType.PROJECTS, node.getRepository(), node.getRepository())); return branches.toArray(); case PROJECTS: List<RepositoryTreeNode<File>> projects = new ArrayList<RepositoryTreeNode<File>>(); Collection<File> result = new HashSet<File>(); Set<String> traversed = new HashSet<String>(); collectProjectFilesFromDirectory(result, repo.getDirectory() .getParentFile(), traversed, new NullProgressMonitor()); for (File file : result) { projects.add(new RepositoryTreeNode<File>(node, RepositoryTreeNodeType.PROJ, repo, file)); } return projects.toArray(); default: return null; } }</code><technical_language>iterating values results in easier read code</technical_language>

Target:
public Object[] getChildren(Object parentElement) { RepositoryTreeNode node = (RepositoryTreeNode) parentElement; Repository repo = node.getRepository(); switch (node.getType()) { case BRANCHES: List<RepositoryTreeNode<Ref>> refs = new ArrayList<RepositoryTreeNode<Ref>>(); Repository rep = node.getRepository(); for (Ref ref : rep.getAllRefs().values()) { refs.add(new RepositoryTreeNode<Ref>(node, RepositoryTreeNodeType.REF, repo, ref)); } return refs.toArray(); case REPO: List<RepositoryTreeNode<Repository>> branches = new ArrayList<RepositoryTreeNode<Repository>>(); branches.add(new RepositoryTreeNode<Repository>(node, RepositoryTreeNodeType.BRANCHES, node.getRepository(), node.getRepository())); branches.add(new RepositoryTreeNode<Repository>(node, RepositoryTreeNodeType.PROJECTS, node.getRepository(), node.getRepository())); return branches.toArray(); case PROJECTS: List<RepositoryTreeNode<File>> projects = new ArrayList<RepositoryTreeNode<File>>(); Collection<File> result = new HashSet<File>(); Set<String> traversed = new HashSet<String>(); collectProjectFilesFromDirectory(result, repo.getDirectory() .getParentFile(), traversed, new NullProgressMonitor()); for (File file : result) { projects.add(new RepositoryTreeNode<File>(node, RepositoryTreeNodeType.PROJ, repo, file)); } Comparator<RepositoryTreeNode<File>> sorter = new Comparator<RepositoryTreeNode<File>>() { public int compare(RepositoryTreeNode<File> o1, RepositoryTreeNode<File> o2) { return o1.getObject().getName().compareTo( o2.getObject().getName()); } }; Collections.sort(projects, sorter); return projects.toArray(); default: return null; } }
Source:
<code>public Status update(String table, String key, HashMap<String, ByteIterator> values) { try { SolrInputDocument updatedDoc = new SolrInputDocument(); updatedDoc.addField("id", key); for (Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { Map<String, Object> fieldModifier = new HashMap<>(1); <START> fieldModifier.put("set", entry.getValue()); <END> updatedDoc.addField(entry.getKey(), fieldModifier); } UpdateResponse writeResponse; if (batchMode) { writeResponse = client.add(table, updatedDoc, commitTime); } else { writeResponse = client.add(table, updatedDoc); client.commit(table); } return checkStatus(writeResponse.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }</code><technical_language>Collections.singletonMap(K, V)</technical_language>

Target:
public Status update(String table, String key, HashMap<String, ByteIterator> values) { try { SolrInputDocument updatedDoc = new SolrInputDocument(); updatedDoc.addField("id", key); for (Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { updatedDoc.addField(entry.getKey(), Collections.singletonMap("set", entry.getValue())); } UpdateResponse writeResponse; if (batchMode) { writeResponse = client.add(table, updatedDoc, commitTime); } else { writeResponse = client.add(table, updatedDoc); client.commit(table); } return checkStatus(writeResponse.getStatus()); } catch (IOException | SolrServerException e) { e.printStackTrace(); } return Status.ERROR; }
Source:
<code>public void onSuccess(final LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { FacebookRequestError requestError = response.getError(); if (requestError != null) { Log.e(TAG, "Received Facebook error: " + requestError.getErrorMessage()); onFailure(); return; } if (object == null) { Log.w(TAG, "Received null response from Facebook GraphRequest"); onFailure(); } else { String email = null; String name = null; Uri photoUri = null; try { email = object.getString("email"); <START> } catch (JSONException ignored) { } <END> try { name = object.getString("name"); } catch (JSONException ignored) { } try { photoUri = Uri.parse(object.getJSONObject("picture") .getJSONObject("data") .getString("url")); } catch (JSONException ignored) { } onSuccess(loginResult, email, name, photoUri); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,picture"); request.setParameters(parameters); request.executeAsync(); }</code><technical_language>log a warning if get email</technical_language>

Target:
public void onSuccess(final LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { FacebookRequestError requestError = response.getError(); if (requestError != null) { Log.e(TAG, "Received Facebook error: " + requestError.getErrorMessage()); onFailure(); return; } if (object == null) { Log.w(TAG, "Received null response from Facebook GraphRequest"); onFailure(); } else { String email = null; String name = null; Uri photoUri = null; try { email = object.getString("email"); } catch (JSONException e) { Log.e(TAG, "Failure retrieving Facebook email", e); } try { name = object.getString("name"); } catch (JSONException ignored) try { photoUri = Uri.parse(object.getJSONObject("picture") .getJSONObject("data") .getString("url")); } catch (JSONException ignored) onSuccess(loginResult, email, name, photoUri); } } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,picture"); request.setParameters(parameters); request.executeAsync(); }