Problems serializing a c++\cli vector - xml-serialization

I am trying to serialize a vector of accounts but I keep getting the following exception :-
To be XML serializable, types which inherit from ICollection must have an implementation of Add(Account) at all levels of their inheritance hierarchy. cliext.vector does not implement Add(Account).
I have added an Add(Account) function to my class but it still doesn't work. I'm relatively new to C++ so my code is probably poor or might not be the correct way of doing what I want.
All help appreciated.
here is the main function :-
// TestDotNetXML.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
int main(array<System::String ^> ^args)
{
AccountList^ MyAccountList = gcnew AccountList;
Account^ Account1 = gcnew Account("1","1","1","1");
Account^ Account2 = gcnew Account("2","2","2","2");
Account Account3;
Account3.setAccountName("3");
Account3.setUserName("3");
Account3.setPassword("3");
Account3.setDescription("3");
MyAccountList->Add(Account1);
MyAccountList->Add(Account2);
MyAccountList->Add(Account3);
try
{
XmlSerializer^ x = gcnew XmlSerializer(MyAccountList->GetType());
x->Serialize(Console::Out, MyAccountList);
}
catch(System::InvalidOperationException^ ex)
{
Console::WriteLine(ex->InnerException);
}
Console::WriteLine();
Console::ReadLine();
return 0;
}
The Account class
Account.h
#pragma once
using namespace System;
[Serializable]
public ref class Account
{
public:
String^ accountName;
String^ userName;
String^ password;
String^ description;
public:
Account(String^ accountName, String^ userName, String^ password, String^ description);
Account(void);
Account(const Account% ob);
Account% operator=(const Account% ob);
~Account(void);
String^ getAccountName();
void setAccountName(String^ accountName);
String^ getUserName();
void setUserName(String^ userName);
String^ getPassword();
void setPassword(String^ password);
String^ getDescription();
void setDescription(String^ description);
};
Account.cpp
#include "stdafx.h"
#include "Account.h"
Account::Account(String^ accountName, String^ userName, String^ password, String^ description)
{
this->accountName = gcnew String(accountName);
this->userName = gcnew String(userName);
this->password = gcnew String(password);
this->description = gcnew String(description);
}
Account::Account(void)
{
}
Account::Account(const Account %ob)
{
accountName = ob.accountName;
userName = ob.userName;
password = ob.password;
description = ob.description;
}
Account% Account::operator=(const Account% ob)
{
if(this != %ob)
{
accountName = ob.accountName;
userName = ob.userName;
password = ob.password;
description = ob.description;
}
return *this;
}
Account::~Account(void)
{
this->accountName = gcnew String("");
this->userName = gcnew String("");
this->password = gcnew String("");
this->description = gcnew String("");
}
String^ Account::getAccountName()
{
return this->accountName;
}
void Account::setAccountName(String^ accountName)
{
this->accountName = accountName;
}
String^ Account::getUserName()
{
return this->userName;
}
void Account::setUserName(String^ userName)
{
this->userName = accountName;
}
String^ Account::getPassword()
{
return this->password;
}
void Account::setPassword(String^ password)
{
this->password = password;
}
String^ Account::getDescription()
{
return this->description;
}
void Account::setDescription(String^ description)
{
this->description = description;
}
AccountList.h
#pragma once
#include <cliext/vector>
#include "Account.h"
using namespace cliext;
public ref class AccountList
{
public:
vector<Account^>^ List;
public:
AccountList(void);
void Add(Account^ anAccount);
void Add(Account anAccount);
void Remove(Account^ anAccount);
bool Exists(Account^ anAccount);
Account^ getAccout(String^ accountName);
vector<Account^>^ getList(void);
unsigned int stopLNK2022() { return List->size(); }
};
AccountList.cpp
#include "stdafx.h"
#include "AccountList.h"
#include "Account.h"
AccountList::AccountList(void)
{
List = gcnew vector<Account^>;
}
void AccountList::Add(Account^ anAccount)
{
this->List->push_back(anAccount);
}
void AccountList::Add(Account anAccount)
{
Account^ ptrAccount = gcnew Account(
anAccount.getAccountName(),
anAccount.getUserName(),
anAccount.getPassword(),
anAccount.getDescription()
);
this->List->push_back(ptrAccount);
}
void AccountList::Remove(Account^ anAccount)
{
vector<Account^>::iterator Iter;
for(Iter = List->begin(); Iter != List->end(); Iter++)
{
if((safe_cast<Account^>(*Iter))->getAccountName()
== anAccount->getAccountName())
{
List->erase(Iter);
}
}
}
bool AccountList::Exists(Account^ anAccount)
{
vector<Account^>::iterator Iter;
for(Iter = List->begin(); Iter != List->end(); Iter++)
{
if((safe_cast<Account^>(*Iter))->getAccountName()
== anAccount->getAccountName())
{
return true;
}
}
return false;
}
vector<Account^>^ AccountList::getList(void)
{
return List;
}
Account^ AccountList::getAccout(String^ accountName)
{
vector<Account^>::iterator Iter;
for(Iter = List->begin(); Iter != List->end(); Iter++)
{
String^ test = (safe_cast<Account^>(*Iter))->getAccountName();
if((safe_cast<Account^>(*Iter))->getAccountName()
== accountName)
{
return safe_cast<Account^>(*Iter);
}
}
return nullptr;
}

Related

mybatis interceptor throw Reflection exception affects cpu performence

I had implement a interceptor of myabtis. but we found a problem, execute interceptor lead to throw so many IllegalAccessException, it affects cpu performence
Shown below is where the problem is, why did not check access permision of feild befor executed code "field.get(target)".
public class GetFieldInvoker implements Invoker {
private final Field field;
public GetFieldInvoker(Field field) {
this.field = field;
}
#Override
public Object invoke(Object target, Object[] args) throws IllegalAccessException {
try {
return field.get(target);
} catch (IllegalAccessException e) {
if (Reflector.canControlMemberAccessible()) {
field.setAccessible(true);
return field.get(target);
} else {
throw e;
}
}
}
#Override
public Class<?> getType() {
return field.getType();
}
}
the intercepor of mine:
#Intercepts({
#Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class})
})
public class SqlIdInterceptor implements Interceptor {
private static final int MAX_LEN = 256;
private final RoomboxLogger logger = RoomboxLogManager.getLogger();
#Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
MappedStatement mappedStatement =
(MappedStatement) metaObject.getValue("delegate.mappedStatement");
String id = mappedStatement.getId();
if (id != null) {
int len = id.length();
if (len > MAX_LEN) {
logger.warn("too long id", "id", id, "len", len);
}
}
String newSQL = "# " + id + "\n" + originalSql;
metaObject.setValue("delegate.boundSql.sql", newSQL);
return invocation.proceed();
}
#SuppressWarnings("unchecked")
public static <T> T realTarget(Object target) {
if (Proxy.isProxyClass(target.getClass())) {
MetaObject metaObject = SystemMetaObject.forObject(target);
return realTarget(metaObject.getValue("h.target"));
}
return (T) target;
}
}
Flame Graph
enter image description here
enter image description here
I need help, how to avoid throw exceptions, is any other way to reslove this problem?
thanks.

MVVM AsyncExecute causing lag

AsyncExecute method causing lag in my treeview application when I am expanding a branch.
Important parts of my TreeView
public DirectoryItemViewModel(string fullPath, DirectoryItemType type, long size)
{
this.ExpandCommand = new AsyncCommand(Expand, CanExecute);
this.FullPath = fullPath;
this.Type = type;
this.Size = size;
this.ClearChildren();
}
public bool CanExecute()
{
return !isBusy;
}
public IAsyncCommand ExpandCommand { get; set; }
private async Task Expand()
{
isBusy = true;
if (this.Type == DirectoryItemType.File)
{
return;
}
List<Task<long>> tasks = new();
var children = DirectoryStructure.GetDirectoryContents(this.FullPath);
this.Children = new ObservableCollection<DirectoryItemViewModel>(
children.Select(content => new DirectoryItemViewModel(content.FullPath, content.Type, 0)));
//If I delete the remaining part of code in this method everything works fine,
in my idea it should output the folders without lag, and then start calculating their size in other threads, but it first lags for 1-2 sec, then output the content of the folder, and then start calculating.
foreach (var item in children)
{
if (item.Type == DirectoryItemType.Folder)
{
tasks.Add(Task.Run(() => GetDirectorySize(new DirectoryInfo(item.FullPath))));
}
}
var results = await Task.WhenAll(tasks);
for (int i = 0; i < results.Length; i++)
{
Children[i].Size = results[i];
}
isBusy = false;
}
My command Interface and class
public interface IAsyncCommand : ICommand
{
Task ExecuteAsync();
bool CanExecute();
}
public class AsyncCommand : IAsyncCommand
{
public event EventHandler CanExecuteChanged;
private bool _isExecuting;
private readonly Func<Task> _execute;
private readonly Func<bool> _canExecute;
public AsyncCommand(
Func<Task> execute,
Func<bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute()
{
return !_isExecuting && (_canExecute?.Invoke() ?? true);
}
public async Task ExecuteAsync()
{
if (CanExecute())
{
try
{
_isExecuting = true;
await _execute();
}
finally
{
_isExecuting = false;
}
}
RaiseCanExecuteChanged();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
void ICommand.Execute(object parameter)
{
//I suppose that here is the problem cause IDE is hinting me that I am not awaiting here, but I don't know how to change it if it is.
ExecuteAsync();
}
}

Dynamic styling with IceFaces: how can I change the color of the outputText at the time of rendering?

I'm new to ICEFaces and I have to maintain someone else's code. I'm working on a web chat where the user can send and receive messages. I would like the messages to have different colors depending on whether they were sent by the user or by someone else.
I currently have the following code in my xhtml file:
<h:dataTable id="history" value="#{chatBean.messages}" var="message" border="0" align="left" style="width: 100%" >
<h:column width="590" height="25" align="left" valign="bottom" >
<h:outputText value="#{message}" styleClass="#{chatBean.messageColor}" />
</h:column>
</h:dataTable>
This shows all messages sent and received, but all with the same color, even though the messageColor property of the chat bean changes: I did an experiment and appended the result of getMessageColor() at the end of each message and it does change, but the text is still rendered in the same color.
The CSS has the following classes (among others):
.class1
{
color:#818181;
width: 100%;
font-size: 15px;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
}
.class2
{
color:#00657c;
width: 100%;
font-size: 15px;
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
}
Here's the code for the ChatBean class:
#ManagedBean(name = "chatBean")
#SessionScoped
public class ChatBean implements Serializable {
private static final long serialVersionUID = -12636320254821872L;
private static final String PUSH_GROUP = "chatPage";
private PortableRenderer renderer;
private String message;
private String lastMessageSent = "";
private Date lastMessageTime = new Date();
private String isDown = "false";
private List<String> messages = new ArrayList<String>();
private String buttonDisabled = "true";
private String buttonCancelDisabled = "true";
private String pollDisabled = "false";
private String id = "";
private ChatClient chat;
private Timer timer = new Timer();
private String messageColor;
public class ChatThread extends Thread implements Serializable {
private static final long serialVersionUID = -7636532554421738019L;
private Map<String, String> data;
private String mail;
public ChatThread(final Map<String, String> data, final String mail) {
this.data = data;
this.mail = mail;
}
#Override
public void run() {
chat = new ChatClient(new ChatClient.Event() {
#Override
public void handle(String msg) {
if(msg != null && msg.length() > 0)
pushMessage(msg);
}
#Override
public void agentConnected(String msg) {
buttonDisabled = "false";
buttonCancelDisabled = "false";
pushMessage(msg);
}
#Override
public void agentDisconnected(String msg) {
buttonDisabled = "true";
pushMessage(msg);
try {
timer.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
});
chat.login(mail, data);
chat.join(mail, data.get("partner"), data.get("business"));
timer.scheduleAtFixedRate(new RefreshTimerTask(), 0, 1000);
}
}
public class RefreshTimerTask extends TimerTask implements Serializable {
private static final long serialVersionUID = 1852678537009150141L;
public void run() {
chat.refresh();
}
}
public ChatBean() {
if(getSession() != null) {
id = getSession().getId();
PushRenderer.addCurrentSession(PUSH_GROUP + id);
renderer = PushRenderer.getPortableRenderer();
setMessageColor("class1");
Log.getLogger().debug("New chat bean.");
if(getData().containsKey("login_chat")) {
ChatThread chat = new ChatThread(getData(), getSessionAttribute(GenesysSingleton.getInstance().getConfigApp().getDisplayName(), "<mail>"));
chat.start();
}
}
}
private void pushMessage(String msg) {
if(msg != null && !msg.isEmpty()) {
ChatBean.this.isDown = "true";
messages.add(msg);//Acá se puede acceder a textColor.
try {
PushRenderer.render(PUSH_GROUP + id);
} catch (Exception e) {
renderer.render(PUSH_GROUP + id);
}
setMessageColor("class1");
}
}
private String getSessionAttribute(String key, String ref) {
Object value = getSession().getAttribute(key);
return value != null ? value.toString() : ref;
}
private Map<String, String> getData() {
Map<String, String> data = new HashMap<String, String>();
HttpSession session = getSession();
#SuppressWarnings("rawtypes")
Enumeration enums = session.getAttributeNames();
while(enums.hasMoreElements()) {
String key = enums.nextElement().toString();
if(!"com.sun.faces.application.view.activeViewMaps".equals(key)
&& !"com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap".equals(key)
&& !"javax.faces.request.charset".equals(key))
data.put(key, session.getAttribute(key).toString());
}
return data;
}
public void sendMessage(ActionEvent event) {
sendMessage();
}
protected synchronized void sendMessage() {
if (message != null && !message.trim().isEmpty()){
Date now = new Date();
//No permito mandar el mismo mensaje 2 veces seguidas en un intervalo menor a un segundo.
message = message.trim();
if (message.equals(lastMessageSent)&&(now.getTime()<(1000+lastMessageTime.getTime()))){
message = null;
}
else{
setMessageColor("class2");
lastMessageSent = message;
message = null;
lastMessageTime = new Date();
chat.refresh(lastMessageSent);
}
}
}
public String disconnect() {
pollDisabled = "true";
return "login";
}
public void sendClose(ActionEvent event) {
}
public void receiveMessage() {
}
#PreDestroy
public void destroy() {
buttonDisabled = "true";
try {
//pushMessage(SISTEMA_3);
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
};
System.out.println(id + "- ssssssss");
try {
timer.cancel();
} catch (Exception e) {
}
chat.logout();
chat.close();
}
private HttpSession getSession() {
return (HttpSession) getContext().getSession(false);
}
private ExternalContext getContext() {
return getFacesContext().getExternalContext();
}
private FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getButtonDisabled() {
return buttonDisabled;
}
public void setButtonDisabled(String buttonDisabled) {
this.buttonDisabled = buttonDisabled;
}
public List<String> getMessages() {
try {
JavascriptContext.addJavascriptCall(getFacesContext(), "document.getElementById('scrollDataTable').scrollIntoView();");
} catch (Exception e) {
e.printStackTrace();
}
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
public String getPollDisabled() {
return pollDisabled;
}
public void setPollDisabled(String pollDisabled) {
this.pollDisabled = pollDisabled;
}
public String getButtonCancelDisabled() {
return buttonCancelDisabled;
}
public void setButtonCancelDisabled(String buttonCancelDisabled) {
this.buttonCancelDisabled = buttonCancelDisabled;
}
public String getIsDown() {
return isDown;
}
public void setIsDown(String isDown) {
this.isDown = isDown;
}
public String getMessageColor() {
return messageColor;
}
public void setMessageColor(String textColor) {
this.messageColor = textColor;
}
}
All help will be appreciated. Thank you in advance.
One possible way which I have changed css dynamically depending on a bean property is through using the styleClass attribute of the <h:outputText>.
In your css file define two varying classes such as
.class1
{
color:red; //Put your colour here (#818181)
}
.class2
{
color:green; //Put your colour here (#00657c)
}
Then in your java bean code you could declare a String field with getters and setters such as
private String messageColor;
Then in your code where you do
setTextColor(COLOR_AGENTE);
You can change this to the class which you would like to change the text to such as:
setMessageColor("class1");
Then on your <h:outputText> attach
styleClass="#{chatBean.messageColor}"
This should hopefully work;
Due to my original suggestion not working, you could try this.
Remove private String messageColor; from you chatBean and the getters/setters along with any calls to setMessageColor("class1");.
But keep the two classes in your css.
Now declare a boolean property with getters and setters in your chatBean:
private boolean colourAgente;
Declare a method:
public String setColor() {
if (colourAgente) {
return "class1";
} else {
return "class2";
}
}
Then in your xhtml change the styleClass attribute to:
styleClass="#{chatBean.setColor()}"
Finally, in your java code change:
setMessageColor("class1");
to either colourAgente = true; or colourAgente=false; depending on what colour you want to set.
I finally did it, but I had to use an ugly JavaScript workaround. That is, I'm now running this script every time the chat is refreshed:
function updateColors(){
var username = document.getElementById("form:username").value;
if (username.length > 0){
var x = document.getElementsByClassName("class1");
if (x != null){
for (i = 0; i < x.length; i++){
if (x[i].innerHTML.indexOf(username) === 0){
x[i].className = "class2";
}
}
}
}
}
Anyway, thanks for your help, LiamWilson94. I still don't know what part of the code I'm working with makes it so that your answers don't work, but you have given me a lot of insight which helped me arrive to this "solution", and I have learnt a few things about IceFaces in the process.
OK, I have found a better solution.
I created a TextModel class:
import java.io.Serializable;
public class TextModel implements Serializable {
private static final long serialVersionUID = -8470475291191399871L;
private String text;
private String clase;
public TextModel() {
}
public TextModel(String text, String clase) {
this.text = text;
this.clase = clase;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getClase() {
return clase;
}
public void setClase(String clase) {
this.clase = clase;
}
public String toString() {
return text;
}
}
Then I changed messages in ChatBean from List to List, and changed the following functions in ChatBean.java:
private void pushMessage(String msg) {
if(msg != null && !msg.isEmpty()) {
ChatBean.this.isDown = "true";
messages.add(new TextModel(msg,clase));
try {
PushRenderer.render(PUSH_GROUP + id);
} catch (Exception e) {
renderer.render(PUSH_GROUP + id);
}
clase = "class1";
}
}
protected synchronized void sendMessage() {
if (message != null && !message.trim().isEmpty()){
Date now = new Date();
message = message.trim();
if (message.equals(lastMessageSent)&&(now.getTime()<(1000+lastMessageTime.getTime()))){
message = null;
}
else{
clase = "class2";
lastMessageSent = message;
message = null;
lastMessageTime = new Date();
chat.refresh(lastMessageSent);
}
}
}
Where clase is either "class1" or "class2" (could be neater, but it works for now, I can always make it neater later).
Finally, on chat.xhtml, I changed the outputtext tag to:
<h:outputText value="#{message.text}" styleClass="#{message.clase}" />
That's it. No more messy JavaScript patches.
The trick was making the class a property of the message itself rather than the ChatBean.
I hope this helps someone else in the future.

Jenkins plugin development - persistence

I'm still learning plugin dev. This is my first one.
I would like to persist the configuration of my plugin, but it won't work.
Could you please tell me, what am I doing wrong?
I have tried debuging the process, starting from the addition of the plugin to the job 'til the saving of the job config.
I have found, that inside the load() method of the descriptor, no xml file is found!
The path it is looking for is something like: c:\users\Peter\workspace\r-script.\work\whatEverDir\xy.xml
I don't think that the .\ part is causing the config file not to be found, but since it is a Jenkins class generating this path, I would not bet on it. Although the system might have tried to create it here at the first place.
Thanks in advance!
Scriptrunner.jelly
<f:block>
<f:entry title="RScript" field="command">
<f:textarea style="width:99%" />
</f:entry>
</f:block>
<f:entry field="installedPackages" title="Installed packages">
<f:select style="width:40%" />
</f:entry>
<f:entry field="mirrors" title="Choose a mirror">
<f:select style="width:40%" />
</f:entry>
<f:entry>
<f:repeatableProperty field="availablePackages" minimum="1"/>
</f:entry>
AvailablePackage.jelly
<f:entry field="availablePackages">
<f:select style="width:40%" />
<f:repeatableDeleteButton />
</f:entry>
ScriptRunner.java
public class ScriptRunner extends Builder {
private static final String fileExtension = ".R";
private ArrayList<AvailablePackage> availablePackages;
private String command;
private String chosenMirror;
private List<String> mirrorList = new ArrayList<String>();
#DataBoundConstructor
public ScriptRunner(String command, ArrayList<String> installedPackages, ArrayList<String> mirrors, ArrayList<AvailablePackage> availablePackages) {
this.chosenMirror = mirrors.get(0);
this.availablePackages = availablePackages;
this.command = command;
}
public final String getCommand() {
return command;
}
#Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
BuildListener listener) throws InterruptedException {
return perform(build, launcher, (TaskListener) listener);
}
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
TaskListener listener) throws InterruptedException {
FilePath workSpace = build.getWorkspace();
FilePath rScript = null;
if (workSpace == null) {
try {
throw new NoSuchFileException("Workspace could not be set!");
} catch (NoSuchFileException e) {
e.printStackTrace();
}
}
try {
try {
String fullScript;
if (command.contains("options(repos=structure(")) {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, "", command);
} else {
fullScript = PackagesManager.singleton().createFullScript(availablePackages, chosenMirror, command);
}
rScript = workSpace.createTextTempFile("RScriptTemp",
getFileExtension(), fullScript, false);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToProduceScript()));
return false;
}
boolean successfullyRan = false;
try {
EnvVars envVars = build.getEnvironment(listener);
for (Map.Entry<String, String> e : build.getBuildVariables()
.entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
if (launcher.launch().cmds(buildCommandLine(rScript))
.envs(envVars).stdout(listener).pwd(workSpace).join() == 1) {
successfullyRan = true;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_CommandFailed()));
}
return successfullyRan;
} finally {
try {
if (rScript != null) {
rScript.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
} catch (Exception e) {
e.printStackTrace(listener.fatalError(Messages
.CommandInterpreter_UnableToDelete(rScript)));
}
}
}
public String[] buildCommandLine(FilePath script) {
return new String[] { "Rscript", script.getRemote() };
}
protected String getFileExtension() {
return fileExtension;
}
public List<String> getMirrorList() {
return mirrorList;
}
public void setMirrorList(List<String> mirrorList) {
this.mirrorList = mirrorList;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
public ArrayList<AvailablePackage> getAvailablePackages() {
return availablePackages;
}
#Override
public ScriptBuildStepDescriptorImplementation getDescriptor() {
return (ScriptBuildStepDescriptorImplementation)super.getDescriptor();
}
#Extension
public static class ScriptBuildStepDescriptorImplementation extends
BuildStepDescriptor<Builder> {
private boolean showInstalled;
private String command;
private String chosenMirror;
private ArrayList<AvailablePackage> availablePackages;
public ScriptBuildStepDescriptorImplementation() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
#Override
public String getDisplayName() {
return "Advanced R script runner";
}
#Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
public ListBoxModel doFillInstalledPackagesItems() {
ListBoxModel mirrors = new ListBoxModel();
Set<String> mirrorsList = PackagesManager.singleton()
.getInstalledPackages();
for (String entry : mirrorsList) {
mirrors.add(entry);
}
return mirrors;
}
public ListBoxModel doFillAvailablePackagesItems() {
ListBoxModel packages = new ListBoxModel();
List<String> packageList = PackagesManager.singleton().getAvailablePackages();
Set<String> alreadyInstalled = PackagesManager.singleton().getInstalledPackages();
for (String entry : packageList) {
if (!alreadyInstalled.contains(entry)) {
packages.add(entry);
}
}
return packages;
}
public ListBoxModel doFillMirrorsItems() {
ListBoxModel mirrors = new ListBoxModel();
String[] mirrorsList = MirrorManager.singleton().getMirrors();
int selected = 34;
for (int i = 0; i < mirrorsList.length; i++) {
String[] splitCurrent = mirrorsList[i].split(" - ");
if (chosenMirror != null && chosenMirror.equals(splitCurrent[1])) {
selected = i;
}
mirrors.add(splitCurrent[1], splitCurrent[0]);
}
mirrors.get(selected).selected = true;
return mirrors;
}
public boolean getShowInstalled() {
return showInstalled;
}
public void setShowInstalled(boolean showInstalled) {
this.showInstalled = showInstalled;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getChosenMirror() {
return chosenMirror;
}
public void setChosenMirror(String chosenMirror) {
this.chosenMirror = chosenMirror;
}
}
}
AvailablePackage.java
public class AvailablePackage extends AbstractDescribableImpl<AvailablePackage> {
private String name;
#DataBoundConstructor
public AvailablePackage(String availablePackages) {
this.name = availablePackages;
}
public String getName() {
return name;
}
#Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
#Extension
public static class DescriptorImpl extends Descriptor<AvailablePackage> {
private String name;
public DescriptorImpl() {
load();
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
public ListBoxModel doFillAvailablePackagesItems() {
return PackagesManager.singleton().getAvailablePackagesAsListBoxModel(name);
}
#Override
public String getDisplayName() {
return "";
}
public String getName() {
return name;
}
}
}
Sorry for the code formatting! First timer at stackoverflow code posting.
I think you may need to comment this line out
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
req.bindJSON(this, formData);
save();
//return super.configure(req,formData);
return true;
}
as it will then save again but with no fields.
A good place to locate Jenkins plugin examples is in https://github.com/jenkinsci

Why is PERSON not a ref class?

I don't understand why compiler thinks PERSON is NOT a ref class:
: error C2811: 'Runner' : cannot
inherit from 'Person', a ref class can
only inherit from a ref class or
interface class
I tried....
adding mscorlib.dll to the header files: #using..etc...<> - didn't work.
making Person an abstract class - didn't work (Im glad since I imagined that to be a instantiatable?? class)
I list the two header files first. Then their cose is listed later if you need it.
PERSON.H
#pragma once
using namespace System;
ref class Person
{
private:
void copy_ptr_data(Person%);
void delete_ptr_data(void);
public:
property String^ Name;
property String^ Age;
Person(String^ name, String^ age);
Person(Person%);
Person% operator= (Person%);
bool operator==(Person%);
bool operator!=(Person%);
virtual ~Person(void);
};
RUNNER.H
#pragma once
#include "Person.h"
using namespace System;
ref class Runner : public Person
{
private:
void copy_ptr_data(Runner%);
void delete_ptr_data(void);
public:
property String^ Time;
property String^ Rank;
Runner(String^ name, String^ age, String^ time);
Runner(Runner%);
Runner% operator= (Runner%);
bool operator==(Runner%);
bool operator!=(Runner%);
~Runner(void);
};
PERSON.CPP
#include "StdAfx.h"
#include "Person.h"
Person::Person(String^ name, String^ age)
{
Name = name;
Age = age;
}
Person::Person(Person% p)
{
Name = p.Name;
Age = p.Age;
copy_ptr_data(p);
}
Person% Person::operator= (Person% p)
{
// prevent self-assignment
if (this == %p) {
return *this;
}
// deallocate/reallocate/assign dynamic memory
delete_ptr_data();
copy_ptr_data(p);
// assign non-dynamic memory
Name = p.Name;
Age = p.Age;
return *this;
}
bool Person::operator==(Person% p)
{
if ((Name == p.Name) &&
(Age == p.Age))
return 1;
return 0;
}
bool Person::operator!=(Person% p)
{
return !(Person::operator==(p));
}
Person::~Person(void)
{
delete_ptr_data();
}
void Person::copy_ptr_data(Person% p)
{
return;
}
void Person::delete_ptr_data()
{
return;
}
RUNNER.CPP
#include "StdAfx.h"
#include "Runner.h"
Runner::Runner(String^ name, String^ age, String^ time) : Person(name, age)
{
Time = time;
Rank = nullptr;
}
Runner::Runner(Runner% r) : Person(r)
{
Time = r.Time;
Time = r.Rank;
copy_ptr_data(r);
}
Runner% Runner::operator= (Runner% r)
{
// handle self assignment
if (this == %r) return *this;
// handle base class portion
Person::operator=(r);
// handle dynamic portion
delete_ptr_data();
copy_ptr_data(r);
// handle non-dynamic portion
Time = r.Time;
Rank = r.Rank;
return *this;
}
bool Runner::operator==(Runner% r)
{
if ((Person::operator==(r)) &&
(Time == r.Time) &&
(Rank == r.Rank))
return 1;
return 0;
}
bool Runner::operator!=(Runner% r)
{
return !(Runner::operator==(r));
}
Runner::~Runner(void)
{
}
void Runner::copy_ptr_data(Runner% r)
{
return;
}
void Runner::delete_ptr_data()
{
return;
}
Shouldn't you be putting:
#using <mscorlib.dll>
at the top of your header files? I'm not sure if that would fix the issue to be honest.
Try making your Person class abstract.