auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected List<ILogData> getNextEntries(long maxGlobal) { boolean readQueueIsEmpty = !fillReadQueue(maxGlobal); if (maxGlobal < queueAddressManager.getCheckpointSuccessStartAddr()) { throw new TrimmedException(); } if (readQueueIsEmpty) { return Collections.emptyList(); } List<Long> readList = queueAddressManager.getAllReads(maxGlobal); List<ILogData> readResults = readAll(readList).stream() .filter(x -> x.getType() == DataType.DATA) .filter(x -> x.containsStream(id)) .collect(Collectors.toList()); queueAddressManager.clearQueue(maxGlobal); readResults.stream() .forEach(x -> queueAddressManager.addToResolvedQueue(x.getGlobalAddress())); <START> if (!readResults.isEmpty()) { <END> queueAddressManager.setGlobalPointerCheckGCTrimMark(readResults.get(readResults.size() - 1) .getGlobalAddress()); } return readResults; }</code><technical_language>Updating global address this function duplicated. Function remainingUpTo this job</technical_language>

Target:
protected List<ILogData> getNextEntries(long maxGlobal) { boolean readQueueIsEmpty = !fillReadQueue(maxGlobal); if (maxGlobal < queueAddressManager.getCheckpointSuccessStartAddr()) { throw new TrimmedException(); } if (readQueueIsEmpty) { return Collections.emptyList(); } List<Long> readList = queueAddressManager.getAllReads(maxGlobal); List<ILogData> readResults = readAll(readList).stream() .filter(x -> x.getType() == DataType.DATA) .filter(x -> x.containsStream(id)) .collect(Collectors.toList()); queueAddressManager.clearReadQueue(maxGlobal); readResults.stream() .forEach(x -> queueAddressManager.addToResolvedQueue(x.getGlobalAddress())); if (!readResults.isEmpty()) { queueAddressManager.setGlobalPointerCheckGCTrimMark(readResults.get(readResults.size() - 1) .getGlobalAddress()); } return readResults; }
Source:
<code>public Value[] getCurrentValueList(Session session) { HashSet<Value> valueSet = new HashSet<>(); for (Expression e : expressionList) { Value v = e.getValue(session); v = column.convert(v); valueSet.add(v); } <START> Value[] array = valueSet.toArray(new Value[0]); <END> final CompareMode mode = session.getDatabase().getCompareMode(); Arrays.sort(array, new Comparator<Value>() { @Override public int compare(Value o1, Value o2) { return o1.compareTo(o2, mode); } }); return array; }</code><technical_language>Please, revert it. ArrayList.toArray(new T[0]) works faster ArrayList.toArray(new T[list.size()]), other collections not. I checked collections some time JMH tests Java versions decided 0 for ArrayList based results of tests</technical_language>

Target:
public Value[] getCurrentValueList(Session session) { HashSet<Value> valueSet = new HashSet<>(); for (Expression e : expressionList) { Value v = e.getValue(session); v = column.convert(v); valueSet.add(v); } Value[] array = valueSet.toArray(new Value[valueSet.size()]); final CompareMode mode = session.getDatabase().getCompareMode(); Arrays.sort(array, new Comparator<Value>() { @Override public int compare(Value o1, Value o2) { return o1.compareTo(o2, mode); } }); return array; }
Source:
<code>public void executeTransactionAsync_exceptionHandling() throws Throwable { final TestHelper.TestLogger testLogger = new TestHelper.TestLogger(); RealmLog.add(testLogger); final Realm realm = looperThread.realm; assertEquals(0, realm.allObjects(Owner.class).size()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); realm.cancelTransaction(); throw new RuntimeException("Boom"); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { fail("Should not reach success if runtime exception is thrown in callback."); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { <START> assertEquals("Could not cancel transaction, not currently in a transaction.", testLogger.previousMessage); <END> RealmLog.remove(testLogger); looperThread.testComplete(); } }); }</code><technical_language>do need previous message here? Instead of current one</technical_language>

Target:
public void executeTransactionAsync_exceptionHandling() throws Throwable { final TestHelper.TestLogger testLogger = new TestHelper.TestLogger(); RealmLog.add(testLogger); final Realm realm = looperThread.realm; assertEquals(0, realm.where(Owner.class).count()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); realm.cancelTransaction(); throw new RuntimeException("Boom"); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { fail("Should not reach success if runtime exception is thrown in callback."); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { assertEquals("Could not cancel transaction, not currently in a transaction.", testLogger.message); RealmLog.remove(testLogger); looperThread.testComplete(); } }); }
Source:
<code>private VdcBllMessages isReadyToRun(final VDS vds) { if ((!vds.getvds_group_id().equals(getVm().getvds_group_id())) || (vds.getstatus() != VDSStatus.Up) || isVdsFailedToRunVm(vds.getId())) { return VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CLUSTER; } else if (getVm().getstatus() != VMStatus.Paused && !RunVmCommandBase.hasMemoryToRunVM(vds, getVm())) { return VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_MEMORY; } else if (vds.getcpu_cores() != null && getVm().getnum_of_cpus() > vds.getcpu_cores()) { return VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS; } else if (!IsVMSwapValueLegal(vds)) { return VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_SWAP; } <START> return null; <END> }</code><technical_language>IMHO returning null checking for is nice behaviour. consider ValidationResult for job</technical_language>

Target:
private ValidationResult isReadyToRun(final VDS vds) { if ((!vds.getvds_group_id().equals(getVm().getvds_group_id())) || (vds.getstatus() != VDSStatus.Up) || isVdsFailedToRunVm(vds.getId())) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CLUSTER); } else if (getVm().getstatus() != VMStatus.Paused && !RunVmCommandBase.hasMemoryToRunVM(vds, getVm())) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_MEMORY); } else if (vds.getcpu_cores() != null && getVm().getnum_of_cpus() > vds.getcpu_cores()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_CPUS); } else if (!IsVMSwapValueLegal(vds)) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VM_SWAP); } return new ValidationResult(); }
Source:
<code>public void print(String msg) { for (String part : msg.split("\n")) { <START> sender.sendMessage("\u00A7d" + part); <END> } }</code><technical_language>extract special constants named fields</technical_language>

Target:
public void print(String msg) { for (String part : msg.split("\n")) { print(TextComponent.of(part, TextColor.LIGHT_PURPLE)); } }
Source:
<code>public StramLocalCluster(LogicalPlan dag) throws IOException, ClassNotFoundException { dag.validate(); cloneLogicalPlan(dag); String pathUri = CLUSTER_WORK_DIR.toURI().toString(); try { FileContext.getLocalFSFileContext().delete(new Path(pathUri ), true); } catch (IllegalArgumentException e) { throw e; } catch (IOException e) { throw new RuntimeException("could not cleanup test dir", e); } dag.getAttributes().put(LogicalPlan.APPLICATION_ID, "app_local_" + System.currentTimeMillis()); if (dag.getAttributes().get(LogicalPlan.APPLICATION_PATH) == null) { dag.getAttributes().put(LogicalPlan.APPLICATION_PATH, pathUri); } if (dag.getAttributes().get(OperatorContext.STORAGE_AGENT) == null) { dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(new Path(pathUri, LogicalPlan.SUBDIR_CHECKPOINTS).toString(), null)); } this.dnmgr = new StreamingContainerManager(dag); this.umbilical = new UmbilicalProtocolLocalImpl(); <START> for (String jar : dag.getJarResources().keySet()) { <END> try { addToClasspath(jar); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException("Failed to add jar to classpath.", e); } } if (!perContainerBufferServer) { StreamingContainer.eventloop.start(); bufferServer = new Server(0, 1024 * 1024,8); bufferServer.setSpoolStorage(new DiskStorage()); SocketAddress bindAddr = bufferServer.run(StreamingContainer.eventloop); this.bufferServerAddress = ((InetSocketAddress)bindAddr); LOG.info("Buffer server started: {}", bufferServerAddress); } }</code><technical_language>rename jarPath be</technical_language>

Target:
public StramLocalCluster(LogicalPlan dag) throws IOException, ClassNotFoundException { dag.validate(); cloneLogicalPlan(dag); String pathUri = CLUSTER_WORK_DIR.toURI().toString(); try { FileContext.getLocalFSFileContext().delete(new Path(pathUri ), true); } catch (IllegalArgumentException e) { throw e; } catch (IOException e) { throw new RuntimeException("could not cleanup test dir", e); } dag.getAttributes().put(LogicalPlan.APPLICATION_ID, "app_local_" + System.currentTimeMillis()); if (dag.getAttributes().get(LogicalPlan.APPLICATION_PATH) == null) { dag.getAttributes().put(LogicalPlan.APPLICATION_PATH, pathUri); } if (dag.getAttributes().get(OperatorContext.STORAGE_AGENT) == null) { dag.setAttribute(OperatorContext.STORAGE_AGENT, new AsyncFSStorageAgent(new Path(pathUri, LogicalPlan.SUBDIR_CHECKPOINTS).toString(), null)); } this.dnmgr = new StreamingContainerManager(dag); this.umbilical = new UmbilicalProtocolLocalImpl(); if (!perContainerBufferServer) { StreamingContainer.eventloop.start(); bufferServer = new Server(0, 1024 * 1024,8); bufferServer.setSpoolStorage(new DiskStorage()); SocketAddress bindAddr = bufferServer.run(StreamingContainer.eventloop); this.bufferServerAddress = ((InetSocketAddress)bindAddr); LOG.info("Buffer server started: {}", bufferServerAddress); } }
Source:
<code>protected boolean isConnectionAlreadyFormed(final Node<? extends View<?>, ? extends Edge> source, final Node<? extends View<?>, ? extends Edge> target, final Edge<? extends View<?>, ? extends Node> connector) { final Set<Edge<? extends View<?>, ? extends Node>> existingEdges = new HashSet<>(); final Class<?> newConnectorClass = connector .getContent() .getDefinition() .getClass(); <START> source.getOutEdges() <END> .stream() .filter(e -> !e.equals(connector)) .forEach(e -> { final Object content = e.getContent(); if (content instanceof Definition) { final Class<?> existingConnectorClass = ((Definition) content).getDefinition().getClass(); if (newConnectorClass.equals(existingConnectorClass)) { existingEdges.add(e); } } }); if (existingEdges.isEmpty()) { return false; } return existingEdges.stream() .map(Edge::getTargetNode) .filter(n -> n != null) .filter(n -> n.equals(target)) .findFirst() .isPresent(); }</code><technical_language>exercise for myself, I write this snippet of code of a collection inbetween. I rid of null-check final Optional. Feel free this code if it. return source.getOutEdges() .stream() .filter(e -> !Objects.equals(e, connector)) .flatMap(e -> { final Object content = e.getContent(); if (content instanceof Definition) { final Class<?> existingConnectorClass = ((Definition) content).getDefinition().getClass(); if (newConnectorClass.equals(existingConnectorClass)) { return Stream.of(e); } } return Stream.empty(); }) .distinct() .map(Edge::getTargetNode) .anyMatch(n -> Objects.equals(n, target));</technical_language>

Target:
protected boolean isConnectionAlreadyFormed(final Node<? extends View<?>, ? extends Edge> source, final Node<? extends View<?>, ? extends Edge> target, final Edge<? extends View<?>, ? extends Node> connector) { final Class<?> newConnectorClass = connector .getContent() .getDefinition() .getClass(); return source.getOutEdges() .stream() .filter(e -> !Objects.equals(e, connector)) .flatMap(e -> { final Object content = e.getContent(); if (content instanceof Definition) { final Class<?> existingConnectorClass = ((Definition) content).getDefinition().getClass(); if (newConnectorClass.equals(existingConnectorClass)) { return Stream.of(e); } } return Stream.empty(); }) .distinct() .map(Edge::getTargetNode) .anyMatch(n -> Objects.equals(n, target)); }
Source:
<code>public int getAdjacentNodeCount() { if (sourceNodes == null) { return sinkNodes.size(); } else if (sinkNodes == null) { return sourceNodes.size(); } <START> int size = sourceNodes.size(); <END> size += sinkNodes.stream().filter(notContainedBy(sourceNodes)).count(); return size; }</code><technical_language>sinkNodes.stream().concat(sinkNodes).distinct() is mildly more clear</technical_language>

Target:
public int getAdjacentNodeCount() { if (sourceNodes == null) { return sinkNodes.size(); } else if (sinkNodes == null) { return sourceNodes.size(); } return (int) Stream.concat(sourceNodes.stream(), sinkNodes.stream()).distinct() .count(); }
Source:
<code>public static List<Phonenumber> extractTelecoms(PRPAMT201306UV02ParameterList params) { LOG.trace("Entering HL7DbParser201305.ExtractTelecoms method..."); List<Phonenumber> phonenumbers = new ArrayList<>(); Phonenumber phonenumber; if (CollectionUtils.isNotEmpty(params.getPatientTelecom()) && params.getPatientTelecom().get(0) != null) { for (PRPAMT201306UV02PatientTelecom patientTelecom : params.getPatientTelecom()) { String telecom = hl7ParserUtils.extractTelecom(patientTelecom); <START> if (telecom != null) { <END> phonenumber = new Phonenumber(); phonenumber.setValue(telecom); phonenumbers.add(phonenumber); } } } else { LOG.info("message does not contain a patientTelecom"); } LOG.trace("Exiting HL7DbParser201305.ExtractTelecoms method..."); return phonenumbers; }</code><technical_language>StringUtils.isNotEmpty check</technical_language>

Target:
public static List<Phonenumber> extractTelecoms(PRPAMT201306UV02ParameterList params) { LOG.trace("Entering HL7DbParser201305.ExtractTelecoms method..."); List<Phonenumber> phonenumbers = new ArrayList<>(); Phonenumber phonenumber; if (CollectionUtils.isNotEmpty(params.getPatientTelecom()) && params.getPatientTelecom().get(0) != null) { for (PRPAMT201306UV02PatientTelecom patientTelecom : params.getPatientTelecom()) { String telecom = hl7ParserUtils.extractTelecom(patientTelecom); if (StringUtils.isNotEmpty(telecom)) { phonenumber = new Phonenumber(); phonenumber.setValue(telecom); phonenumbers.add(phonenumber); } } } else { LOG.info("message does not contain a patientTelecom"); } LOG.trace("Exiting HL7DbParser201305.ExtractTelecoms method..."); return phonenumbers; }
Source:
<code>protected List<String> getKotlinCompilerOptions(boolean isTest) { if (!isKotlin) { return ImmutableList.of(); } ImmutableList.Builder<String> optionBuilder = ImmutableList.builder(); if (getProject().getPlugins().hasPlugin(KotlinManager.KOTLIN_ALLOPEN_MODULE)) { AllOpenKotlinGradleSubplugin subplugin = getAllOpenKotlinGradleSubplugin(); if (subplugin != null && fakeCompile != null) { List<SubpluginOption> options = subplugin.apply(getProject(), fakeCompile, fakeCompile, null, null, null); optionBuilder.add( "-Xplugin=" + KotlinManager.KOTLIN_LIBRARIES_LOCATION + File.separator + KotlinManager.KOTLIN_ALLOPEN_JAR); for (SubpluginOption option : options) { optionBuilder.add("-P"); optionBuilder.add( "plugin:org.jetbrains.kotlin.allopen:" + option.getKey() + "=" + option.getValue()); } } } if (isTest) { <START> optionBuilder.add("-Xfriend-paths=$(location :" + JvmBuckRuleComposer.src(this) + "[output])"); <END> } return optionBuilder.build(); }</code><technical_language>this output '-Xfriend-paths=buck-out/gen/libraries/kotlinlibrary/lib__src_main__output/src_main.jar', for libraries/kotlinlibrary in extra_kotlinc_arguments</technical_language>

Target:
protected List<String> getKotlinCompilerOptions(boolean isTest) { if (!isKotlin) { return ImmutableList.of(); } ImmutableList.Builder<String> optionBuilder = ImmutableList.builder(); if (getProject().getPlugins().hasPlugin(KotlinManager.KOTLIN_ALLOPEN_MODULE)) { AllOpenKotlinGradleSubplugin subplugin = getAllOpenKotlinGradleSubplugin(); if (subplugin != null && fakeCompile != null) { List<SubpluginOption> options = subplugin.apply(getProject(), fakeCompile, fakeCompile, null, null, null); optionBuilder.add( "-Xplugin=" + KotlinManager.KOTLIN_LIBRARIES_LOCATION + File.separator + KotlinManager.KOTLIN_ALLOPEN_JAR); for (SubpluginOption option : options) { optionBuilder.add("-P"); optionBuilder.add("plugin:org.jetbrains.kotlin.allopen:" + option.getKey() + "=" + option.getValue()); } } } if (isTest) { String composedTargetName = JvmBuckRuleComposer.src(this); optionBuilder.add( "-Xfriend-paths=" + Paths.get("buck-out/gen") .resolve(getProject().getRootProject().relativePath(getProject().getProjectDir())) .resolve(String.format("lib__%s__output", composedTargetName)) .resolve(composedTargetName + ".jar") .toString()); } return optionBuilder.build(); }
Source:
<code>private Vector3i findRequiredBuilding(BuildingType buildingType, TaskComponent oreonTaskComponent, HoldingComponent oreonHolding) { List<EntityRef> buildings = oreonHolding.constructedBuildings; for (EntityRef building : buildings) { ConstructedBuildingComponent constructedBuildingComponent = building.getComponent(ConstructedBuildingComponent.class); if (constructedBuildingComponent.buildingType.equals(buildingType)) { <START> oreonTaskComponent.taskRegion = constructedBuildingComponent.boundingRegions.get(86); <END> oreonTaskComponent.buildingToVisit = building; return constructedBuildingComponent.boundingRegions.get(86).min(); } } logger.info("Could not find required building"); return null; }</code><technical_language>86 magic number..</technical_language>

Target:
private Vector3i findRequiredBuilding(BuildingType buildingType, TaskComponent oreonTaskComponent, HoldingComponent oreonHolding) { List<EntityRef> buildings = oreonHolding.constructedBuildings; for (EntityRef building : buildings) { ConstructedBuildingComponent constructedBuildingComponent = building.getComponent(ConstructedBuildingComponent.class); if (constructedBuildingComponent.buildingType.equals(buildingType)) { oreonTaskComponent.taskRegion = constructedBuildingComponent.boundingRegions.get(Constants.DINER_CHAIR_REGION_INDEX); oreonTaskComponent.buildingToVisit = building; return constructedBuildingComponent.boundingRegions.get(Constants.DINER_CHAIR_REGION_INDEX).min(); } } logger.info("Could not find required building"); return null; }
Source:
<code>public Optional getTrackableSession(final J2EContext context) { <START> return Optional.of(getHttpSession(context)); <END> }</code><technical_language>ofNulllable I suppose</technical_language>

Target:
public Optional getTrackableSession(final J2EContext context) { return Optional.ofNullable(getHttpSession(context)); }
Source:
<code>public void processCancellationBarrier(CancelCheckpointMarker cancelBarrier) throws IOException { final long cancelledId = cancelBarrier.getCheckpointId(); <START> if (cancelledId >= currentCheckpointId && (cancelledId > currentCheckpointId || numBarriersReceived > 0)) { <END> abortInternal(cancelledId, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED_ON_CANCELLATION_BARRIER)); } }</code><technical_language>correct easier do cancelledId > currentCheckpointId || (currentCheckpointId == cancelledId && numBarriersReceived > 0) a future checkpoint, current checkpoint canceled</technical_language>

Target:
public void processCancellationBarrier(CancelCheckpointMarker cancelBarrier) throws IOException { final long cancelledId = cancelBarrier.getCheckpointId(); if (cancelledId > currentCheckpointId || (cancelledId == currentCheckpointId && numBarriersReceived > 0)) { abortInternal(cancelledId, new CheckpointException(CheckpointFailureReason.CHECKPOINT_DECLINED_ON_CANCELLATION_BARRIER)); } }
Source:
<code>public void leaseExpired() { <START> if (listener != null) { <END> listener.notifyDisconnected(); } }</code><technical_language>a race if calls setDisconnectListener(null). Do want allow unsetting null? If not, prevent it</technical_language>

Target:
public void leaseExpired() { disconnectLock.lock(); try { this.listeners.forEach(DisconnectedEventListener::notifyDisconnected); } finally { disconnectLock.unlock(); } }
Source:
<code>public void bindInputs(ChannelBindingService channelBindingService) { if (log.isDebugEnabled()) { log.debug(String.format("Binding inputs for %s:%s", this.channelNamespace, this.type)); } <START> for (Map.Entry<String, ChannelHolder> channelHolderEntry : this.channelFactory.getInputs().entrySet()) { <END> String inputChannelName = channelHolderEntry.getKey(); ChannelHolder channelHolder = channelHolderEntry.getValue(); if (channelHolder.isBindable()) { if (log.isDebugEnabled()) { log.debug(String.format("Binding %s:%s:%s", this.channelNamespace, this.type, inputChannelName)); } channelBindingService.bindConsumer(channelHolder.getMessageChannel(), inputChannelName); } } }</code><technical_language>I need move channels managed a Bindable move ChannelFactory, if do, binding happen elsewhere. This effectively results in binding/unbinding channels multiple times if @EnableBindings(Source.class,Sink.class). suggestion is channels of a proxy instance proxy (as is more intuitive for source.output() ) basically revert move</technical_language>

Target:
public void bindInputs(ChannelBindingService channelBindingService) { if (log.isDebugEnabled()) { log.debug(String.format("Binding inputs for %s:%s", this.channelNamespace, this.type)); } for (Map.Entry<String, ChannelHolder> channelHolderEntry : this.inputs.entrySet()) { String inputChannelName = channelHolderEntry.getKey(); ChannelHolder channelHolder = channelHolderEntry.getValue(); if (channelHolder.isBindable()) { if (log.isDebugEnabled()) { log.debug(String.format("Binding %s:%s:%s", this.channelNamespace, this.type, inputChannelName)); } channelBindingService.bindConsumer(channelHolder.getMessageChannel(), inputChannelName); } } }
Source:
<code><START> void resetButtons() { <END> for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) arrayOfButtons[i][j].setGraphic(new ImageView(imageEmpty)); field.resetLogic(); }</code><technical_language>4. private static int</technical_language>

Target:
void resetButtons() { for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) arrayOfButtons[i][j].setGraphic(new ImageView(imageEmpty)); field.resetLogic(); }
Source:
<code>public String sendEventsToEs(){ <START> OnmsRestEventsClient onmsRestEventsClient = new OnmsRestEventsClient(); <END> onmsRestEventsClient.setOnmsUrl(onmsUrl); onmsRestEventsClient.setOnmsPassWord(onmsPassWord); onmsRestEventsClient.setOnmsUserName(onmsUserName); Event firstEvent=null; Event lastEvent=null; boolean endofEvents=false; int eventsSent=0; int eventOffset=offset; while (!endofEvents && eventsSent<=limit){ List<Event> events = onmsRestEventsClient.getEvents(EVENT_RETREIVAL_LIMIT, eventOffset); endofEvents = events.isEmpty(); for(Event event:events){ if(firstEvent==null) firstEvent=event; lastEvent=event; eventsSent++; if (! useNodeLabel){ List<Parm> parmCollection = event.getParmCollection(); ListIterator<Parm> iter = parmCollection.listIterator(); while(iter.hasNext()){ if(XmlOnmsEvent.NODE_LABEL.equals(iter.next().getParmName())){ iter.remove(); } } } LOG.debug("sending event to es: eventid="+event.getDbid()); getEventForwarder().sendNow(event); } eventOffset=eventOffset+EVENT_RETREIVAL_LIMIT; } return "Sent "+eventsSent + " events to Elastic Search. First event id="+firstEvent.getDbid()+ " last event id="+lastEvent.getDbid(); }</code><technical_language>Event DAO instead of reaching in REST</technical_language>

Target:
public String sendEventsToEs(){ OnmsRestEventsClient onmsRestEventsClient = new OnmsRestEventsClient(); onmsRestEventsClient.setOnmsUrl(onmsUrl); onmsRestEventsClient.setOnmsPassWord(onmsPassWord); onmsRestEventsClient.setOnmsUserName(onmsUserName); Event firstEvent=null; Event lastEvent=null; boolean endofEvents=false; int eventsSent=0; int eventOffset=offset; while (!endofEvents && eventsSent<=limit){ List<Event> events = onmsRestEventsClient.getEvents(EVENT_RETREIVAL_LIMIT, eventOffset); endofEvents = events.isEmpty(); for(Event event:events){ if(firstEvent==null) firstEvent=event; lastEvent=event; eventsSent++; if (! useNodeLabel){ List<Parm> parmCollection = event.getParmCollection(); ListIterator<Parm> iter = parmCollection.listIterator(); while(iter.hasNext()){ if(OnmsRestEventsClient.NODE_LABEL.equals(iter.next().getParmName())){ iter.remove(); } } } LOG.debug("sending event to es: eventid="+event.getDbid()); getEventForwarder().sendNow(event); } eventOffset=eventOffset+EVENT_RETREIVAL_LIMIT; } return "Sent "+eventsSent + " events to Elastic Search. First event " + "id="+((firstEvent!=null) ? firstEvent.getDbid() : "firstEvent null") + " last event id="+((lastEvent!=null) ? lastEvent.getDbid() : "lastEvent null"); }
Source:
<code>public void upload(InputStream input, OutputStream output, @Nullable OutputStream messages) throws IOException { try { uploadWithExceptionPropagation(input, output, messages); } catch (ServiceMayNotContinueException err) { if (!err.isOutput() && err.getMessage() != null) { try { errOut.writeError(err.getMessage()); } catch (IOException e) { err.addSuppressed(e); throw err; } err.setOutput(); } throw err; } catch (IOException | RuntimeException | Error err) { if (rawOut != null) { String msg = err instanceof PackProtocolException ? err.getMessage() : JGitText.get().internalServerError; try { errOut.writeError(msg); } catch (IOException e) { err.addSuppressed(e); throw err; } throw new UploadPackInternalServerErrorException(err); } throw err; <START> } finally { <END> msgOut = NullOutputStream.INSTANCE; walk.close(); if (timer != null) { try { timer.terminate(); } finally { timer = null; } } } }</code><technical_language>finally block in uploadWithExceptionPropagation() handle this</technical_language>

Target:
public void upload(InputStream input, OutputStream output, @Nullable OutputStream messages) throws IOException { try { uploadWithExceptionPropagation(input, output, messages); } catch (ServiceMayNotContinueException err) { if (!err.isOutput() && err.getMessage() != null) { try { errOut.writeError(err.getMessage()); } catch (IOException e) { err.addSuppressed(e); throw err; } err.setOutput(); } throw err; } catch (IOException | RuntimeException | Error err) { if (rawOut != null) { String msg = err instanceof PackProtocolException ? err.getMessage() : JGitText.get().internalServerError; try { errOut.writeError(msg); } catch (IOException e) { err.addSuppressed(e); throw err; } throw new UploadPackInternalServerErrorException(err); } throw err; } }
Source:
<code><START> private boolean isApp(File file) { <END> if (file.getAbsolutePath().contains(".apk")) { String ext = file.getName(); return ext.endsWith(".apk"); } return false; }</code><technical_language>this simplified check if absolute path ends .apk</technical_language>

Target:
private boolean isApp(File file) { if (file != null) { return file.getAbsolutePath().endsWith(".apk"); } return false; }
Source:
<code>public void onClick(View v) { switch (v.getId()) { case R.id.google_sign_in_button: connectionProgressDialog.show(); saveServerURL(); <START> Toast.makeText(this, getString(R.string.logging_into_server, ZulipApp.get().getServerURI()), Toast.LENGTH_SHORT).show(); <END> setupGoogleSignIn(); break; case R.id.zulip_login: if (!isInputValid(true)) return; saveServerURL(); Toast.makeText(this, getString(R.string.logging_into_server, ZulipApp.get().getServerURI()), Toast.LENGTH_SHORT).show(); connectionProgressDialog.show(); AsyncLogin alog = new AsyncLogin(LoginActivity.this, mUserName.getText().toString(), mPassword.getText().toString(), false); alog.setCallback(new AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result, JSONObject object) { connectionProgressDialog.dismiss(); } @Override public void onTaskFailure(String result) { connectionProgressDialog.dismiss(); } }); alog.execute(); break; case R.id.legal_button: openLegal(); break; case R.id.local_server_button: if (!isInputValid(false)) return; saveServerURL(); AsyncDevGetEmails asyncDevGetEmails = new AsyncDevGetEmails(LoginActivity.this); asyncDevGetEmails.execute(); default: break; } }</code><technical_language>this message is for sign ins servers other Zulip. here, show for G+ logins, is incorrect. (right log in G+ for a server other Zulip.com)</technical_language>

Target:
public void onClick(View v) { switch (v.getId()) { case R.id.google_sign_in_button: connectionProgressDialog.show(); saveServerURL(); Toast.makeText(this, getString(R.string.logging_into_server, ZulipApp.get().getServerURI()), Toast.LENGTH_SHORT).show(); setupGoogleSignIn(); break; case R.id.zulip_login: if (!isInputValid()) return; saveServerURL(); Toast.makeText(this, getString(R.string.logging_into_server, ZulipApp.get().getServerURI()), Toast.LENGTH_SHORT).show(); connectionProgressDialog.show(); AsyncLogin alog = new AsyncLogin(LoginActivity.this, mUserName.getText().toString(), mPassword.getText().toString(), false); alog.setCallback(new AsyncTaskCompleteListener() { @Override public void onTaskComplete(String result, JSONObject object) { connectionProgressDialog.dismiss(); } @Override public void onTaskFailure(String result) { connectionProgressDialog.dismiss(); } }); alog.execute(); break; case R.id.legal_button: openLegal(); break; case R.id.local_server_button: if (!isInputValidForDevAuth()) return; saveServerURL(); AsyncDevGetEmails asyncDevGetEmails = new AsyncDevGetEmails(LoginActivity.this); asyncDevGetEmails.execute(); default: break; } }
Source:
<code>public void onReceive(Context context, Intent intent) { if (intent != null) { if (IDP_LOGIN_REQUEST_ACTION.equals(intent.getAction())) { final Bundle extras = intent.getExtras(); if (extras != null) { userHint = extras.getString(USER_HINT_KEY); spActivityName = extras.getString(SP_ACTVITY_NAME_KEY); } if (!doesUserExist()) { launchLoginActivity(); } else { UserAccountManager.getInstance().switchToUser(getUserForHint()); if (!TextUtils.isEmpty(spActivityName)) { try { final Intent launchIntent = new Intent(SalesforceSDKManager.getInstance().getAppContext(), <START> Class.forName(spActivityName)); <END> launchIntent.addCategory(Intent.CATEGORY_DEFAULT); SalesforceSDKManager.getInstance().getAppContext().startActivity(launchIntent); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Could not start activity", e); } } } } } }</code><technical_language>able pass a bundle extra</technical_language>

Target:
public void onReceive(Context context, Intent intent) { if (intent != null) { if (IDP_LOGIN_REQUEST_ACTION.equals(intent.getAction())) { final Bundle extras = intent.getExtras(); if (extras != null) { userHint = extras.getString(USER_HINT_KEY); spActivityName = extras.getString(SP_ACTVITY_NAME_KEY); spActivityExtras = extras.getBundle(SP_ACTVITY_EXTRAS_KEY); } if (!doesUserExist()) { launchLoginActivity(); } else { UserAccountManager.getInstance().switchToUser(getUserForHint()); if (!TextUtils.isEmpty(spActivityName)) { try { final Intent launchIntent = new Intent(SalesforceSDKManager.getInstance().getAppContext(), Class.forName(spActivityName)); launchIntent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra(SP_ACTVITY_EXTRAS_KEY, spActivityExtras); SalesforceSDKManager.getInstance().getAppContext().startActivity(launchIntent); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Could not start activity", e); } } } } } }
Source:
<code>private static Map<String, Object> createEvent(final String identifier, final String eventTypes) { final Map<String, Object> headers = new HashMap<>(); headers.put(FCREPO_URI, identifier); headers.put(FCREPO_DATE_TIME, timestamp); headers.put(FCREPO_AGENT, Arrays.asList(userID, userAgent)); headers.put(FCREPO_EVENT_TYPE, eventTypes); headers.put(FCREPO_BASE_URL, baseUri); headers.put(EVENT_TYPE, "ResourceCreation"); headers.put(IDENTIFIER, "original_file"); headers.put(RESOURCE_TYPE, Binary.getURI()); <START> headers.put("MimeType", "application/octet-stream"); <END> return headers; }</code><technical_language>header constant exists</technical_language>

Target:
private static Map<String, Object> createEvent(final String identifier, final String eventTypes) { final Map<String, Object> headers = new HashMap<>(); headers.put(FCREPO_URI, identifier); headers.put(FCREPO_DATE_TIME, timestamp); headers.put(FCREPO_AGENT, Arrays.asList(userID, userAgent)); headers.put(FCREPO_EVENT_TYPE, eventTypes); headers.put(FCREPO_BASE_URL, baseUri); headers.put(EVENT_TYPE, "ResourceCreation"); headers.put(IDENTIFIER, "original_file"); headers.put(RESOURCE_TYPE, Binary.getURI()); headers.put(CdrBinaryMimeType, "application/octet-stream"); return headers; }
Source:
<code>void updateValue() { if (is24HourView) { LocalTimeStringConverter localTimeStringConverter = new LocalTimeStringConverter(FormatStyle.SHORT, Locale.GERMAN); timePicker.setValue(localTimeStringConverter.fromString(selectedHourLabel.getText() + ":" + selectedMinLabel.getText())); } else { <START> String input = selectedHourLabel.getText() + ":" + selectedMinLabel.getText() + " " + period.get(); <END> timePicker.setValue(LocalTime.parse(input, DateTimeFormatter.ofPattern("h:mm a").withLocale(Locale.ENGLISH))); } }</code><technical_language>Do need declare new variable, if in place</technical_language>

Target:
void updateValue() { if (is24HourView) { LocalTimeStringConverter localTimeStringConverter = new LocalTimeStringConverter(FormatStyle.SHORT, Locale.GERMAN); timePicker.setValue(localTimeStringConverter.fromString(selectedHourLabel.getText() + ":" + selectedMinLabel.getText())); } else { timePicker.setValue(LocalTime.parse(selectedHourLabel.getText() + ":" + selectedMinLabel.getText() + " " + period.get(), DateTimeFormatter.ofPattern("h:mm a").withLocale(Locale.ENGLISH))); } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getIntent().getExtras().getString("selection_name")); setContentView(R.layout.player_skin_simple_layout); EMBED = getIntent().getExtras().getString("embed_code"); OoyalaSkinLayout skinLayout = (OoyalaSkinLayout)findViewById(R.id.ooyalaSkin); PlayerDomain domain = new PlayerDomain(DOMAIN); Options options = new Options.Builder().setShowPromoImage(false).setShowNativeLearnMoreButton(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(PCODE, domain, options); JSONObject overrides = createSkinOverrides(); SkinOptions skinOptions = new SkinOptions.Builder().setSkinOverrides(overrides).build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); player.addObserver(this); File folder = new File(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_MOVIES), EMBED); <START> OfflineVideo ov = OfflineVideo.getVideo(getApplicationContext(), folder); <END> if (player.setUnbundledVideo(ov)) { } else { Log.e(TAG, "Asset Failure"); } }</code><technical_language>ActivityContext instead of ApplicationContext</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getIntent().getExtras().getString("selection_name")); setContentView(R.layout.player_skin_simple_layout); EMBED = getIntent().getExtras().getString("embed_code"); OoyalaSkinLayout skinLayout = (OoyalaSkinLayout)findViewById(R.id.ooyalaSkin); PlayerDomain domain = new PlayerDomain(DOMAIN); Options options = new Options.Builder().setShowPromoImage(false).setShowNativeLearnMoreButton(false).setUseExoPlayer(true).build(); player = new OoyalaPlayer(PCODE, domain, options); JSONObject overrides = createSkinOverrides(); SkinOptions skinOptions = new SkinOptions.Builder().setSkinOverrides(overrides).build(); playerLayoutController = new OoyalaSkinLayoutController(getApplication(), skinLayout, player, skinOptions); player.addObserver(this); File folder = new File(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_MOVIES), EMBED); OfflineVideo ov = OfflineVideo.getVideo(this, folder); if (player.setUnbundledVideo(ov)) { } else { Log.e(TAG, "Asset Failure"); } }
Source:
<code>public Node getNode( Location location ) { if (location != null) { String pathString = factories.getStringFactory().create(location.getPath()); try { <START> return session.getNode(pathString, false); <END> } catch (PathNotFoundException pnfe) { LOGGER.debug("'{0}' not found - it must have been deleted from storage but not yet from the indexes", pathString); } catch (AccessDeniedException ade) { LOGGER.debug("READ access denied on '{0}'", pathString); } catch (RepositoryException re) { LOGGER.error(re, JcrI18n.cannotLoadNodeFromQueryResult, pathString); } } return null; }</code><technical_language>implement this find path (which requires traversing ancestors) ask for Node path (which requires traversing path)? This results in N 2N node accesses (depending quickly ACL prevent read permission), N is depth of path. for nodes read, requires 2N node accesses. easier Node identifier? I understand checking ACLs requires ancestors, stopping soon ACL prevents read. this result in 1 N+1 node accesses; for nodes read, require N+1 operations (rather 2N in current impl). thought, getNodeByIdentifier check ACLs? I it, buried in of methods</technical_language>

Target:
public Node getNode( Location location ) { if (location != null) { Path path = location.getPath(); try { session.checkPermission(path, ModeShapePermissions.READ); return session.node(location.getKey(), null); } catch (ItemNotFoundException infe) { LOGGER.debug("'{0}' not found - it must have been deleted from storage but not yet from the indexes", path); } catch (AccessDeniedException ade) { LOGGER.debug("READ access denied on '{0}'", path); } } return null; }
Source:
<code>private boolean attachVolume(String volumeId) { String mountPoint = this.targetProperties.get(Ec2Constants.VOLUME_MOUNTPOINT); if(Utils.isEmptyOrWhitespaces(mountPoint)) mountPoint = "/dev/sdf"; AttachVolumeRequest attachRequest = new AttachVolumeRequest() .withInstanceId(this.machineId) .withDevice(mountPoint) .withVolumeId(volumeId); try { this.ec2Api.attachVolume(attachRequest); } catch(Exception e) { <START> logger.info("EBS Volume attachment error: " + e); <END> } if(Boolean.parseBoolean(this.targetProperties.get(Ec2Constants.VOLUME_VOLATILE))) { EbsInstanceBlockDeviceSpecification ebsSpecification = new EbsInstanceBlockDeviceSpecification() .withVolumeId(volumeId) .withDeleteOnTermination(true); InstanceBlockDeviceMappingSpecification mappingSpecification = new InstanceBlockDeviceMappingSpecification() .withDeviceName(mountPoint) .withEbs(ebsSpecification); ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest() .withInstanceId(this.machineId) .withBlockDeviceMappings(mappingSpecification); this.ec2Api.modifyInstanceAttribute(request); } return true; }</code><technical_language>Non-critical errors logged **warning** level</technical_language>

Target:
private boolean attachVolume(String volumeId) { String name = this.targetProperties.get(Ec2Constants.VOLUME_SNAPSHOT_ID); if(Utils.isEmptyOrWhitespaces(name)) name = "Created by Roboconf for " + this.tagName; tagResource(volumeId, name); String mountPoint = this.targetProperties.get(Ec2Constants.VOLUME_MOUNTPOINT); if(Utils.isEmptyOrWhitespaces(mountPoint)) mountPoint = "/dev/sdf"; AttachVolumeRequest attachRequest = new AttachVolumeRequest() .withInstanceId(this.machineId) .withDevice(mountPoint) .withVolumeId(volumeId); try { this.ec2Api.attachVolume(attachRequest); } catch(Exception e) { logger.warning("EBS Volume attachment error: " + e); } if(Boolean.parseBoolean(this.targetProperties.get(Ec2Constants.VOLUME_VOLATILE))) { EbsInstanceBlockDeviceSpecification ebsSpecification = new EbsInstanceBlockDeviceSpecification() .withVolumeId(volumeId) .withDeleteOnTermination(true); InstanceBlockDeviceMappingSpecification mappingSpecification = new InstanceBlockDeviceMappingSpecification() .withDeviceName(mountPoint) .withEbs(ebsSpecification); ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest() .withInstanceId(this.machineId) .withBlockDeviceMappings(mappingSpecification); this.ec2Api.modifyInstanceAttribute(request); } return true; }
Source:
<code>protected final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { <START> String tokenString = req.getParameter("_token").replace(' ', '+'); <END> ParsedToken token; try { token = verifier.decode(tokenString); } catch (InvalidTokenException err) { handleError(err, req, res); return; } CurrentUser user = currentUser.get(); if (user instanceof IdentifiedUser) { Account.Id userId = ((IdentifiedUser) user).getAccountId(); if (!token.getUser().equals(userId) || !token.getUrl().equals(getReqUrl(req))) { handleError(new InvalidTokenException(), req, res); return; } doRequest(req, res); } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } }</code><technical_language>This is ugly, notes in token code</technical_language>

Target:
protected final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { if (!acceptsJson(req)) { handleError(new InvalidTokenException(), req, res); return; } JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(req.getReader()); String tokenString = json.get("token").getAsString(); ParsedToken token; try { token = verifier.decode(tokenString); } catch (InvalidTokenException err) { handleError(err, req, res); return; } CurrentUser user = currentUser.get(); if (user instanceof IdentifiedUser) { Account.Id userId = ((IdentifiedUser) user).getAccountId(); if (!token.getAccountId().equals(userId) || !token.getUrl().equals(getReqUrl(req))) { handleError(new InvalidTokenException(), req, res); return; } doRequest(req, res); } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } }
Source:
<code>@Override public Properties build(Cluster cluster, Path buildPath) throws FalconException { WORKFLOWAPP workflow = new WORKFLOWAPP(); String wfName = EntityUtil.getWorkflowName(Tag.RETENTION, entity).toString(); ACTION eviction = unmarshalAction(EVICTION_ACTION_TEMPLATE); <START> if (!isPostProcessingEnabled()){ <END> addTransition(eviction, OK_ACTION_NAME, FAIL_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(eviction); }else{ addTransition(eviction, SUCCESS_POSTPROCESS_ACTION_NAME, FAIL_POSTPROCESS_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(eviction); ACTION success = getSuccessPostProcessAction(); addTransition(success, OK_ACTION_NAME, FAIL_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(success); ACTION fail = getFailPostProcessAction(); addTransition(fail, FAIL_ACTION_NAME, FAIL_ACTION_NAME); workflow.getDecisionOrForkOrJoin().add(fail); } decorateWorkflow(workflow, wfName, EVICTION_ACTION_NAME); addLibExtensionsToWorkflow(cluster, workflow, Tag.RETENTION); Properties props = getProperties(buildPath, wfName); props.putAll(getWorkflowProperties(cluster)); props.putAll(createDefaultConfiguration(cluster)); props.putAll(FeedHelper.getUserWorkflowProperties(getLifecycle())); if (EntityUtil.isTableStorageType(cluster, entity)) { setupHiveCredentials(cluster, buildPath, workflow); props.putAll(HiveUtil.getHiveCredentials(cluster)); } marshal(cluster, workflow, buildPath); marshal(cluster, workflow, getConfig(props), buildPath); return props; }</code><technical_language>Re-iterate. Is move this piece of code a parent class repeat sub-classes</technical_language>

Target:
@Override public Properties build(Cluster cluster, Path buildPath) throws FalconException { WORKFLOWAPP workflow = new WORKFLOWAPP(); String wfName = EntityUtil.getWorkflowName(Tag.RETENTION, entity).toString(); ACTION eviction = unmarshalAction(EVICTION_ACTION_TEMPLATE); addPostProcessing(workflow, eviction); decorateWorkflow(workflow, wfName, EVICTION_ACTION_NAME); addLibExtensionsToWorkflow(cluster, workflow, Tag.RETENTION); Properties props = getProperties(buildPath, wfName); props.putAll(getWorkflowProperties(cluster)); props.putAll(createDefaultConfiguration(cluster)); props.putAll(FeedHelper.getUserWorkflowProperties(getLifecycle())); if (EntityUtil.isTableStorageType(cluster, entity)) { setupHiveCredentials(cluster, buildPath, workflow); props.putAll(HiveUtil.getHiveCredentials(cluster)); } marshal(cluster, workflow, buildPath); marshal(cluster, workflow, getConfig(props), buildPath); return props; }
Source:
<code>private TimeoutException newTimeoutException(Object key, CacheTransaction tx, TxInvocationContext txContext) { String txLog = "(no transaction)"; if( tx != null ) txLog = tx.toString(); return new TimeoutException("Could not acquire lock on " + key + " on behalf of transaction " + <START> txContext.getGlobalTransaction() + ". Waiting to complete tx: " + txLog + ". Lock is being held by " + lockManager.getOwner(key)); <END> }</code><technical_language>I prefer messages for case, instead of listing in message. all, if a tx owns a real lock, waiting for tx complete. message txLog = "(backup) " + tx.toString()</technical_language>

Target:
private TimeoutException newTimeoutException(Object key, CacheTransaction tx, TxInvocationContext txContext) { return new TimeoutException("Could not acquire lock on " + key + " on behalf of transaction " + txContext.getGlobalTransaction() + ". Waiting to complete tx: " + tx + "."); }
Source:
<code>public Map<PageTitle, T> processResult(ApiResult result) throws Throwable { Map<PageTitle, T> map = new HashMap<>(); JSONObject data = result.asObject(); <START> JSONObject query = data.optJSONObject("query"); <END> if (query == null) { return map; } JSONObject pages = query.getJSONObject("pages"); Iterator<String> keys = pages.keys(); while (keys.hasNext()) { String key = keys.next(); int pageId = Integer.parseInt(key); JSONObject pageData = pages.getJSONObject(key); String titleString = pageData.getString("title"); PageTitle pageTitle = new PageTitle(null, titleString, site); T pageResult = processPage(pageId, pageTitle, pageData); map.put(pageTitle, pageResult); } return map; }</code><technical_language>this change mentioned in commit message is this some related gallery changes</technical_language>

Target:
public Map<PageTitle, T> processResult(ApiResult result) throws Throwable { Map<PageTitle, T> map = new HashMap<>(); JSONObject data = result.asObject(); JSONObject query = data.getJSONObject("query"); JSONObject pages = query.getJSONObject("pages"); Iterator<String> keys = pages.keys(); while (keys.hasNext()) { String key = keys.next(); int pageId = Integer.parseInt(key); JSONObject pageData = pages.getJSONObject(key); String titleString = pageData.getString("title"); PageTitle pageTitle = new PageTitle(null, titleString, site); T pageResult = processPage(pageId, pageTitle, pageData); map.put(pageTitle, pageResult); } return map; }
Source:
<code>public void getPermissions_noLongerValidWhenPermissionManagerIsClosed() { final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { <START> RealmLog.error("OnSuccess"); <END> try { assertTrue(permissions.isValid()); pm.close(); assertFalse(permissions.isValid()); } finally { user.logout(); } looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { RealmLog.error("onError"); fail(error.toString()); } }); }</code><technical_language>log level</technical_language>

Target:
public void getPermissions_noLongerValidWhenPermissionManagerIsClosed() { final PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { try { assertTrue(permissions.isValid()); pm.close(); assertFalse(permissions.isValid()); } finally { user.logout(); } looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }