auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected IStatus run(IProgressMonitor monitor) { ConsoleHistoryLinesBuffer.HistorySnapShot history = fHistoryBuffer.getHistorySnapShot(); String[] buffLines = history.fHistoryLinesSnapShot; int start = 0; int end = buffLines.length <= HIST_BUFFER_WRITE_SIZE ? buffLines.length : HIST_BUFFER_WRITE_SIZE; StringBuilder sb = new StringBuilder(HIST_BUFFER_WRITE_SIZE); OutputStream terminalOutputStream = fTerminalControl.getRemoteToTerminalOutputStream(); while (start < buffLines.length) { String[] chunk = Arrays.copyOfRange(buffLines, start, end); for (String line : chunk) { sb.append(line); } start = end; int linesLeft = buffLines.length - end; end = start + (linesLeft <= HIST_BUFFER_WRITE_SIZE ? linesLeft : HIST_BUFFER_WRITE_SIZE); if (!(start < buffLines.length)) { sb.append(history.fHistoryRemainderSnapShot); } if (sb.length() > 0) { if (terminalOutputStream != null) { synchronized (terminalOutputStream) { try { terminalOutputStream.write(sb.toString().getBytes(), 0, sb.toString().getBytes().length); } catch (IOException e) { } } } sb.setLength(0); } } return Status.OK_STATUS; }

Target:
protected IStatus run(IProgressMonitor monitor) { OutputStream terminalOutputStream = fTerminalControl.getRemoteToTerminalOutputStream(); if (terminalOutputStream == null) { return Status.OK_STATUS; } ConsoleHistoryLinesBuffer.HistorySnapShot history = fHistoryBuffer.getHistorySnapShot(); String[] buffLines = history.fHistoryLinesSnapShot; int start = 0; int end = buffLines.length <= HIST_BUFFER_WRITE_SIZE ? buffLines.length : HIST_BUFFER_WRITE_SIZE; StringBuilder sb = new StringBuilder(HIST_BUFFER_WRITE_SIZE); while (start < buffLines.length) { String[] chunk = Arrays.copyOfRange(buffLines, start, end); for (String line : chunk) { sb.append(line); } start = end; int linesLeft = buffLines.length - end; end = start + (linesLeft <= HIST_BUFFER_WRITE_SIZE ? linesLeft : HIST_BUFFER_WRITE_SIZE); if (!(start < buffLines.length)) { sb.append(history.fHistoryRemainderSnapShot); } if (sb.length() > 0) { byte[] bytes = sb.toString().getBytes(); try { terminalOutputStream.write(bytes, 0, bytes.length); } catch (IOException e) { } sb.setLength(0); } } return Status.OK_STATUS; }
Source:
public static OptimizeTableAnalyzedStatement createStatement(AnalyzedOptimizeTable optimizeTable, CoordinatorTxnCtx txnCtx, Functions functions, Row parameters, SubQueryResults subQueryResults) { Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate( txnCtx, functions, x, parameters, subQueryResults ); var genericProperties = optimizeTable.properties().map(eval); var settings = genericPropertiesToSettings(genericProperties, SUPPORTED_SETTINGS); validateSettings(settings, genericProperties); ArrayList<String> toOptimize = new ArrayList<>(); for (Map.Entry<Table<Symbol>, TableInfo> table : optimizeTable.tables().entrySet()) { var tableInfo = table.getValue(); var tableSymbol = table.getKey(); if (tableInfo instanceof BlobTableInfo) { toOptimize.add(((BlobTableInfo) tableInfo).concreteIndices()[0]); } else { var docTableInfo = (DocTableInfo) tableInfo; if (tableSymbol.partitionProperties().isEmpty()) { toOptimize.addAll(Arrays.asList(docTableInfo.concreteOpenIndices())); } else { var partitionName = toPartitionName( docTableInfo, Lists2.map(tableSymbol.partitionProperties(), x -> x.map(eval))); if (!docTableInfo.partitions().contains(partitionName)) { throw new PartitionUnknownException(partitionName); } toOptimize.add(partitionName.asIndexName()); } } } return new OptimizeTableAnalyzedStatement(toOptimize, settings); }

Target:
public static BoundedOptimizeTable createStatement(AnalyzedOptimizeTable optimizeTable, CoordinatorTxnCtx txnCtx, Functions functions, Row parameters, SubQueryResults subQueryResults) { Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate( txnCtx, functions, x, parameters, subQueryResults ); var genericProperties = optimizeTable.properties().map(eval); var settings = genericPropertiesToSettings(genericProperties, SUPPORTED_SETTINGS); validateSettings(settings, genericProperties); ArrayList<String> toOptimize = new ArrayList<>(); for (Map.Entry<Table<Symbol>, TableInfo> table : optimizeTable.tables().entrySet()) { var tableInfo = table.getValue(); var tableSymbol = table.getKey(); if (tableInfo instanceof BlobTableInfo) { toOptimize.add(((BlobTableInfo) tableInfo).concreteIndices()[0]); } else { var docTableInfo = (DocTableInfo) tableInfo; if (tableSymbol.partitionProperties().isEmpty()) { toOptimize.addAll(Arrays.asList(docTableInfo.concreteOpenIndices())); } else { var partitionName = toPartitionName( docTableInfo, Lists2.map(tableSymbol.partitionProperties(), x -> x.map(eval))); if (!docTableInfo.partitions().contains(partitionName)) { throw new PartitionUnknownException(partitionName); } toOptimize.add(partitionName.asIndexName()); } } } return new BoundedOptimizeTable(toOptimize, settings); }
Source:
private void fetchNodesLimit() { this.rm.getState(LoginModel.getInstance().getSessionId(), new AsyncCallback<String>() { public void onSuccess(String result) { JSONObject rmState = JSONParser.parseStrict(result).isObject(); JSONValue maxNumberOfNodes = rmState.get("maxNumberOfNodes"); if (maxNumberOfNodes != null && maxNumberOfNodes.isNumber() != null) { model.setMaxNumberOfNodes(Long.parseLong(maxNumberOfNodes.isNumber().toString())); } } public void onFailure(Throwable caught) { LogModel.getInstance().logMessage("Failed to access node limit through rmState: " + caught.getMessage()); } }); }

Target:
private void fetchNodesLimit() { this.rm.getState(LoginModel.getInstance().getSessionId(), new AsyncCallback<String>() { public void onSuccess(String result) { JSONObject rmState = JSONParser.parseStrict(result).isObject(); if (rmState == null) { LogModel.getInstance().logMessage("Failed to parse json rmState: " + result); } else { JSONValue maxNumberOfNodes = rmState.get("maxNumberOfNodes"); if (maxNumberOfNodes != null && maxNumberOfNodes.isNumber() != null) { model.setMaxNumberOfNodes(Long.parseLong(maxNumberOfNodes.isNumber().toString())); } } } public void onFailure(Throwable caught) { LogModel.getInstance().logMessage("Failed to access node limit through rmState: " + caught.getMessage()); } }); }
Source:
public void setExternalCard(ExternalCard externalCard) { this.externalCard = externalCard; }

Target:
public Builder setExternalCard(ExternalCard externalCard) { this.externalCard = externalCard; return this; }
Source:
public void updateErrataDetailFormPanel(Erratum erratum) { logger.info("updateErrataDetailFormPanel for " + erratum); buildErrataDetailPanel(); errataTitle.setText(erratum.getTitle()); FormBuilder formBuilder = new FormBuilder(errataDetailFormPanel, 1, 10); formBuilder.setRelativeColumnWidth(0, 3); formBuilder.addFormItem(new FormItem(constants.errataId(), new Span(erratum.getId()), 0, 0)); formBuilder.addFormItem(new FormItem(constants.errataDateIssued(), new Span(erratum.getIssued().toString()), 1, 0)); formBuilder.addFormItem(new FormItem(constants.errataType(), new Span(erratum.getType().toString()), 2, 0)); if (erratum.getSeverity() != null) { formBuilder.addFormItem(new FormItem(constants.errataSeverity(), new Span(erratum.getSeverity().toString()), 3, 0)); } formBuilder.addFormItem(new FormItem(constants.description(), new Span(erratum.getDescription().toString()), 4, 0)); formBuilder.addFormItem(new FormItem(constants.solution(), new Span(erratum.getSolution()), 5, 0)); formBuilder.addFormItem(new FormItem(constants.summary(), new Span(erratum.getSummary()), 6, 0)); formBuilder.addFormItem(new FormItem(constants.errataPackages(), new Span(StringUtils.join(erratum.getPackages(), ", ")), 7, 0)); }

Target:
public void updateErrataDetailFormPanel(Erratum erratum) { buildErrataDetailPanel(); errataTitle.setText(erratum.getTitle()); FormBuilder formBuilder = new FormBuilder(errataDetailFormPanel, 1, 10); formBuilder.setRelativeColumnWidth(0, 3); formBuilder.addFormItem(new FormItem(constants.errataId(), new Span(erratum.getId()), 0, 0)); formBuilder.addFormItem(new FormItem(constants.errataDateIssued(), new Span(erratum.getIssued().toString()), 1, 0)); formBuilder.addFormItem(new FormItem(constants.errataType(), new Span(erratum.getType().toString()), 2, 0)); if (erratum.getSeverity() != null) { formBuilder.addFormItem(new FormItem(constants.errataSeverity(), new Span(erratum.getSeverity().toString()), 3, 0)); } formBuilder.addFormItem(new FormItem(constants.description(), new Span(erratum.getDescription().toString()), 4, 0)); formBuilder.addFormItem(new FormItem(constants.solution(), new Span(erratum.getSolution()), 5, 0)); formBuilder.addFormItem(new FormItem(constants.summary(), new Span(erratum.getSummary()), 6, 0)); formBuilder.addFormItem(new FormItem(constants.errataPackages(), new Span(StringUtils.join(erratum.getPackages(), ", ")), 7, 0)); }
Source:
private static Collection<TmfEventTableColumn> convertFromColumnData( org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData[] columnData) { List<TmfEventTableColumn> list = new LinkedList<>(); for (org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData col : columnData) { String header = col.header; if (header != null) { list.add(new TmfEventTableFieldColumn(header)); } } return list; }

Target:
private static Collection<TmfEventTableColumn> convertFromColumnData( org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData[] columnData) { ImmutableList.Builder<TmfEventTableColumn> builder = new ImmutableList.Builder<>(); for (org.eclipse.linuxtools.tmf.ui.widgets.virtualtable.ColumnData col : columnData) { String header = col.header; if (header != null) { builder.add(new TmfEventTableFieldColumn(header)); } } return builder.build(); }
Source:
public boolean isAtLeastAsRecentAs(final VCFHeaderVersion target) { switch (target) { case VCF4_3: return this == VCF4_3; case VCF4_2: return this == VCF4_2 || this == VCF4_3; case VCF4_1: return this == VCF4_1 || this == VCF4_2 || this == VCF4_3; case VCF4_0: return this != VCF3_2 && this != VCF3_3; case VCF3_3: return this != VCF3_2; case VCF3_2: default: return true; } }

Target:
public boolean isAtLeastAsRecentAs(final VCFHeaderVersion target) { return this.ordinal() >= target.ordinal(); }
Source:
T release() { closeable = null; return closeable; }

Target:
void release() { closeable = null; }
Source:
private VaadinService getServiceWithResource(String content) throws ServiceException, IOException { MockDeploymentConfiguration configuration = new MockDeploymentConfiguration(); configuration.setProductionMode(true); VaadinService service = new MockVaadinServletService(configuration); service.init(); VaadinContext context = service.getContext(); Lookup lookup = Mockito.mock(Lookup.class); context.setAttribute(Lookup.class, lookup); ResourceProvider provider = Mockito.mock(ResourceProvider.class); Mockito.when(lookup.lookup(ResourceProvider.class)) .thenReturn(provider); if (content != null) { File tmpFile = tmpDir.newFile(); try (FileOutputStream outputStream = new FileOutputStream( tmpFile)) { IOUtils.write(content, outputStream, StandardCharsets.UTF_8); } Mockito.when(provider.getApplicationResource(service, VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT)) .thenReturn(tmpFile.toURI().toURL()); } return service; }

Target:
private VaadinService getServiceWithResource(String content) throws ServiceException, IOException { MockDeploymentConfiguration configuration = new MockDeploymentConfiguration(); configuration.setProductionMode(true); VaadinService service = new MockVaadinServletService(configuration); VaadinContext context = service.getContext(); Lookup lookup = Mockito.mock(Lookup.class); context.setAttribute(Lookup.class, lookup); ResourceProvider provider = Mockito.mock(ResourceProvider.class); Mockito.when(lookup.lookup(ResourceProvider.class)) .thenReturn(provider); if (content != null) { File tmpFile = tmpDir.newFile(); try (FileOutputStream outputStream = new FileOutputStream( tmpFile)) { IOUtils.write(content, outputStream, StandardCharsets.UTF_8); } Mockito.when(provider.getApplicationResource(service, VAADIN_SERVLET_RESOURCES + STATISTICS_JSON_DEFAULT)) .thenReturn(tmpFile.toURI().toURL()); } return service; }
Source:
protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object result; try { ReflectionUtil.getField( entity.getClass(), Persistence.DEFAULT_OBJECT_ID_FIELD ); result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity } ); } catch( NoSuchFieldException nfe ) { String objectId = FootprintsManager.getInstance().getObjectId( entity ); result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), objectId } ); } FootprintsManager.getInstance().Inner.removeFootprintForObject( BackendlessSerializer.serializeToMap( entity ), entity ); return ((Number) result).longValue(); }

Target:
protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object result; if( ReflectionUtil.hasField( entity.getClass(), Persistence.DEFAULT_OBJECT_ID_FIELD ) ) { result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity } ); } else { String objectId = FootprintsManager.getInstance().getObjectId( entity ); result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), objectId } ); } FootprintsManager.getInstance().Inner.removeFootprintForObject( BackendlessSerializer.serializeToMap( entity ), entity ); return ((Number) result).longValue(); }
Source:
public void testDifferenceExport() { Collection<Mutation> mutations; mutations = new DiffExport(null, "a").toMutations("k1", 1); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k1", "a", 1))); mutations = new DiffExport("b", "b").toMutations("k2", 2); Assert.assertEquals(0, mutations.size()); mutations = new DiffExport("c", "d").toMutations("k3", 3); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k3", "d", 3))); mutations = new DiffExport("e", null).toMutations("k", 4); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makeDel("k", "e"))); }

Target:
public void testDifferenceExport() { Collection<Mutation> mutations; mutations = new DiffExport(Optional.empty(), Optional.of("a")).toMutations("k1", 1); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k1", "a", 1))); mutations = new DiffExport(Optional.of("ab"), Optional.of("ab")).toMutations("k2", 2); Assert.assertEquals(0, mutations.size()); mutations = new DiffExport(Optional.of("b"), Optional.of("ab")).toMutations("k2", 2); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makePut("k2", "a", 2))); mutations = new DiffExport(Optional.of("c"), Optional.of("d")).toMutations("k3", 3); Assert.assertEquals(1, mutations.size()); Mutation m = makeDel("k3", "c", 3); addPut(m, "k3", "d", 3); Assert.assertTrue(mutations.contains(m)); mutations = new DiffExport(Optional.of("e"), Optional.empty()).toMutations("k4", 4); Assert.assertEquals(1, mutations.size()); Assert.assertTrue(mutations.contains(makeDel("k4", "e", 4))); mutations = new DiffExport(Optional.of("ef"), Optional.of("fg")).toMutations("k5", 5); Assert.assertEquals(1, mutations.size()); m = makeDel("k5", "e", 5); addPut(m, "k5", "g", 5); Assert.assertTrue(mutations.contains(m)); }
Source:
protected void checkNewDefaultBrowser(Object browser) { TableItem[] children = tableViewer.getTable().getItems(); for (TableItem element : children) { TableItem item = element; if (!(item.getData().equals(browser))) item.setChecked(false); } }

Target:
protected void checkNewDefaultBrowser(Object browser) { for (TableItem item : tableViewer.getTable().getItems()) { if (!(item.getData().equals(browser))) item.setChecked(false); } }
Source:
private void throwAmbiguousMethodsException(List<ScoreMethodAndExtractPathVars> methods) { WebRequest request = getCurrentWebRequest(); String methodsNames = ""; for (ScoreMethodAndExtractPathVars method : methods) { if (!methodsNames.isEmpty()) methodsNames += ", "; MethodMappingInfo urlMappingInfo = method.getMethodInfo(); methodsNames += urlMappingInfo.getMethod().getReturnType().getSimpleName() + " " + urlMappingInfo.getMethod().getDeclaringClass().getSimpleName() + "." + urlMappingInfo.getMethod().getName(); } throw new WicketRuntimeException("Ambiguous methods mapped for the current request: URL '" + request.getClientUrl() + "', HTTP method " + HttpUtils.getHttpMethod(request) + ". " + "Mapped methods: " + methodsNames); }

Target:
private void throwAmbiguousMethodsException(List<ScoreMethodAndExtractPathVars> methods) { WebRequest request = getCurrentWebRequest(); StringBuilder methodsNames = new StringBuilder(); for (ScoreMethodAndExtractPathVars method : methods) { if (methodsNames.length() != 0) methodsNames.append(", "); MethodMappingInfo urlMappingInfo = method.getMethodInfo(); methodsNames.append(urlMappingInfo.getMethod().getReturnType().getSimpleName()); methodsNames.append(" "); methodsNames.append(urlMappingInfo.getMethod().getDeclaringClass().getSimpleName()); methodsNames.append("."); methodsNames.append(urlMappingInfo.getMethod().getName()); } throw new WicketRuntimeException("Ambiguous methods mapped for the current request: URL '" + request.getClientUrl() + "', HTTP method " + HttpUtils.getHttpMethod(request) + ". " + "Mapped methods: " + methodsNames); }
Source:
public void setBuildDiscarder(BuildDiscarder bd) throws IOException { BulkChange bc = new BulkChange(this); try { removeProperty(BuildDiscarderProperty.class); if (bd != null) { addProperty(new BuildDiscarderProperty(bd)); } bc.commit(); } finally { bc.abort(); } }

Target:
public synchronized void setBuildDiscarder(BuildDiscarder bd) throws IOException { BulkChange bc = new BulkChange(this); try { removeProperty(BuildDiscarderProperty.class); if (bd != null) { addProperty(new BuildDiscarderProperty(bd)); } bc.commit(); } finally { bc.abort(); } }
Source:
public void onUpdateWeatherReturn(CallbackInfo ci) { Weather weather = getWeather(); if (this.prevWeather != weather) { int duration = (int) getRemainingDuration(); ChangeWorldWeatherEvent event = SpongeEventFactory.createChangeWorldWeatherEvent(Sponge.getGame(), Cause.of((World) this), duration, duration, weather, weather, this.prevWeather, this); Sponge.getGame().getEventManager().post(event); if (event.isCancelled()) { this.forecast(this.prevWeather); } else { this.forecast(event.getWeather(), event.getDuration()); this.prevWeather = event.getWeather(); } } }

Target:
public void onUpdateWeatherReturn(CallbackInfo ci) { Weather weather = getWeather(); int duration = (int) getRemainingDuration(); if (this.prevWeather != weather && duration > 0) { ChangeWorldWeatherEvent event = SpongeEventFactory.createChangeWorldWeatherEvent(Cause.of(NamedCause.source(this)), duration, duration, weather, weather, this.prevWeather, this); SpongeImpl.postEvent(event); if (event.isCancelled()) { this.forecast(this.prevWeather); } else { this.forecast(event.getWeather(), event.getDuration()); this.prevWeather = event.getWeather(); this.weatherStartTime = this.worldInfo.getWorldTotalTime(); } } }
Source:
public void setWriteDelays(Integer minWriteDelay, Integer maxWriteDelay) { minWriteDelay = minWriteDelay != null ? minWriteDelay : 0; maxWriteDelay = maxWriteDelay != null ? maxWriteDelay : 1; if (minWriteDelay < 0) { throw new IllegalArgumentException("Minimum write delay seconds cannot be less then 0."); } if (maxWriteDelay < 1) { throw new IllegalArgumentException("Maximum write delay seconds cannot be less then 1."); } if (maxWriteDelay < minWriteDelay) { throw new IllegalArgumentException( format("Maximum write delay (%d seconds) must be equal or greater than minimum write delay (%d seconds)", maxWriteDelay, minWriteDelay)); } this.minWriteDelay = minWriteDelay; this.maxWriteDelay = maxWriteDelay; }

Target:
public void setWriteDelays(Integer minWriteDelay, Integer maxWriteDelay) { minWriteDelay = minWriteDelay != null ? minWriteDelay : 0; maxWriteDelay = maxWriteDelay != null ? maxWriteDelay : 1; if (minWriteDelay < 0) { throw new IllegalArgumentException("Minimum write delay seconds cannot be less than 0."); } if (maxWriteDelay < 1) { throw new IllegalArgumentException("Maximum write delay seconds cannot be less than 1."); } if (maxWriteDelay < minWriteDelay) { throw new IllegalArgumentException( format("Maximum write delay (%d seconds) must be equal or greater than minimum write delay (%d seconds)", maxWriteDelay, minWriteDelay)); } this.minWriteDelay = minWriteDelay; this.maxWriteDelay = maxWriteDelay; }
Source:
public static <K, V> Predicate<EventJournalCacheEvent<K, V>> cachePutEvents() { return new CachePutEventsPredicate<>(); }

Target:
public static <K, V> Predicate<EventJournalCacheEvent<K, V>> cachePutEvents() { return new CachePutEventsPredicate<K, V>(); }
Source:
public TagPropertySource(Repository repo, Ref ref) { this.ref = ref; RevWalk refWalk = new RevWalk(repo); try { RevObject any = refWalk.parseAny(repo.resolve(ref.getName())); if (any instanceof RevTag) { tag = (RevTag) any; } } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } finally { refWalk.close(); } }

Target:
public TagPropertySource(Repository repo, Ref ref) { this.ref = ref; try (RevWalk refWalk = new RevWalk(repo)) { ObjectId objectId = repo.resolve(ref.getName()); RevObject any = refWalk.parseAny(objectId); RevObject peeledObject = refWalk.peel(any); if (any instanceof RevTag) { tag = (RevTag) any; } if (peeledObject instanceof RevCommit) { commit = (RevCommit) peeledObject; } } catch (IOException e) { Activator.handleError(e.getMessage(), e, true); } }
Source:
private PrintWriter getWriter(OutputStream os) { if (os instanceof WrapperOutputStream) { OutputStream out = ((WrapperOutputStream) os).getRecursivelyUnderlyingStream(); if (out instanceof FilteredOutputStream) { FilteredOutputStream filteredStream = (FilteredOutputStream) out; return new PrintWriter(new IgnoreCloseWriter(filteredStream.asWriter())); } } return new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))); }

Target:
private PrintWriter getWriter(OutputStream os) throws IOException { if (os instanceof WrapperOutputStream) { OutputStream out = ((WrapperOutputStream) os).unwrapRecursively(); if (out instanceof FilteredOutputStream) { FilteredOutputStream filteredStream = (FilteredOutputStream) out; return new PrintWriter(new IgnoreCloseWriter(filteredStream.asWriter())); } } return new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))); }
Source:
Task<Void> saveAsync(final String sessionToken, final Task<Void> toAwait) { return super.saveAsync(sessionToken, toAwait).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { if(task.getError() != null && task.getError() instanceof ParseException && ((ParseException) task.getError()).getCode() == ParseException.OBJECT_NOT_FOUND) { synchronized (mutex) { setObjectId(null); markAllFieldsDirty(); return ParseInstallation.super.saveAsync(sessionToken, toAwait); } } return task; } }); }

Target:
Task<Void> saveAsync(final String sessionToken, final Task<Void> toAwait) { return super.saveAsync(sessionToken, toAwait).continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(Task<Void> task) throws Exception { if (task.getError() != null && task.getError() instanceof ParseException) { int errCode = ((ParseException) task.getError()).getCode(); if (errCode == ParseException.OBJECT_NOT_FOUND || (errCode == ParseException.MISSING_REQUIRED_FIELD_ERROR && getObjectId() == null)) { synchronized (mutex) { setState(new State.Builder(getState()).objectId(null).build()); markAllFieldsDirty(); return ParseInstallation.super.saveAsync(sessionToken, toAwait); } } } return task; } }); }
Source:
public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); final MethodReference currentMethod = methodReferences.peek(); if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } }

Target:
public void visitIdentifier(IdentifierTree tree) { super.visitIdentifier(tree); if ("class".equals(tree.name()) || methodReferences.isEmpty()) { return; } Symbol symbol = tree.symbol(); MethodReference currentMethod = methodReferences.peek(); if (symbol.isUnknown()) { currentMethod.setNonStaticReference(); return; } for (MethodReference methodReference : methodReferences) { methodReference.checkSymbol(symbol); } }
Source:
public void run() { Set<UUID> onlineIds = new HashSet<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); }

Target:
public void run() { List<UUID> onlineIds = new ArrayList<>(); for (Player player : Sponge.getServer().getOnlinePlayers()) { onlineIds.add(player.getUniqueId()); } this.onlineIds = new CopyOnWriteArraySet<>(onlineIds); }
Source:
public TmfModelResponse<OutputStyleModel> fetchStyle(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { for (P dataProvider : getProviders()) { if (dataProvider instanceof IOutputStyleProvider) { TmfModelResponse<OutputStyleModel> response = ((IOutputStyleProvider) dataProvider).fetchStyle(fetchParameters, monitor); OutputStyleModel model = response.getModel(); if (model != null) { return response; } } } return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }

Target:
public TmfModelResponse<OutputStyleModel> fetchStyle(Map<String, Object> fetchParameters, @Nullable IProgressMonitor monitor) { Map<String, OutputElementStyle> styles = new HashMap<>(); for (P dataProvider : getProviders()) { if (dataProvider instanceof IOutputStyleProvider) { TmfModelResponse<OutputStyleModel> response = ((IOutputStyleProvider) dataProvider).fetchStyle(fetchParameters, monitor); OutputStyleModel model = response.getModel(); if (model != null) { styles.putAll(model.getStyles()); } } } if (styles.isEmpty()) { return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); } return new TmfModelResponse<>(new OutputStyleModel(styles), ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
private synchronized static DataPublisher initDataPublisher(){ if (publisher == null){ try { loadConfigs(); publisher = new DataPublisher(null,receiverUrl, authUrl, username, password); if (log.isDebugEnabled()) { log.debug("Connected to analytics sever with the following details, " + " ReceiverURL:" + receiverUrl + ", AuthURL:" + authUrl + ", Username:" + username); } } catch (DataEndpointAgentConfigurationException e) { log.error("Error while creating databridge publisher", e); } catch (DataEndpointException e) { log.error("Error while creating databridge publisher", e); } catch (DataEndpointConfigurationException e) { log.error("Error while creating databridge publisher", e); } catch (DataEndpointAuthenticationException e) { log.error("Error while creating databridge publisher", e); } catch (TransportException e) { log.error("Error while creating databridge publisher", e); } } return publisher; }

Target:
private synchronized static void initDataPublisher() { if (publisher == null) { try { loadConfigs(); publisher = new DataPublisher(null, receiverUrl, authUrl, username, password); if (log.isDebugEnabled()) { log.debug("Connected to analytics sever with the following details, " + " ReceiverURL:" + receiverUrl + ", AuthURL:" + authUrl + ", Username:" + username); } } catch (DataEndpointAgentConfigurationException | DataEndpointConfigurationException | DataEndpointException | DataEndpointAuthenticationException | TransportException e) { log.error("Error while creating databridge publisher", e); } } }
Source:
public void process(JSONRequestContext requestContext) { StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO(); PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO(); UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO(); PersonVariableDAO personVariableDAO = DAOFactory.getInstance().getPersonVariableDAO(); Long personId = NumberUtils.createLong(requestContext.getRequest().getParameter("personId")); Person person = personDAO.findById(personId); String personOid = requestContext.getString("personOid"); personVariableDAO.setPersonVariable(person, KoskiConsts.VariableNames.KOSKI_HENKILO_OID, StringUtils.trim(personOid)); Integer personVariableCount = requestContext.getInteger("studentKoskiIDsTable.rowCount"); if (personVariableCount != null) { for (int i = 0; i < personVariableCount; i++) { String colPrefix = "studentKoskiIDsTable." + i; String linkedOid = requestContext.getString(colPrefix + ".linkedOid"); Long studentId = requestContext.getLong(colPrefix + ".studentId"); Student student = studentDAO.findById(studentId); if (person.getId().equals(student.getPerson().getId())) { userVariableDAO.setUserVariable(student, KoskiConsts.VariableNames.KOSKI_LINKED_STUDYPERMISSION_ID, StringUtils.trim(linkedOid)); } } } }

Target:
public void process(JSONRequestContext requestContext) { StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO(); PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO(); UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO(); PersonVariableDAO personVariableDAO = DAOFactory.getInstance().getPersonVariableDAO(); Long personId = requestContext.getLong("personId"); Person person = personDAO.findById(personId); String personOid = requestContext.getString("personOid"); personVariableDAO.setPersonVariable(person, KoskiConsts.VariableNames.KOSKI_HENKILO_OID, StringUtils.trim(personOid)); Integer personVariableCount = requestContext.getInteger("studentKoskiIDsTable.rowCount"); if (personVariableCount != null) { for (int i = 0; i < personVariableCount; i++) { String colPrefix = "studentKoskiIDsTable." + i; String linkedOid = requestContext.getString(colPrefix + ".linkedOid"); Long studentId = requestContext.getLong(colPrefix + ".studentId"); Student student = studentDAO.findById(studentId); if (person.getId().equals(student.getPerson().getId())) { userVariableDAO.setUserVariable(student, KoskiConsts.VariableNames.KOSKI_LINKED_STUDYPERMISSION_ID, StringUtils.trim(linkedOid)); } } } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); }
Source:
public void accept(String json, Context context) { logger.info("Function triggered by event: " + json); }

Target:
public void accept(String json, Context context) { JsonObject body = gsonParser.fromJson(json, JsonObject.class); LOGGER.info("Function triggered by event: " + json); }
Source:
void groupElementWithItsParent(final List<DataTypeListItem> groupedElements, final List<DataTypeListItem> allElements, final DataTypeListItem item) { if (groupedElements.contains(item)) { return; } final String parentElementId = item.getDragAndDropElement().getAttribute(PARENT_UUID_ATTR); if (!StringUtils.isEmpty(parentElementId)) { final Optional<DataTypeListItem> parentElement = allElements.stream() .filter(element -> Objects.equals(element.getDragAndDropElement().getAttribute(UUID_ATTR), parentElementId)) .findFirst(); if (!isParentElementOnList(groupedElements, parentElementId)) { parentElement.ifPresent(p -> groupElementWithItsParent(groupedElements, allElements, p)); groupedElements.add(item); } else { int index = getIndexOfParentOrLastElementInGroup(groupedElements, parentElement.get()); groupedElements.add(index, item); } } else { groupedElements.add(item); } }

Target:
void groupElementWithItsParent(final List<DataTypeListItem> groupedElements, final List<DataTypeListItem> allElements, final DataTypeListItem item) { if (groupedElements.contains(item)) { return; } final String parentElementId = item.getDragAndDropElement().getAttribute(PARENT_UUID_ATTR); if (!StringUtils.isEmpty(parentElementId)) { final Optional<DataTypeListItem> parentElement = allElements.stream() .filter(element -> Objects.equals(element.getDragAndDropElement().getAttribute(UUID_ATTR), parentElementId)) .findFirst(); parentElement.ifPresent(parent -> { if (!isParentElementOnList(groupedElements, parentElementId)) { groupElementWithItsParent(groupedElements, allElements, parent); groupedElements.add(item); } else { final int index = getIndexOfParentOrLastElementInGroup(groupedElements, parent) + 1; if (index == groupedElements.size()) { groupedElements.add(item); } else { groupedElements.add(index, item); } } }); } else { groupedElements.add(item); } }
Source:
public BoxFolder onSend() throws BoxException { BoxRequestsFolder.GetFolderInfo folderInfoReq = new BoxRequestsFolder.GetFolderInfo(mFolderId, mRequestUrlString, mSession) { @Override protected void onSendCompleted(BoxResponse<BoxFolder> response) throws BoxException { } }.setFields(BoxFolder.ALL_FIELDS).setLimit(1000); BoxFolder folder = folderInfoReq.send(); BoxRequestBatch batchRequest = new BoxRequestBatch().setExecutor(SdkUtils.createDefaultThreadPoolExecutor(10, 10, 3600, TimeUnit.SECONDS)); BoxListItems boxListItems = folder.getItemCollection(); int offset = boxListItems.offset().intValue(); int limit = boxListItems.limit().intValue(); while (offset + limit < boxListItems.fullSize()) { offset += limit; limit = 1000; BoxRequestsFolder.GetFolderItems folderItemsReq = new BoxRequestsFolder.GetFolderItems(mFolderId, mRequestUrlString + "/items", mSession) { @Override protected void onSendCompleted(BoxResponse<BoxListItems> response) throws BoxException { } }.setFields(BoxFolder.ALL_FIELDS) .setOffset(offset) .setLimit(limit); batchRequest.addRequest(folderItemsReq); } BoxResponseBatch batchResponse = batchRequest.send(); for (BoxResponse response : batchResponse.getResponses()) { if (response.isSuccess()) { folder.getItemCollection().addAll((BoxListItems) response.getResult()); } else { throw (BoxException) response.getException(); } } return folder; }

Target:
public BoxFolder onSend() throws BoxException { String fields = mQueryMap.get(QUERY_FIELDS); BoxRequestsFolder.GetFolderInfo folderInfoReq = new BoxRequestsFolder.GetFolderInfo(mFolderId, mRequestUrlString, mSession) { @Override protected void onSendCompleted(BoxResponse<BoxFolder> response) throws BoxException { } }.setFields(fields).setLimit(LIMIT); BoxFolder folder = folderInfoReq.send(); BoxRequestBatch batchRequest = new BoxRequestBatch().setExecutor(SdkUtils.createDefaultThreadPoolExecutor(10, 10, 3600, TimeUnit.SECONDS)); BoxIteratorItems BoxIteratorItems = folder.getItemCollection(); int offset = BoxIteratorItems.offset().intValue(); int limit = BoxIteratorItems.limit().intValue(); while (offset + limit < BoxIteratorItems.fullSize()) { offset += limit; limit = LIMIT; BoxRequestsFolder.GetFolderItems folderItemsReq = new BoxRequestsFolder.GetFolderItems(mFolderId, mItemsUrl, mSession) { @Override protected void onSendCompleted(BoxResponse<BoxIteratorItems> response) throws BoxException { } }.setFields(fields) .setOffset(offset) .setLimit(limit); batchRequest.addRequest(folderItemsReq); } BoxResponseBatch batchResponse = batchRequest.send(); JsonObject folderJson = folder.toJsonObject(); JsonArray collection = folderJson.get(BoxFolder.FIELD_ITEM_COLLECTION).asObject() .get(BoxIterator.FIELD_ENTRIES).asArray(); for (BoxResponse response : batchResponse.getResponses()) { if (response.isSuccess()) { for (BoxItem item : (BoxIteratorItems)response.getResult()) { collection.add(item.toJsonObject()); } } else { throw (BoxException) response.getException(); } } return new BoxFolder(folderJson); }
Source:
public static String toString(Document document) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString(); }

Target:
protected static String toString(Document document) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString(); }
Source:
static SonarComponents sonarComponents(File file) { SensorContextTester context = SensorContextTester.create(new File("")).setRuntime(SonarRuntimeImpl.forSonarLint(Version.create(6, 7))); context.setSettings(new MapSettings().setProperty("sonar.java.failOnException", true)); SonarComponents sonarComponents = new SonarComponents(null, context.fileSystem(), null, null, null) { @Override public boolean reportAnalysisError(RecognitionException re, File file) { return false; } }; sonarComponents.setSensorContext(context); context.fileSystem().add(new TestInputFileBuilder("", file.getPath()).setCharset(StandardCharsets.UTF_8).build()); return sonarComponents; }

Target:
static SonarComponents sonarComponents(File file) throws IOException { File moduleBaseDir = new File(""); SensorContextTester context = SensorContextTester.create(moduleBaseDir); context.fileSystem().setWorkDir(moduleBaseDir.toPath()); SonarComponents sonarComponents = new SonarComponents(null, context.fileSystem(), null, null, null); sonarComponents.setSensorContext(context); DefaultInputFile inputFile = new TestInputFileBuilder("", moduleBaseDir, file).setCharset(StandardCharsets.UTF_8) .setContents(new String(Files.readAllBytes(file.toPath()))).build(); context.fileSystem().add(inputFile); return sonarComponents; }
Source:
public ModelMetaData metaData() { return null ; }

Target:
public ModelMetaData metaData() { return new ModelMetaData(new int[][] {inputShape}, 1, ZooType.CNN); }
Source:
public WorkflowTask findTaskByContentlet(final Contentlet contentlet) throws DotDataException { if (!UtilMethods.isSet(contentlet.getIdentifier()) || cache.is404(contentlet)) { return null; } WorkflowTask task = cache.getTask(contentlet); if (task == null) { final DotConnect db = new DotConnect(); db.setSQL(WorkflowSQL.SELECT_TASK); db.addParam(contentlet.getIdentifier()); db.addParam(contentlet.getLanguageId()); List<WorkflowTask> foundTasks = this .convertListToObjects(db.loadObjectResults(), WorkflowTask.class); if (null != foundTasks && !foundTasks.isEmpty()) { task = foundTasks.get(0); } if (null != task && null != task.getId()) { cache.addTask(contentlet, task); } else { cache.add404Task(contentlet); } } return task; }

Target:
public WorkflowTask findTaskByContentlet(final Contentlet contentlet) throws DotDataException { WorkflowTask task = null; if (!UtilMethods.isSet(contentlet.getIdentifier()) || cache.is404(contentlet)) { return task; } task = cache.getTask(contentlet); if (task == null) { final DotConnect db = new DotConnect(); db.setSQL(WorkflowSQL.SELECT_TASK); db.addParam(contentlet.getIdentifier()); db.addParam(contentlet.getLanguageId()); List<WorkflowTask> foundTasks = this .convertListToObjects(db.loadObjectResults(), WorkflowTask.class); if (null != foundTasks && !foundTasks.isEmpty()) { task = foundTasks.get(0); } if (null != task && null != task.getId()) { cache.addTask(contentlet, task); } else { cache.add404Task(contentlet); } } return task; }
Source:
public static void clear() { MDC.remove(SITE_NAME_MDC_KEY); SiteContext current = threadLocal.get(); logger.debug("Releasing read lock for context {}", current); current.accessLock.unlock(); threadLocal.remove(); }

Target:
public static void clear() { MDC.remove(SITE_NAME_MDC_KEY); SiteContext current = threadLocal.get(); logger.debug("Releasing access lock for context {}", current); current.accessLock.unlock(); threadLocal.remove(); }
Source:
protected void activate(final BundleContext bundleContext) { productInfo = productInfoProvider.getProductInfo(); final Dictionary<String, Object> properties = new Hashtable<>(); String distribution; String version = productInfo.getShortVersion(); if (Distribution.CLOUD_READY.equals(getDistribution())) { distribution = Distribution.CLOUD_READY.getValue(); } else { distribution = Distribution.CLASSIC.getValue(); log.debug("Registering [ ] as an OSGi Service so it be be used to enable/disable other OSGi Components", this.getClass().getSimpleName()); } properties.put(PN_DISTRIBUTION, distribution); properties.put(PN_VERSION, version); serviceRegistration = bundleContext.registerService(RequireAem.class.getName(), this, properties); log.error("Registering [ RequireAem.class ] as an OSGi Service with OSGi properties [ distribution = {}, version = ] so it be be used to enable/disable other OSGi Components", properties.get(PN_DISTRIBUTION), properties.get(PN_VERSION)); }

Target:
protected void activate(final BundleContext bundleContext) { productInfo = productInfoProvider.getProductInfo(); final Dictionary<String, Object> properties = new Hashtable<>(); String distribution; String version = productInfo.getShortVersion(); if (Distribution.CLOUD_READY.equals(getDistribution())) { distribution = Distribution.CLOUD_READY.getValue(); } else { distribution = Distribution.CLASSIC.getValue(); } properties.put(PN_DISTRIBUTION, distribution); properties.put(PN_VERSION, version); serviceRegistration = bundleContext.registerService(RequireAem.class.getName(), this, properties); log.info("Registering [ RequireAem.class ] as an OSGi Service with OSGi properties [ distribution = {}, version = ] so it be be used to enable/disable other OSGi Components", properties.get(PN_DISTRIBUTION), properties.get(PN_VERSION)); }
Source:
public void apply(PacketContext pktCtx, RuleResult res, UUID ownerId) { if (!pktCtx.tracingEnabled(requestId)) { pktCtx.setTracingEnabled(requestId); throw TraceRequiredException.instance(); } }

Target:
public void apply(PacketContext pktCtx, RuleResult res, UUID ownerId) { if (!pktCtx.tracingEnabled(requestId)) { pktCtx.enableTracing(requestId); throw TraceRequiredException.instance(); } }
Source:
protected void doPublish(final ExtLogRecord record) { record.copyAll(); synchronized (buffer) { if (isLoggable(record)) { if (buffer.size() == limit) { buffer.removeFirst(); } buffer.addLast(record); } for (Handler handler : getHandlers()) { if (handler.isLoggable(record)) { handler.publish(record); } } } }

Target:
protected void doPublish(final ExtLogRecord record) { record.copyAll(); synchronized (buffer) { if (isLoggable(record)) { if (buffer.size() == limit) { buffer.removeFirst(); } buffer.addLast(record); } for (Handler handler : getHandlers()) { handler.publish(record); } } }
Source:
public void run() { logger.info("Starting."); try { while (!shutdownRequested) { try { executor.waitUntilQueueSizeLowerThanThreshold(executorRecovery.getMaxWaitUntil()); if (!shutdownRequested) { executorRecovery.tick(); if (stateProcessorFactory.getPotentiallyStuckProcessors() == executor.getThreadCount()) { logger.warn("All state processor threads are potentially stuck."); } dispatch(getNextInstanceIds()); } } catch (PollingRaceConditionException pex) { logger.info(pex.getMessage()); sleep(true); } catch (@SuppressWarnings("unused") InterruptedException dropThrough) { } catch (Exception e) { logger.error("Exception in executing dispatcher - retrying after sleep period (" + e.getMessage() + ")", e); sleep(false); } } } finally { shutdownPool(); logger.info("Shutdown finished."); shutdownDone.countDown(); } }

Target:
public void run() { logger.info("Starting."); try { while (!shutdownRequested) { try { executor.waitUntilQueueSizeLowerThanThreshold(executorRecovery.getMaxWaitUntil()); if (!shutdownRequested) { executorRecovery.tick(); int potentiallyStuckProcessors = stateProcessorFactory.getPotentiallyStuckProcessors(); if (potentiallyStuckProcessors > 0) { periodicLogger.warn("{} of state processor threads are potentially stuck (processing longer than seconds)", potentiallyStuckProcessors, executor.getThreadCount(), stuckThreadThresholdSeconds); } dispatch(getNextInstanceIds()); } } catch (PollingRaceConditionException pex) { logger.info(pex.getMessage()); sleep(true); } catch (@SuppressWarnings("unused") InterruptedException dropThrough) { } catch (Exception e) { logger.error("Exception in executing dispatcher - retrying after sleep period (" + e.getMessage() + ")", e); sleep(false); } } } finally { shutdownPool(); executorRecovery.markShutdown(); logger.info("Shutdown finished."); shutdownDone.countDown(); } }
Source:
private int idx(long val) { int hashCode = Long.hashCode(val); hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12); return (hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4)) & (cache.length - 1); }

Target:
private int idx(long val) { return hashFunction.hash(val) & (cache.length - 1); }
Source:
protected List<MondrianCatalog> getCatalogs( IPentahoSession pentahoSession ) { Map<String, MondrianCatalog> catalogsMap = (Map<String, MondrianCatalog>) PentahoSystem.getCacheManager( pentahoSession ).getFromRegionCache( MONDRIAN_CATALOG_CACHE_REGION, getLocale().toString() ); List<MondrianCatalog> catalogs = new ArrayList<MondrianCatalog>(); if ( catalogsMap == null ) { return catalogs; } synchronized ( catalogsMap ) { for ( Object o : catalogsMap.values() ) { if ( o instanceof MondrianCatalog ) { catalogs.add( (MondrianCatalog) o ); } } } Collections.sort( catalogs, new Comparator<MondrianCatalog>() { @Override public int compare( MondrianCatalog o1, MondrianCatalog o2 ) { return o1.getName().compareTo( o2.getName() ); } } ); SetUniqueList uniqueCatalogs = SetUniqueList.decorate( catalogs ); return uniqueCatalogs; }

Target:
protected List<MondrianCatalog> getCatalogs( IPentahoSession pentahoSession ) { Map<String, MondrianCatalog> catalogsMap = (Map<String, MondrianCatalog>) PentahoSystem.getCacheManager( pentahoSession ).getFromRegionCache( MONDRIAN_CATALOG_CACHE_REGION, getLocale().toString() ); List<MondrianCatalog> catalogs = new ArrayList<MondrianCatalog>(); for ( Object o : catalogsMap.values() ) { if ( o instanceof MondrianCatalog ) { catalogs.add( (MondrianCatalog) o ); } } Collections.sort( catalogs, new Comparator<MondrianCatalog>() { @Override public int compare( MondrianCatalog o1, MondrianCatalog o2 ) { return o1.getName().compareTo( o2.getName() ); } } ); SetUniqueList uniqueCatalogs = SetUniqueList.decorate( catalogs ); return uniqueCatalogs; }