auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected String handleObjectPost(Object object) throws Exception { String workspace = getAttribute( "workspace"); String coveragestore = getAttribute( "coveragestore"); CoverageInfo coverage = (CoverageInfo) object; if ( coverage.getStore() == null ) { CoverageStoreInfo ds = catalog.getCoverageStoreByName( workspace, coveragestore ); coverage.setStore( ds ); } final boolean isNew = isNewCoverage(coverage); String name = coverage.getName(); CatalogBuilder builder = new CatalogBuilder(catalog); CoverageStoreInfo store = coverage.getStore(); builder.setStore(store); if (!isNew) { builder.initCoverage(coverage, name); } else { coverage = builder.buildCoverage(name); } NamespaceInfo ns = coverage.getNamespace(); if ( ns != null && !ns.getPrefix().equals( workspace ) ) { LOGGER.warning( "Namespace: " + ns.getPrefix() + " does not match workspace: " + workspace + ", overriding." ); ns = null; } if ( ns == null){ ns = catalog.getNamespaceByPrefix( workspace ); coverage.setNamespace( ns ); } coverage.setEnabled(true); List<RuntimeException> validationErrors = catalog.validate(coverage, true); if (!validationErrors.isEmpty()) { throw new RuntimeException("Validation failed"); } catalog.add( coverage ); catalog.add(builder.buildLayer(coverage)); LOGGER.info( "POST coverage " + coveragestore + "," + coverage.getName() ); return coverage.getName(); }

Target:
protected String handleObjectPost(Object object) throws Exception { String workspace = getAttribute( "workspace"); String coveragestore = getAttribute( "coveragestore"); CoverageInfo coverage = (CoverageInfo) object; if ( coverage.getStore() == null ) { CoverageStoreInfo ds = catalog.getCoverageStoreByName( workspace, coveragestore ); coverage.setStore( ds ); } final boolean isNew = isNewCoverage(coverage); String name = coverage.getName(); CatalogBuilder builder = new CatalogBuilder(catalog); CoverageStoreInfo store = coverage.getStore(); builder.setStore(store); if (!isNew) { builder.initCoverage(coverage, name); } else { coverage = builder.buildCoverage(name); } NamespaceInfo ns = coverage.getNamespace(); if ( ns != null && !ns.getPrefix().equals( workspace ) ) { LOGGER.warning( "Namespace: " + ns.getPrefix() + " does not match workspace: " + workspace + ", overriding." ); ns = null; } if ( ns == null){ ns = catalog.getNamespaceByPrefix( workspace ); coverage.setNamespace( ns ); } coverage.setEnabled(true); catalog.validate(coverage, true).throwIfInvalid(); catalog.add( coverage ); catalog.add(builder.buildLayer(coverage)); LOGGER.info( "POST coverage " + coveragestore + "," + coverage.getName() ); return coverage.getName(); }
Source:
protected final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException { JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(req.getReader()); String tokenString = json.get("_authKey").getAsString(); CurrentUser user = currentUser.get(); Account.Id userId; if (user instanceof IdentifiedUser) { userId = ((IdentifiedUser) user).getAccountId(); } else { res.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } try { verifier.verify(userId, getReqUrl(req), tokenString); } catch (InvalidTokenException err) { handleError(err, req, res); return; } doRequest(req, res, json); }

Target:
protected final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { CurrentUser user = userProvider.get(); if (!(user instanceof IdentifiedUser)) { sendError(res, SC_UNAUTHORIZED, "API requires authentication"); return; } ParsedBody body; if (JSON_TYPE.equals(req.getContentType())) { body = parseJson(req, res); } else if (FORM_ENCODED.equals(req.getContentType())) { body = parseForm(req, res); } else { sendError(res, SC_BAD_REQUEST, String.format( "Expected Content-Type: %s or %s", JSON_TYPE, FORM_ENCODED)); return; } if (body == null) { return; } if (Strings.isNullOrEmpty(body._authkey)) { String h = req.getHeader(AUTHKEY_HEADER); if (Strings.isNullOrEmpty(h)) { sendError(res, SC_BAD_REQUEST, String.format( "Expected %s in request body or %s in HTTP headers", AUTHKEY_NAME, AUTHKEY_HEADER)); return; } body._authkey = URLDecoder.decode(h, UTF_8); } try { verifier.verify( ((IdentifiedUser) user).getAccountId(), computeUrl(req), body._authkey); } catch (InvalidTokenException err) { sendError(res, SC_BAD_REQUEST, String.format("Invalid or expired %s", AUTHKEY_NAME)); return; } doRequest(body.req, res, body.json); }
Source:
Object asJSON() { return this.value; }

Target:
Object asJSON() { if (value instanceof Date) return DateUtils.toJson((Date) value); else return value; }
Source:
public void testGetExpiredTimelines() { final DateTime now = new DateTime(); final DateTime tomorrow = now.plusDays(1); final DateTime yesterday = now.minusDays(1); final DateTime twoDaysAgo = now.minusDays(2); insertTimeline(tomorrow.toDate(), true, 0); insertTimeline(tomorrow.toDate(), false, 1); insertTimeline(yesterday.toDate(), true, 2); final Timeline t4 = insertTimeline(yesterday.toDate(), false, 3); final Timeline t5 = insertTimeline(twoDaysAgo.toDate(), false, 4); final List<Timeline> expiredTimelines = tRepository.getExpiredTimelines(); Assert.assertEquals(2, expiredTimelines.size()); Assert.assertEquals(ImmutableList.of(t4, t5), expiredTimelines); }

Target:
public void testGetExpiredTimelines() { final DateTime now = new DateTime(); final DateTime tomorrow = now.plusDays(1); final DateTime yesterday = now.minusDays(1); final DateTime twoDaysAgo = now.minusDays(2); insertTimeline(tomorrow.toDate(), true, 0); insertTimeline(tomorrow.toDate(), false, 1); insertTimeline(yesterday.toDate(), true, 2); final Timeline t4 = insertTimeline(yesterday.toDate(), false, 3); final Timeline t5 = insertTimeline(twoDaysAgo.toDate(), false, 4); insertTimeline(null, false, 5); final List<Timeline> expiredTimelines = tRepository.getExpiredTimelines(); Assert.assertEquals(2, expiredTimelines.size()); Assert.assertEquals(ImmutableList.of(t4, t5), expiredTimelines); }
Source:
public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(f -> { log.trace("Inject target> Field: ({}) Decorator: ({})", f, decorator); try { Object value = getInjectableValue(f.getAnnotation(decorator), f.getName(), clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { f.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }

Target:
public List<Closeable> inject(ForkliftMessage msg, final Object instance) { final List<Closeable> closeMe = new ArrayList<>(); injectFields.keySet().stream().forEach(decorator -> { final Map<Class<?>, List<Field>> fields = injectFields.get(decorator); fields.keySet().stream().forEach(clazz -> { fields.get(clazz).forEach(field -> { log.trace("Inject target> Field: ({}) Decorator: ({})", field, decorator); try { Object value = getInjectableValue(field.getAnnotation(decorator), field.getName(), clazz, msg); if (value instanceof ForkliftProducerI) { closeMe.add((ForkliftProducerI)value); } if (value != null) { field.set(instance, value); } } catch (JsonMappingException | JsonParseException e) { log.warn("Unable to parse json for injection.", e); } catch (Exception e) { log.error("Error injecting data into Msg Handler", e); e.printStackTrace(); throw new RuntimeException("Error injecting data into Msg Handler"); } }); }); }); return closeMe; }
Source:
public void InstallationRepositoriesEvent() throws Exception { GHEventPayload.InstallationRepositories event = GitHub.offline() .parseEventPayload(payload.asReader(), GHEventPayload.InstallationRepositories.class); assertThat(event.getAction(), is("added")); assertThat(event.getInstallation().getId(), is(957387L)); assertThat(event.getInstallation().getAccount().getLogin(), is("Codertocat")); assertThat(event.getRepositorySelection(), is("selected")); assertThat(event.getRepositoriesAdded().get(0).getId(), is(186853007L)); assertThat(event.getRepositoriesAdded().get(0).getName(), is("Space")); assertThat(event.getRepositoriesAdded().get(0).getFullName(), is("Codertocat/Space")); assertThat(event.getRepositoriesAdded().get(0).isPrivate(), is(false)); assertThat(event.getRepositoriesRemoved(), is(Collections.emptyList())); assertThat(event.getSender().getLogin(), is("Codertocat")); }

Target:
public void InstallationRepositoriesEvent() throws Exception { GHEventPayload.InstallationRepositories event = GitHub.offline() .parseEventPayload(payload.asReader(), GHEventPayload.InstallationRepositories.class); assertThat(event.getAction(), is("added")); assertThat(event.getInstallation().getId(), is(957387L)); assertThat(event.getInstallation().getAccount().getLogin(), is("Codertocat")); assertThat(event.getRepositorySelection(), is("selected")); assertThat(event.getRepositoriesAdded().get(0).getId(), is(186853007L)); assertThat(event.getRepositoriesAdded().get(0).getNodeId(), is("MDEwOlJlcG9zaXRvcnkxODY4NTMwMDc=")); assertThat(event.getRepositoriesAdded().get(0).getName(), is("Space")); assertThat(event.getRepositoriesAdded().get(0).getFullName(), is("Codertocat/Space")); assertThat(event.getRepositoriesAdded().get(0).isPrivate(), is(false)); assertThat(event.getRepositoriesRemoved(), is(Collections.emptyList())); assertThat(event.getSender().getLogin(), is("Codertocat")); }
Source:
protected void onResume() { super.onResume(); Disposable merlinDisposable = MerlinFlowable.from(this).subscribe(new Consumer<NetworkStatus.State>() { @Override public void accept(@NonNull NetworkStatus.State state) throws Exception { if (NetworkStatus.State.AVAILABLE == state) { networkStatusDisplayer.displayConnected(); } else { networkStatusDisplayer.displayDisconnected(); } } }); disposables.add(merlinDisposable); }

Target:
protected void onResume() { super.onResume(); Disposable merlinDisposable = MerlinFlowable.from(this) .distinctUntilChanged() .subscribe(new NetworkConsumer(networkStatusDisplayer)); disposables.add(merlinDisposable); }
Source:
private String colored(String message, Ansi.Color color, boolean addPrefix, Object ... params) { Ansi ansi = ansi().fg(color); message = ansi.a(format(evaluateEmphasis(message, color), params)).reset().toString(); return addPrefix ? prefix + message : message; }

Target:
private String colored(String message, Ansi.Color color, boolean addPrefix, Object ... params) { Ansi ansi = ansi().fg(color); String msgToPrint = addPrefix ? prefix + message : message; return ansi.a(format(evaluateEmphasis(msgToPrint, color), params)).reset().toString(); }
Source:
private <T> Collection<Collection<T>> batch( Collection<T> collection, int batchSize ) { Collection<Collection<T>> batches = new ArrayList<>(); Collection<T> batch = new ArrayList<>(); int count = 0; for ( T t : collection ) { ( (ArrayList<T>) batch ).add( t ); count++; if ( count >= batchSize ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); batch = new ArrayList<>(); count = 0; } } return batches; }

Target:
private <T> Collection<Collection<T>> batch( Collection<T> collection, int batchSize ) { Collection<Collection<T>> batches = new ArrayList<>(); Collection<T> batch = new ArrayList<>( batchSize ); int count = 0; for ( T t : collection ) { ( (ArrayList<T>) batch ).add( t ); count++; if ( count >= batchSize ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); batch = new ArrayList<>( batchSize ); count = 0; } } if ( batch != null && !batch.isEmpty() ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); } return batches; }
Source:
public IndexRecord(String msg, boolean isDeleted, boolean isExpired) { this.message = msg; this.isDeleted = isDeleted; this.isExpired = isExpired; }

Target:
IndexRecord(String msg, boolean isDeleted, boolean isExpired) { this.message = msg; this.isDeleted = isDeleted; this.isExpired = isExpired; }
Source:
public void testInspectDatastoreEntity() throws InterruptedException, ExecutionException, IOException { InspectDatastoreEntity.insepctDatastoreEntity( PROJECT_ID, datastoreNamespace, datastoreKind, TOPIC_ID, SUBSCRIPTION_ID); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } }

Target:
public void testInspectDatastoreEntity() throws InterruptedException, ExecutionException, IOException { InspectDatastoreEntity.insepctDatastoreEntity( PROJECT_ID, datastoreNamespace, datastoreKind, TOPIC_ID, SUBSCRIPTION_ID); TimeUnit.SECONDS.sleep(3); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } }
Source:
public Object() { this.timestampFormatter = new TimestampFormatter(); }

Target:
private Object() { }
Source:
private void setupSSLSocket() throws NoSuchAlgorithmException, IOException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); DnsTlsTrustManager trustManager = new DnsTlsTrustManager(new TrustManagerImpl(mKeyStore)); sslContext.init( null, new TrustManager[] { (TrustManager) trustManager }, new SecureRandom()); mSslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(); mSslSocket.setSoTimeout(TCP_TIMEOUT); if (!TextUtils.isEmpty(mHostname)) { List<SNIServerName> names = new ArrayList<SNIServerName>(); names.add(new SNIHostName(mHostname)); SSLParameters params = mSslSocket.getSSLParameters(); params.setServerNames(names); mSslSocket.setSSLParameters(params); } }

Target:
private void setupSSLSocket() throws NoSuchAlgorithmException, IOException, KeyManagementException, KeyStoreException { String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(mKeyStore); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, tmf.getTrustManagers(), new SecureRandom()); mSslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(); mSslSocket.setSoTimeout(TCP_TIMEOUT); if (!TextUtils.isEmpty(mHostname)) { List<SNIServerName> names = new ArrayList<SNIServerName>(); names.add(new SNIHostName(mHostname)); SSLParameters params = mSslSocket.getSSLParameters(); params.setServerNames(names); mSslSocket.setSSLParameters(params); } }
Source:
public String getType() { if (fileName.endsWith(".mp3")) { return "audio/mp3"; } else if (fileName.endsWith(".png")) { return "image/png"; } else { return null; } }

Target:
public String getType() { String extension = MimeTypeMap.getFileExtensionFromUrl(fileName); return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
Source:
public JSON toJSON() { if (values == null) { return null; } JSONObject jo = new JSONObject(); for (Entry<String, T> val : values.entrySet()) { T value = val.getValue(); jo.put(val.getKey(), ApiUtil.getJsonFriendlyString((String) value)); } return jo; }

Target:
public JSON toJSON() { if (values == null) { return null; } JSONObject jo = new JSONObject(); for (Entry<String, T> val : values.entrySet()) { T value = val.getValue(); if (value instanceof String) { jo.put(val.getKey(), JsonUtil.getJsonFriendlyString((String) value)); } else { jo.put(val.getKey(), value); } } return jo; }
Source:
public int getNumCores() { if (getBoolean(JobConfig.JOB_AUTOSIZING_ENABLED, false) && containsKey(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES)) { return getInt(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES); } else if (containsKey(CLUSTER_MANAGER_MAX_CORES)) { return getInt(CLUSTER_MANAGER_MAX_CORES); } else if (containsKey(CONTAINER_MAX_CPU_CORES)) { log.info("Configuration is deprecated. Please use {}", CONTAINER_MAX_CPU_CORES, CLUSTER_MANAGER_MAX_CORES); return getInt(CONTAINER_MAX_CPU_CORES); } else { return DEFAULT_CPU_CORES; } }

Target:
public int getNumCores() { if (new JobConfig(this).getAutosizingEnabled() && containsKey(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES)) { return getInt(JobConfig.JOB_AUTOSIZING_CONTAINER_MAX_CORES); } else if (containsKey(CLUSTER_MANAGER_MAX_CORES)) { return getInt(CLUSTER_MANAGER_MAX_CORES); } else if (containsKey(CONTAINER_MAX_CPU_CORES)) { log.info("Configuration is deprecated. Please use {}", CONTAINER_MAX_CPU_CORES, CLUSTER_MANAGER_MAX_CORES); return getInt(CONTAINER_MAX_CPU_CORES); } else { return DEFAULT_CPU_CORES; } }
Source:
protected boolean isKieContainerRemovalAllowed(ConfigMap cm, KieServerState newState) { KieServerState state = (KieServerState) xs.fromXML(cm.getData().get(CFG_MAP_DATA_KEY)); for (KieContainerResource container : state.getContainers()) { if (container.getStatus().equals(KieContainerStatus.STOPPED) && newState.getContainers().stream() .filter(c -> c.getContainerId().equals(container.getContainerId())) .collect(Collectors.toList()).isEmpty()) { logger.warn("Removing STOPPED KieContainer by KieServer process is not allowed."); return false; } } return true; }

Target:
public boolean isKieContainerRemovalAllowed(ConfigMap cm, KieServerState newState) { KieServerState state = (KieServerState) xs.fromXML(cm.getData().get(CFG_MAP_DATA_KEY)); for (KieContainerResource container : state.getContainers()) { if (container.getStatus().equals(KieContainerStatus.STOPPED) && newState.getContainers().stream() .noneMatch(c -> c.getContainerId().equals(container.getContainerId()))) { logger.warn("Removing STOPPED KieContainer by KieServer process is not allowed."); return false; } } return true; }
Source:
protected Partitioner.Partition<AbstractKafkaInputOperator> createPartition(Set<AbstractKafkaPartitioner.PartitionMeta> partitionAssignment) { Kryo kryo = new Kryo(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos); kryo.writeObject(output, prototypeOperator); output.close(); Input lInput = new Input(bos.toByteArray()); Partitioner.Partition<AbstractKafkaInputOperator> p = new DefaultPartition<>(kryo.readObject(lInput, prototypeOperator.getClass())); p.getPartitionedInstance().setAssignment(partitionAssignment); return p; }

Target:
protected Partitioner.Partition<AbstractKafkaInputOperator> createPartition(Set<AbstractKafkaPartitioner.PartitionMeta> partitionAssignment) { Kryo kryo = new Kryo(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos); kryo.writeObject(output, prototypeOperator); output.close(); Input lInput = new Input(bos.toByteArray()); Partitioner.Partition<AbstractKafkaInputOperator> p = (Partitioner.Partition<AbstractKafkaInputOperator>) new DefaultPartition<>(kryo.readObject(lInput, prototypeOperator.getClass())); p.getPartitionedInstance().assign(partitionAssignment); return p; }
Source:
public void onSelectionChanged(PreviewNode selectedNode) { Either<ResourceChange, TextEdit> data = selectedNode.getData(); if (data != null && data.isLeft()) { view.showDiff(null); return; } PreviewNode node = nodes.get(selectedNode.getUri()); List<TextEdit> edits = new ArrayList<>(); if (node.getId().equals(selectedNode.getId())) { for (PreviewNode child : node.getChildren()) { TextEdit right = child.getData().getRight(); if (child.isEnable()) { edits.add(right); } } } else if (data != null && selectedNode.isEnable()) { edits.add(data.getRight()); } Path path = toPath(selectedNode.getUri()).removeFirstSegments(1); Container workspaceRoot = appContext.getWorkspaceRoot(); Promise<Optional<File>> file = workspaceRoot.getFile(path); file.then( arg -> { if (!arg.isPresent()) { return; } File existedFile = arg.get(); existedFile .getContent() .then( content -> { ChangePreview changePreview = dtoFactory.createDto(ChangePreview.class); changePreview.setFileName(existedFile.getName()); changePreview.setOldContent(content); StringBuilder output = new StringBuilder(); new StringStreamEditor(edits, content, output).transform(); String result = output.toString(); changePreview.setNewContent(result); view.showDiff(changePreview); }); }); }

Target:
public void onSelectionChanged(PreviewNode selectedNode) { Either<ResourceChange, TextEdit> data = selectedNode.getData(); if (data != null && data.isLeft()) { view.showDiff(null); return; } List<TextEdit> edits = collectTextEditsForSelectedNode(selectedNode); updateContentInCompareWidget(selectedNode, edits); }
Source:
private MetaLanguage buildMetaLanguage(Language language, String packageCode, PackageList packages, PackageStructureList packageStructures, Multimap<UUID, Translation> translationsMap, boolean draftsOnly, boolean allResults) { MetaLanguage metaLanguage = new MetaLanguage(language); if(Strings.isNullOrEmpty(packageCode)) { TranslationList translations = new TranslationList((List<Translation>) translationsMap.get(language.getId())); if(!allResults) { translations = new TranslationList(translations.pareResults()); } for (Translation translation : translations) { Package gtPackage = packages.getPackageById(translation.getPackageId()).get(); metaLanguage.addPackage( gtPackage.getCode(), new GodToolsVersion( packageStructures.getByPackageId(gtPackage.getId()).get(), translation), translation.isReleased()); } } else { Translation translation = null; Package gtPackage = packages.getPackageByCode(packageCode).get(); for(Translation translationT : new TranslationList((List<Translation>) translationsMap.get(language.getId()))) { if(translationT.getPackageId().equals(gtPackage.getId())) { if(draftsOnly) { if(!translationT.isReleased()) { translation = translationT; } } else { if(translationT.isReleased() && (translation == null || translationT.getVersionNumber().compareTo(translation.getVersionNumber()) > 0)) { translation = translationT; } } } } if(translation != null) { metaLanguage.addPackage( packageCode, new GodToolsVersion( packageStructures.getByPackageId(gtPackage.getId()).get(), translation), translation.isReleased()); } } return metaLanguage; }

Target:
private MetaLanguage buildMetaLanguage(Language language, String packageCode, PackageList packages, PackageStructureList packageStructures, Multimap<UUID, Translation> translationsMap, boolean draftsOnly, boolean allResults) { MetaLanguage metaLanguage = new MetaLanguage(language); if(Strings.isNullOrEmpty(packageCode)) { TranslationList translations = new TranslationList((List<Translation>) translationsMap.get(language.getId())); if(!allResults) { translations = translations.pareResults(); } for (Translation translation : translations) { Package gtPackage = packages.getPackageById(translation.getPackageId()).get(); metaLanguage.addPackage( gtPackage.getCode(), new GodToolsVersion( packageStructures.getByPackageId(gtPackage.getId()).get(), translation), translation.isReleased()); } } else { Package gtPackage = packages.getPackageByCode(packageCode).get(); TranslationList translations = new TranslationList((List<Translation>) translationsMap.get(language.getId())) .pareResults(!draftsOnly) .pareResults(gtPackage.getId()); translations = draftsOnly ? translations : translations.pareResults(); Translation translation = !translations.isEmpty() ? translations.get(0) : null; if(translation != null) { metaLanguage.addPackage( packageCode, new GodToolsVersion( packageStructures.getByPackageId(gtPackage.getId()).get(), translation), translation.isReleased()); } } return metaLanguage; }
Source:
private double getMcqOtherWeight(Map<String, String[]> requestParameters, boolean mcqOtherEnabled, boolean hasAssignedWeights) { double mcqOtherWeight = this.mcqOtherWeight; if (!hasAssignedWeights || !mcqOtherEnabled) { return mcqOtherWeight; } String weightOther = HttpRequestHelper.getValueFromParamMap( requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MCQ_OTHER_WEIGHT); try { mcqOtherWeight = Double.parseDouble(weightOther); } catch (NumberFormatException e) { log.warning("Failed to parse \"other\" weight of MCQ question: " + weightOther); } return mcqOtherWeight; }

Target:
private double getMcqOtherWeight(Map<String, String[]> requestParameters, boolean mcqOtherEnabled, boolean hasAssignedWeights) { double mcqOtherWeight = 0; if (!hasAssignedWeights || !mcqOtherEnabled) { return mcqOtherWeight; } String weightOther = HttpRequestHelper.getValueFromParamMap( requestParameters, Const.ParamsNames.FEEDBACK_QUESTION_MCQ_OTHER_WEIGHT); Assumption.assertNotNull("Null 'other' weight of MCQ question", weightOther); Assumption.assertNotEmpty("Empty 'other' weight of MCQ question", weightOther); try { mcqOtherWeight = Double.parseDouble(weightOther); } catch (NumberFormatException e) { log.warning("Failed to parse \"other\" weight of MCQ question: " + weightOther); } return mcqOtherWeight; }
Source:
public void test_streaming_of_signature_and_type_signatures() throws Exception { var objectType = ObjectType.builder() .setInnerType("x", DataTypes.INTEGER) .build(); var signature = Signature.builder() .name("foo") .kind(FunctionInfo.Type.SCALAR) .setVariableArity(true) .argumentTypes( parseTypeSignature("E"), DataTypes.INTEGER.getTypeSignature(), objectType.getTypeSignature() ) .returnType(DataTypes.BIGINT_ARRAY.getTypeSignature()) .variableArityGroup( List.of( DataTypes.INTEGER.getTypeSignature(), objectType.getTypeSignature() ) ) .typeVariableConstraints(typeVariable("E")) .build(); BytesStreamOutput out = new BytesStreamOutput(); signature.writeTo(out); StreamInput in = out.bytes().streamInput(); var signature2 = new Signature(in); assertThat(signature2, equalTo(signature)); }

Target:
public void test_streaming_of_signature_and_type_signatures() throws Exception { var objectType = ObjectType.builder() .setInnerType("x", DataTypes.INTEGER) .build(); var signature = Signature.builder() .name("foo") .kind(FunctionInfo.Type.SCALAR) .argumentTypes( parseTypeSignature("E"), DataTypes.INTEGER.getTypeSignature(), objectType.getTypeSignature() ) .returnType(DataTypes.BIGINT_ARRAY.getTypeSignature()) .variableArityGroup( List.of( DataTypes.INTEGER.getTypeSignature(), objectType.getTypeSignature() ) ) .typeVariableConstraints(typeVariable("E")) .build(); BytesStreamOutput out = new BytesStreamOutput(); signature.writeTo(out); StreamInput in = out.bytes().streamInput(); var signature2 = new Signature(in); assertThat(signature2, equalTo(signature)); }
Source:
public void process() { enableWireframeIf(renderingDebugConfig.isWireframe()); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); setRenderBufferMask(sceneOpaque, true, true, true); if (renderingConfig.isInscattering()) { sceneSkyBand0 = frameBuffersManager.getFBO("sceneSkyBand0"); FBO sceneSkyBand1 = frameBuffersManager.getFBO("sceneSkyBand1"); generateSkyBand(sceneSkyBand0); generateSkyBand(sceneSkyBand1); } sceneOpaque.bind(); playerCamera.lookThrough(); endRenderSkyActivity(); }

Target:
public void process() { PerformanceMonitor.startActivity("rendering/skybands"); enableWireframeIf(renderingDebugConfig.isWireframe()); sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); setRenderBufferMask(sceneOpaque, true, true, true); if (renderingConfig.isInscattering()) { sceneSkyBand0 = frameBuffersManager.getFBO("sceneSkyBand0"); FBO sceneSkyBand1 = frameBuffersManager.getFBO("sceneSkyBand1"); generateSkyBand(sceneSkyBand0); generateSkyBand(sceneSkyBand1); } sceneOpaque.bind(); playerCamera.lookThrough(); disableWireframeIf(renderingDebugConfig.isWireframe()); PerformanceMonitor.endActivity(); }
Source:
protected boolean isSubtypeWithElements( AnnotationMirror subAnno, QualifierKind subKind, AnnotationMirror superAnno, QualifierKind superKind) { if (!subKind.isInSameHierarchyAs(NULLABLE) || !superKind.isInSameHierarchyAs(NULLABLE)) { return this.isSubtypeInitialization(subAnno, subKind, superAnno, superKind); } throw new BugInCF("Unexpected annotations %s %s.", subAnno, superAnno); }

Target:
protected boolean isSubtypeWithElements( AnnotationMirror subAnno, QualifierKind subKind, AnnotationMirror superAnno, QualifierKind superKind) { if (!subKind.isInSameHierarchyAs(NULLABLE) || !superKind.isInSameHierarchyAs(NULLABLE)) { return this.isSubtypeInitialization(subAnno, subKind, superAnno, superKind); } throw new BugInCF( "Unexpected annotations isSubtypeWithElements(%s, %s)", subAnno, superAnno); }
Source:
public void testCsvQueryResponseTransformer() throws CatalogTransformerException, IOException { Map<String, Serializable> argumentsMap = new HashMap<>(); String[] hiddenFieldsArray = {"attribute3", "attribute5"}; argumentsMap.put("hiddenFields", buildSet(hiddenFieldsArray)); String[] columnOrderArray = {"attribute4", "attribute2", "attribute1"}; argumentsMap.put("columnOrder", buildList(columnOrderArray)); String[][] aliases = {{"attribute1", "column1"}, {"attribute2", "column2"}}; argumentsMap.put("aliases", buildMap(aliases)); assertThat(ATTRIBUTE_DESCRIPTOR_LIST.size(), is(ATTRIBUTE_DATA.length)); BinaryContent bc = transformer.transform(sourceResponse, argumentsMap); Scanner scanner = new Scanner(bc.getInputStream()); scanner.useDelimiter("\\n|\\r|,"); String[] expectedHeaders = {"attribute4", "column2", "column1"}; validate(scanner, expectedHeaders); String[] expectedValues = {"", "\"value", "4\"", "101", "value1"}; for (int i = 0; i < METACARD_COUNT; i++) { validate(scanner, expectedValues); } assertThat(scanner.hasNext(), is(true)); assertThat(scanner.next(), is("")); assertThat(scanner.hasNext(), is(false)); }

Target:
public void testCsvQueryResponseTransformer() throws CatalogTransformerException, IOException { Map<String, Serializable> argumentsMap = new HashMap<>(); String[] hiddenFieldsArray = {"attribute3", "attribute5"}; argumentsMap.put("hiddenFields", buildSet(hiddenFieldsArray)); String[] columnOrderArray = {"attribute4", "attribute2"}; argumentsMap.put("columnOrder", buildList(columnOrderArray)); String[][] aliases = {{"attribute1", "column1"}, {"attribute2", "column2"}}; argumentsMap.put("aliases", buildMap(aliases)); assertThat(ATTRIBUTE_DESCRIPTOR_LIST.size(), is(ATTRIBUTE_DATA.length)); BinaryContent bc = transformer.transform(sourceResponse, argumentsMap); Scanner scanner = new Scanner(bc.getInputStream()); scanner.useDelimiter("\\n|\\r|,"); String[] expectedHeaders = {"attribute4", "column2"}; validate(scanner, expectedHeaders); String[] expectedValues = {"", "\"value", "4\"", "101"}; for (int i = 0; i < METACARD_COUNT; i++) { validate(scanner, expectedValues); } assertThat(scanner.hasNext(), is(true)); assertThat(scanner.next(), is("")); assertThat(scanner.hasNext(), is(false)); }
Source:
public void update(VdsDynamic vds) { DnsResolverConfiguration reportedDnsResolverConfiguration = vds.getReportedDnsResolverConfiguration(); if (reportedDnsResolverConfiguration != null) { if (reportedDnsResolverConfiguration.getId() == null) { dnsResolverConfigurationDao.save(reportedDnsResolverConfiguration); } else { dnsResolverConfigurationDao.update(reportedDnsResolverConfiguration); } } getCallsHandler().executeModification("UpdateVdsDynamic", createFullParametersMapper(vds)); }

Target:
public void update(VdsDynamic vds) { DnsResolverConfiguration reportedDnsResolverConfiguration = vds.getReportedDnsResolverConfiguration(); if (reportedDnsResolverConfiguration == null) { dnsResolverConfigurationDao.removeByVdsDynamicId(vds.getId()); } else { if (reportedDnsResolverConfiguration.getId() == null) { dnsResolverConfigurationDao.save(reportedDnsResolverConfiguration); } else { dnsResolverConfigurationDao.update(reportedDnsResolverConfiguration); } } getCallsHandler().executeModification("UpdateVdsDynamic", createFullParametersMapper(vds)); }
Source:
public Map<TaskName, Integer> readPartitionMapping() { LOG.debug("Reading changelog partition information"); final Map<TaskName, Integer> changelogMapping = new HashMap<>(); metadataStore.all().forEach((taskName, partitionIdAsBytes) -> { String partitionId = valueSerde.fromBytes(partitionIdAsBytes); LOG.debug("TaskName: is mapped to {}", taskName, partitionId); if (partitionId != null) { changelogMapping.put(new TaskName(taskName), Integer.valueOf(partitionId)); } }); return changelogMapping; }

Target:
public Map<TaskName, Integer> readPartitionMapping() { LOG.debug("Reading changelog partition information"); final Map<TaskName, Integer> changelogMapping = new HashMap<>(); metadataStore.all().forEach((taskName, partitionIdAsBytes) -> { String partitionId = valueSerde.fromBytes(partitionIdAsBytes); LOG.debug("TaskName: is mapped to {}", taskName, partitionId); if (StringUtils.isNotBlank(partitionId)) { changelogMapping.put(new TaskName(taskName), Integer.valueOf(partitionId)); } }); return changelogMapping; }
Source:
public static boolean checkClusterVersionSupported(Version clusterCompatibilityVersion, VDS vds) { boolean isVersionSupported = !StringUtils.isEmpty(vds.getSupportedClusterLevels()); if (isVersionSupported) { try { isVersionSupported = vds.getSupportedClusterVersionsSet().contains(clusterCompatibilityVersion); } catch (RuntimeException e) { log.error(e.getMessage()); isVersionSupported = false; } } return isVersionSupported; }

Target:
public static boolean checkClusterVersionSupported(Version clusterCompatibilityVersion, VDS vds) { boolean isVersionSupported = !StringUtils.isEmpty(vds.getSupportedClusterLevels()); if (isVersionSupported) { try { isVersionSupported = vds.getSupportedClusterVersionsSet().contains(clusterCompatibilityVersion); } catch (RuntimeException e) { log.error("{}", e.getMessage()); log.debug("Exception", e); isVersionSupported = false; } } return isVersionSupported; }
Source:
public String encodePartition(SinkRecord sinkRecord) { long timestamp; if (timeFieldName.equals("")) { timestamp = System.currentTimeMillis(); } else { Struct struct = (Struct) sinkRecord.value(); timestamp = (long) struct.get(timeFieldName); } DateTime bucket = new DateTime(getPartition(partitionDurationMs, timestamp, formatter.getZone())); return bucket.toString(formatter); }

Target:
public String encodePartition(SinkRecord sinkRecord) { long timestamp; if (timeFieldName.equals("")) { timestamp = System.currentTimeMillis(); } else { try { Struct struct = (Struct) sinkRecord.value(); timestamp = (long) struct.get(timeFieldName); } catch (ClassCastException | DataException e) { throw new ConnectException("Failed to get time field:", e); } } DateTime bucket = new DateTime(getPartition(partitionDurationMs, timestamp, formatter.getZone())); return bucket.toString(formatter); }
Source:
public void testTranslateClusteredResourcePoolConfiguration() { ClusteredResourceConfigurationParser configTranslator = new ClusteredResourceConfigurationParser(); ClusteredResourcePoolImpl clusteredResourcePool = new ClusteredResourcePoolImpl(); Node retElement = configTranslator.unparseResourcePool(clusteredResourcePool); assertThat(retElement, is(notNullValue())); assertThat(retElement.getNodeName(), is("ehcache:resources")); assertThat(retElement.getAttributes(), is(notNullValue())); assertThat(retElement.getAttributes().getLength(), is(1)); assertThat(retElement.getAttributes().item(0).getNodeName(), is("xmlns:ehcache")); assertThat(retElement.getAttributes().item(0).getNodeValue(), is("<LINK_0>")); Node clusterElement = retElement.getFirstChild(); assertThat(clusterElement, is(notNullValue())); assertThat(clusterElement.getAttributes(), is(notNullValue())); assertThat(clusterElement.getAttributes().getLength(), is(1)); assertThat(clusterElement.getAttributes().item(0).getNodeName(), is("xmlns:tc")); assertThat(clusterElement.getAttributes().item(0).getNodeValue(), is("<LINK_0>/clustered")); assertThat(clusterElement.getNodeName(), is("tc:clustered")); assertThat(clusterElement.getFirstChild(), is(nullValue())); }

Target:
public void testTranslateClusteredResourcePoolConfiguration() { ClusteredResourceConfigurationParser configTranslator = new ClusteredResourceConfigurationParser(); ClusteredResourcePoolImpl clusteredResourcePool = new ClusteredResourcePoolImpl(); Node retElement = configTranslator.unparseResourcePool(clusteredResourcePool); assertThat(retElement, is(notNullValue())); assertThat(retElement.getNodeName(), is("ehcache:resources")); checkAttributeItems(retElement); Node clusterElement = retElement.getFirstChild(); assertThat(clusterElement, is(notNullValue())); assertThat(clusterElement.getNodeName(), is("tc:clustered")); checkAttributeItems(clusterElement); assertThat(clusterElement.getFirstChild(), is(nullValue())); }
Source:
BitSet<T> fromBitMaskNoCopy(long[] elements) { final int len = elements.length; if (len == 0) { return createEmpty(); } if (len == 1) { return new BitSet1<>(fromInt, toInt, elements[0]); } if (len == 2) { return new BitSet2<>(fromInt, toInt, elements[0], elements[1]); } return new BitSetN<>(fromInt, toInt, elements); }

Target:
BitSet<T> fromBitMaskNoCopy(long[] elements) { final int len = elements.length; if (len == 0) { return createEmpty(); } else if (len == 1) { return new BitSet1<>(fromInt, toInt, elements[0]); } else if (len == 2) { return new BitSet2<>(fromInt, toInt, elements[0], elements[1]); } else { return new BitSetN<>(fromInt, toInt, elements); } }
Source:
private boolean knownToBeCommittedAfterSweepTs(long startTs, long sweepTs) { Optional<Long> commitTsIfCached = commitTsCache.loadIfCached(startTs); return commitTsIfCached.isPresent() && commitTsIfCached.get() >= sweepTs; }

Target:
private boolean knownToBeCommittedAfterSweepTs(long startTs, long sweepTs) { return commitTsCache.loadIfCached(startTs).map(commitTs -> commitTs >= sweepTs).orElse(false); }
Source:
public Option[] individualModules() { return options( frameworkProperty("org.ehcache.core.osgi").value("true"), gradleBundle("org.ehcache.modules:api"), gradleBundle("org.ehcache.modules:core"), gradleBundle("org.ehcache.modules:impl"), gradleBundle("org.ehcache.modules:xml"), gradleBundle("org.ehcache:clustered-dist"), wrappedGradleBundle("org.terracotta:statistics"), wrappedGradleBundle("org.ehcache:sizeof"), wrappedGradleBundle("org.terracotta:offheap-store"), baseConfiguration() ); }

Target:
public Option[] individualModules() { return options( gradleBundle("org.ehcache.modules:api"), gradleBundle("org.ehcache.modules:core"), gradleBundle("org.ehcache.modules:impl"), gradleBundle("org.ehcache.modules:xml"), gradleBundle("org.ehcache:clustered-dist"), wrappedGradleBundle("org.terracotta:statistics"), wrappedGradleBundle("org.ehcache:sizeof"), wrappedGradleBundle("org.terracotta:offheap-store"), baseConfiguration() ); }
Source:
public void onEventTime(InternalTimer<K, VoidNamespace> timer) throws Exception { long timestamp = timer.getTimestamp(); List<RowData> inputs = inputState.get(timestamp); Iterable<Long> keyIter = inputState.keys(); for (Long dataTs : keyIter) { insertToSortedList(dataTs); } int index = sortedTimestamps.indexOf(timestamp); for (int i = 0; i < inputs.size(); i++) { forwardedInputQueue.add(inputs.get(i)); triggerWindowProcess(inputs, i, index); } windowData.clear(); sortedTimestamps.clear(); }

Target:
public void onEventTime(InternalTimer<K, VoidNamespace> timer) throws Exception { long timestamp = timer.getTimestamp(); List<RowData> inputs = inputState.get(timestamp); Iterable<Long> keyIter = inputState.keys(); long currentWatermark = timerService.currentWatermark(); for (Long dataTs : keyIter) { if (dataTs <= currentWatermark) { insertToSortedList(dataTs); } } int index = sortedTimestamps.indexOf(timestamp); for (int i = 0; i < inputs.size(); i++) { forwardedInputQueue.add(inputs.get(i)); triggerWindowProcess(inputs, i, index); } windowData.clear(); sortedTimestamps.clear(); }
Source:
public Unmarshaller getUnmarshaller() throws JAXBException { if (unmarshaller == null) { unmarshaller = JAXBContext.newInstance(ServiceDefinitionPair.class).createUnmarshaller(); } return unmarshaller; }

Target:
private synchronized Unmarshaller getUnmarshaller() throws JAXBException { if (unmarshaller == null) { unmarshaller = JAXBContext.newInstance(ServiceDefinitionPair.class).createUnmarshaller(); } return unmarshaller; }
Source:
protected Assertion getDecryptedAssertion(EncryptedAssertion encryptedAssertion) throws SSOAgentException { try { KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver( new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); EncryptedKey key = encryptedAssertion.getEncryptedData(). getKeyInfo().getEncryptedKeys().get(0); Decrypter decrypter = new Decrypter(null, keyResolver, null); SecretKey dkey = (SecretKey) decrypter.decryptKey(key, encryptedAssertion.getEncryptedData(). getEncryptionMethod().getAlgorithm()); Credential shared = SecurityHelper.getSimpleCredential(dkey); decrypter = new Decrypter(new StaticKeyInfoCredentialResolver(shared), null, null); decrypter.setRootInNewDocument(true); return decrypter.decrypt(encryptedAssertion); } catch (Exception e){ if(log.isDebugEnabled()){ log.debug("Decrypted assertion error : ",e); throw new SSOAgentException(e); } } return null; }

Target:
protected Assertion getDecryptedAssertion(EncryptedAssertion encryptedAssertion) throws SSOAgentException { try { KeyInfoCredentialResolver keyResolver = new StaticKeyInfoCredentialResolver( new X509CredentialImpl(ssoAgentConfig.getSAML2().getSSOAgentX509Credential())); EncryptedKey key = encryptedAssertion.getEncryptedData(). getKeyInfo().getEncryptedKeys().get(0); Decrypter decrypter = new Decrypter(null, keyResolver, null); SecretKey dkey = (SecretKey) decrypter.decryptKey(key, encryptedAssertion.getEncryptedData(). getEncryptionMethod().getAlgorithm()); Credential shared = SecurityHelper.getSimpleCredential(dkey); decrypter = new Decrypter(new StaticKeyInfoCredentialResolver(shared), null, null); decrypter.setRootInNewDocument(true); return decrypter.decrypt(encryptedAssertion); } catch (Exception e) { throw new SSOAgentException("Decrypted assertion error", e); } }
Source:
private String doTokenAuth(HttpServletRequest request, HttpServletResponse response) throws HttpAuthenticationException { String delegationTokenHeader = "X-Hadoop-Delegation-Token"; String tokenStr = request.getHeader(delegationTokenHeader); try { return hiveAuthFactory.verifyDelegationToken(tokenStr); } catch (HiveSQLException e) { throw new HttpAuthenticationException(e); } }

Target:
private String doTokenAuth(HttpServletRequest request, HttpServletResponse response) throws HttpAuthenticationException { String tokenStr = request.getHeader(HIVE_DELEGATION_TOKEN_HEADER); try { return hiveAuthFactory.verifyDelegationToken(tokenStr); } catch (HiveSQLException e) { throw new HttpAuthenticationException(e); } }
Source:
public void testQueryByDeployTimeAfter() { String deployTime = withTimezone("2020-03-27T00:00:00"); Date date = DateTimeUtil.parseDate(deployTime); given().queryParam("deployedAfter", deployTime) .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(PROCESS_DEFINITION_QUERY_URL); verify(mockedQuery).deployedAfter(date); verify(mockedQuery).list(); }

Target:
public void testQueryByDeployTimeAfter() { String deployTime = withTimezone("2020-03-27T01:23:45"); Date date = DateTimeUtil.parseDate(deployTime); given().queryParam("deployedAfter", deployTime) .then().expect().statusCode(Status.OK.getStatusCode()) .when().get(PROCESS_DEFINITION_QUERY_URL); verify(mockedQuery).deployedAfter(date); verify(mockedQuery).list(); }
Source:
protected void onSuccessAuthentication() { ProjectDescriptor descriptor = appContext.getCurrentProject().getProjectDescription(); final String nameSpace = getAttributeValue(descriptor, OPENSHIFT_NAMESPACE_VARIABLE_NAME); if (!nameSpace.isEmpty()) { Promise<List<BuildConfig>> buildConfigs = service.getBuildConfigs(nameSpace); buildConfigs.then(showConfirmDialog(descriptor, nameSpace)) .catchError(handleError(nameSpace)); } else { notificationManager.showInfo(locale.projectAttributeNameSpaceIsEmpty()); } }

Target:
protected void onSuccessAuthentication() { ProjectDescriptor descriptor = appContext.getCurrentProject().getProjectDescription(); final String namespace = getAttributeValue(descriptor, OPENSHIFT_NAMESPACE_VARIABLE_NAME); if (!Strings.isNullOrEmpty(namespace)) { Promise<List<BuildConfig>> buildConfigs = service.getBuildConfigs(namespace); buildConfigs.then(showConfirmDialog(descriptor, namespace)) .catchError(handleError(namespace)); } else { notificationManager.showError(locale.projectAttributeNameSpaceIsEmpty()); } }
Source:
public static <T> void assertResult(final FEELFnResult<T> result, final T expectedResult) { if (expectedResult == null) { assertResultNull(result); } else { assertResultNotError(result); final T resultValue = result.cata(left -> null, right -> right); Assert.assertThat(resultValue, Matchers.notNullValue()); ; } }

Target:
public static <T> void assertResult(final FEELFnResult<T> result, final T expectedResult) { if (expectedResult == null) { assertResultNull(result); } else { assertResultNotError(result); final T resultValue = result.cata(left -> null, right -> right); Assert.assertThat(resultValue, Matchers.notNullValue()); Assert.assertThat(resultValue, Matchers.equalTo(expectedResult)); } }
Source:
public void setUp() throws Exception { super.setUp(); when(canvasPanel.getLocationConstraints()).thenReturn(PANEL_BOUNDS); when(candidate.getContent()).thenReturn(new ViewImpl<>(mock(Object.class), ELEMENT_BOUNDS)); ; }

Target:
public void setUp() throws Exception { super.setUp(); when(canvasPanel.getLocationConstraints()).thenReturn(PANEL_BOUNDS); when(candidate.getContent()).thenReturn(new ViewImpl<>(mock(Object.class), ELEMENT_BOUNDS)); }
Source:
protected Configuration createConfiguration(Object data, Class clazz) { Configuration cfg = super.createConfiguration(data, ModuleStatusImpl.class); cfg.setClassForTemplateLoading(getClass(),"templates"); cfg.setObjectWrapper( new BeansWrapper() { @Override public TemplateModel wrap(Object obj) throws TemplateModelException { if( obj instanceof List){ List<?> list = (List<?>) obj; SimpleHash hash = new SimpleHash(); hash.put( "values", new CollectionModel( list, new BeansWrapper(){ public TemplateModel wrap(Object object) throws TemplateModelException { if( object instanceof ModuleStatus){ ModuleStatus status = (ModuleStatus) object; SimpleHash hash = new SimpleHash(); hash.put("module", status.getModule() ); hash.put("name", status.getName() ); if (status.getComponent() != null) { hash.put("component", status.getComponent().get()); } if (status.getVersion() != null) { hash.put("version", status.getVersion().get()); } if (status.getMessage() != null) { hash.put("message", status.getMessage().get()); } return hash; } return super.wrap(object); }; }) ); return hash; } return super.wrap(obj); } }); return cfg; }

Target:
protected Configuration createConfiguration(Object data, Class clazz) { Configuration cfg = super.createConfiguration(data, ModuleStatusImpl.class); cfg.setClassForTemplateLoading(getClass(),"templates"); cfg.setObjectWrapper( new BeansWrapper() { @Override public TemplateModel wrap(Object obj) throws TemplateModelException { if( obj instanceof List){ List<?> list = (List<?>) obj; SimpleHash hash = new SimpleHash(); hash.put( "values", new CollectionModel( list, new BeansWrapper(){ public TemplateModel wrap(Object object) throws TemplateModelException { if( object instanceof ModuleStatus){ ModuleStatus status = (ModuleStatus) object; SimpleHash hash = new SimpleHash(); hash.put("module", status.getModule() ); hash.put("name", status.getName() ); status.getComponent().ifPresent(component->{hash.put("component",component);}); status.getVersion().ifPresent(version->{hash.put("version", version);}); status.getMessage().ifPresent(message->{hash.put("message",message);}); return hash; } return super.wrap(object); }; }) ); return hash; } return super.wrap(obj); } }); return cfg; }