I am new to Struts2. I am unable to get file name and path. Kindly help any one.
import java.io.File;
import java.util.ResourceBundle;
import org.apache.commons.io.FileUtils;
import nre.dao.DBconnection;
import com.mysql.jdbc.Connection;
import com.opensymphony.xwork2.ActionSupport;
public class AddProperty extends ActionSupport
{
private String propertyid;
private String propertyname;
private String country;
private String state;
private String city;
private String description;
private File uploadphoto;
private String photofiletype;
private String photoname;
public String getPropertyid()
{
return propertyid;
}
public void setPropertyid(String propertyid)
{
this.propertyid = propertyid;
}
public String getPropertyname()
{
return propertyname;
}
public void setPropertyname(String propertyname)
{
this.propertyname = propertyname;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public File getUploadphoto()
{
return uploadphoto;
}
public void setUploadphoto(File uploadphoto)
{
this.uploadphoto = uploadphoto;
}
public String getPhotofiletype() {
return photofiletype;
}
public void setPhotofiletype(String photofiletype) {
this.photofiletype = photofiletype;
}
public String getPhotoname() {
return photoname;
}
public void setPhotoname(String photoname) {
this.photoname = photoname;
}
public String execute(){
DBconnection connection=new DBconnection();
connection.getConnection();
try{
String filepath=connection.filepath;
System.out.println("filepath : : "+filepath);
System.out.println("photoname : : "+photoname);
if(filepath!=null && photoname!=null){
File filetocreate=new File(filepath,photoname);
FileUtils.copyFile(uploadphoto, filetocreate);
}
}catch(Exception e){
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
String query ="insert into addproperty(propertyid,propertyname,propertycity,propertystate,propertycountry,addedby,addeddate,removeddate) values ('"+propertyid+"','"+propertyname+"','"+city+"','"+state+"','"+country+"','Parthi',now(),NULL)";
connection.executeUpdate(query);
System.out.println("Completed Inserting");
return SUCCESS;
//System.out.println("Class completed");
}
}
Action class should have the following three properties.
• [inputName]File
• [inputName]FileName
• [inputName]ContentType
[inputName] is the name of the file tag(s) on the JSP. For example, if the file tag's name is uploadphoto, the properties will be as follows:
• File uploadphotoFile
• String uploadphotoFileName
• String uploadphotoContentType
String filePath = servletRequest.getRealPath("/");
File fileToCreate = new File(filePath, this.uploadphotoFileName);
FileUtils.copyFile(this.uploadphotoFile, fileToCreate);
Related
I’m working on upgrading our application vaadin version from 7.7.24 to 8.13.3. We’ve completed all the dependency issues and i’m able to start the application in locally.
We have a textbox that is showing up the Event data.
Here is the class file that i'm using:
#Entity
#Table(name = "changelog")
public class ChangelogEvent extends BaseEntity
{
#Column(name = "remote_ip")
private String remoteIp;
#Column(name = "remote_host")
private String remoteHost;
#Column(name = "event")
#Enumerated(EnumType.ORDINAL)
private ChangelogEventType eventType;
#Column(name = "entity_type")
private String entityType;
public ChangelogEvent()
{
}
public ChangelogEvent(String remoteIp, String remoteHost, ChangelogEventType eventType)
{
this.remoteIp = remoteIp;
this.remoteHost = remoteHost;
this.eventType = eventType;
}
public String getRemoteIp()
{
return remoteIp;
}
public void setRemoteIp(String remoteIp)
{
this.remoteIp = remoteIp;
}
public ChangelogEventType getEventType()
{
return eventType;
}
public void setEventType(ChangelogEventType eventType)
{
this.eventType = eventType;
}
public String getRemoteHost()
{
return remoteHost;
}
public void setRemoteHost(String remoteHost)
{
this.remoteHost = remoteHost;
}
public String getEntityType()
{
return entityType;
}
public void setEntityType(String entityType)
{
this.entityType = entityType;
}
}
And here is my ChangelogEventType.java file that defined ChangelogEventType enum:
public enum ChangelogEventType
{
CREATED("Created"),
UPDATED("Updated"),
DELETED("Deleted"),
LOGIN("Login"),
LOGOUT("Logout"),
LOGIN_RETRY("Login Retry"),
ACCOUNT_LOCKED("Account Locked"),
PASSWORD_EXPIRED("Password Expired"),
PASSWORD_CHANGED("Password Changed");
private String text;
ChangelogEventType(String text)
{
this.text = text;
}
public String getText()
{
return text;
}
public static ChangelogEventType fromString(String text)
{
if (text != null)
{
for (ChangelogEventType event : ChangelogEventType.values())
{
if (text.equalsIgnoreCase(event.text))
{
return event;
}
}
}
return null;
}
}
Here is the code that i'm using for binding the values into textfield.
eventType = createTextField("Event", COLUMN_WIDTH);
binder.forField(eventType)
.withNullRepresentation("None")
.bind(ChangelogEvent::getEventType, ChangelogEvent::setEventType);
Is there any way to bind the Enum to textbox ?
You need to write custom converter and use it in Binder using withConverter method, in your case something like:
class StringToChangelogEventTypeConverter implements Converter<String, ChangelogEventType> {
#Override
public Result<ChangelogEventType> convertToModel(String fieldValue, ValueContext context) {
// Produces a converted value or an error
ChangelogEventType event = ChangelogEventType.fromString(fieldValue);
if (event != null) {
// ok is a static helper method that creates a Result
return Result.ok(ChangelogEventType.fromString(fieldValue));
} else {
// error is a static helper method that creates a Result
return Result.error("Please enter a number");
}
}
#Override
public String convertToPresentation(ChangelogEventType event, ValueContext context) {
// Converting to the field type should always succeed,
// so there is no support for returning an error Result.
return event.getText();
}
}
I am trying to get the following to be inserted into firebase but read that we can only store one information at a time? I thought that we can somehow store multiple information under a single unique id? Below is the code and I am trying to insert information such as phone numbers, address etc. With the address, can we use a string for the whole address or must we break it down to integer plus string? Also, should i be using "long" for phone number? I am also not sure if I should be using multiple Firebasedatabase for this?
public class MainActivity extends AppCompatActivity {
private Button logout;
private EditText edit;
private EditText number;
private EditText address;
private EditText phone;
private EditText postcode;
private Button add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logout = findViewById(R.id.logout);
edit = findViewById(R.id.edit);
add = findViewById(R.id.add);
number = findViewById(R.id.number);
address = findViewById(R.id.address);
phone = findViewById(R.id.phone);
postcode = findViewById(R.id.postcode);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Toast.makeText(MainActivity.this, "Logged Out", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, StartActivity.class));
finish();
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_name = edit.getText().toString();
// int txtnumber = Integer.valueof(number);
String txt_address = address.getText().toString();
// Long phone_number = Long.parseLong(phone.getText().toString().trim());
// Long postcode2 = Long.parseLong(postcode.getText().toString().trim());
if (txt_name.isEmpty()) {
Toast.makeText(MainActivity.this, "No name entered!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child("Medical Clinic").push().child("Name").setValue(txt_name, txt_address);
// FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child("Medical Clinic").setValue(txt_address);
// FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child("Medical Clinic").child("Name:").child("Address No:").child("Address Name:").setValue(txt_address);
// FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child("Medical Clinic").child("Name:").child("Address No:").child("Address Name").child("Phone number:").setValue(phone_number);
// FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child("Medical Clinic").child("Name:").child("Address No:").child("Address Name").child("Phone number:").child("Postcode:").setValue(postcode2);
}
}
});
}
}
Create a class named Info
public class Info {
private String name;
private String address;
private String phoneNo;
private String postcode;
public Info(String name, String address, String phoneNo, String postcode) {
this.name = name;
this.address = address;
this.phoneNo = phoneNo;
this.postcode = postcode;
}
public Info() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
}
then in your activity
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_name = edit.getText().toString();
// int txtnumber = Integer.valueof(number);
String txt_address = address.getText().toString();
// Long phone_number = Long.parseLong(phone.getText().toString().trim());
// Long postcode2 = Long.parseLong(postcode.getText().toString().trim());
if (txt_name.isEmpty()) {
Toast.makeText(MainActivity.this, "No name entered!", Toast.LENGTH_SHORT).show();
} else {
String key = FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child("Medical Clinic").push().getKey();
Info info = new Info(name,String.valueOf(txtnumber),String.valueOf(phone_number),String.valueOf(postcode2));
FirebaseDatabase.getInstance("https://medical-review-in-australia.firebaseio.com/").getReference().child(key).setValue(info);
});
Hi I am new to richfaces picklist , My scenario is to load hashmap and by selecting the key value i need to load it in picklist. After getting the key i need to generate dynamic jasper report. My problem is while try to load the map value i end up with Typecast exception with the examples i came accross.
<rich:pickList id="pickList1" value="#{xxx.selectionBean.fieldNameList}" sourceCaption="Fields to be Selected for Report"
targetCaption="Selected Fields for Report" listWidth="165px" listHeight="100px" orderable="true" converter="pickListConvertor">
<f:selectItems value="#{xxx.commencementworkBean.commencementList}" var="s"
itemLabel="#{s.key}" itemValue="#{s.value}" />
<f:converter converterId="pickListConvertor" />
</rich:pickList>
SelectionBean
package xxx.xxx.xxx.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class SelectionBean implements Serializable{
/**
vs00324258
*/
private static final long serialVersionUID = -1597587007448113972L;
private String key;
private String value;
List<SelectionBean> fieldNameList = new ArrayList<SelectionBean>();
List<SelectionBean> dynamicList = new ArrayList<SelectionBean>();
List<Object> fieldList = new ArrayList<Object>();
public List<SelectionBean> getFieldNameList() {
return fieldNameList;
}
public void setFieldNameList(List<SelectionBean> fieldNameList) {
this.fieldNameList = fieldNameList;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<SelectionBean> getDynamicList() {
return dynamicList;
}
public void setDynamicList(List<SelectionBean> dynamicList) {
this.dynamicList = dynamicList;
}
public List<Object> getFieldList() {
return fieldList;
}
public void setFieldList(List<Object> fieldList) {
this.fieldList = fieldList;
}
}
PicklistConvertor
#FacesConverter(value = "pickListConvertor")
public class PickListConvertor implements Converter{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if(submittedValue.trim().equals("")){
return null;
}else{
return submittedValue.toString();
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
return String.valueOf(((SelectionBean) value));
}
}
}
CommencementWorkBean
public class CommencementworkBean implements Serializable{
/**
vs00324258
*/
private static final long serialVersionUID = -5020735931910106047L;
private String agreementnum;
private String agreementtype;
private String authorityentering;
private String contractorname;
private String tendercalledbyoffice;
private Date dateofagreemtn;
private Date dateofcommofwork;
private Date dateofintendedcompl;
private Date tenderdate;
private Date duedateofmeterialworks;
private Date regdateofcontract;
private String detailsofsecurdeposit;
private String estamtsanctionno;
private String estimateamt;
private String isitlowest;
private String nameofwork;
private String orignalorsupplemental;
private String pricevariationapplicable;
private String reasonforlowest;
private String regnumberofvendor;
private String remarks;
private String taxes;
private String statusCode;
private String tenderauthority;
private String tenderpremium;
private String validityofsecurdeposit;
private String valueofcontract;
private String worldbankapproval;
private boolean searchCommTableEnabled = false;
private String fieldName;
private Map<String,Object> commencementList = new TreeMap<String, Object>();
private String headerName;
private String valueName;
private List<CommencementworkBean>searchCommencementBeanList = new ArrayList<CommencementworkBean>();
public String getAgreementnum() {
return agreementnum;
}
public void setAgreementnum(String agreementnum) {
this.agreementnum = agreementnum;
}
public String getAgreementtype() {
return agreementtype;
}
public void setAgreementtype(String agreementtype) {
this.agreementtype = agreementtype;
}
public String getAuthorityentering() {
return authorityentering;
}
public void setAuthorityentering(String authorityentering) {
this.authorityentering = authorityentering;
}
public String getContractorname() {
return contractorname;
}
public void setContractorname(String contractorname) {
this.contractorname = contractorname;
}
public String getTendercalledbyoffice() {
return tendercalledbyoffice;
}
public void setTendercalledbyoffice(String tendercalledbyoffice) {
this.tendercalledbyoffice = tendercalledbyoffice;
}
public Date getDateofagreemtn() {
return dateofagreemtn;
}
public void setDateofagreemtn(Date dateofagreemtn) {
this.dateofagreemtn = dateofagreemtn;
}
public Date getDateofcommofwork() {
return dateofcommofwork;
}
public void setDateofcommofwork(Date dateofcommofwork) {
this.dateofcommofwork = dateofcommofwork;
}
public Date getDateofintendedcompl() {
return dateofintendedcompl;
}
public void setDateofintendedcompl(Date dateofintendedcompl) {
this.dateofintendedcompl = dateofintendedcompl;
}
public Date getTenderdate() {
return tenderdate;
}
public void setTenderdate(Date tenderdate) {
this.tenderdate = tenderdate;
}
public Date getRegdateofcontract() {
return regdateofcontract;
}
public void setRegdateofcontract(Date regdateofcontract) {
this.regdateofcontract = regdateofcontract;
}
public String getDetailsofsecurdeposit() {
return detailsofsecurdeposit;
}
public void setDetailsofsecurdeposit(String detailsofsecurdeposit) {
this.detailsofsecurdeposit = detailsofsecurdeposit;
}
public String getEstamtsanctionno() {
return estamtsanctionno;
}
public void setEstamtsanctionno(String estamtsanctionno) {
this.estamtsanctionno = estamtsanctionno;
}
public String getEstimateamt() {
return estimateamt;
}
public void setEstimateamt(String estimateamt) {
this.estimateamt = estimateamt;
}
public String getIsitlowest() {
return isitlowest;
}
public void setIsitlowest(String isitlowest) {
this.isitlowest = isitlowest;
}
public String getNameofwork() {
return nameofwork;
}
public void setNameofwork(String nameofwork) {
this.nameofwork = nameofwork;
}
public String getOrignalorsupplemental() {
return orignalorsupplemental;
}
public void setOrignalorsupplemental(String orignalorsupplemental) {
this.orignalorsupplemental = orignalorsupplemental;
}
public String getPricevariationapplicable() {
return pricevariationapplicable;
}
public void setPricevariationapplicable(String pricevariationapplicable) {
this.pricevariationapplicable = pricevariationapplicable;
}
public String getReasonforlowest() {
return reasonforlowest;
}
public void setReasonforlowest(String reasonforlowest) {
this.reasonforlowest = reasonforlowest;
}
public String getRegnumberofvendor() {
return regnumberofvendor;
}
public void setRegnumberofvendor(String regnumberofvendor) {
this.regnumberofvendor = regnumberofvendor;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getTaxes() {
return taxes;
}
public void setTaxes(String taxes) {
this.taxes = taxes;
}
public String getTenderauthority() {
return tenderauthority;
}
public void setTenderauthority(String tenderauthority) {
this.tenderauthority = tenderauthority;
}
public String getTenderpremium() {
return tenderpremium;
}
public void setTenderpremium(String tenderpremium) {
this.tenderpremium = tenderpremium;
}
public String getValidityofsecurdeposit() {
return validityofsecurdeposit;
}
public void setValidityofsecurdeposit(String validityofsecurdeposit) {
this.validityofsecurdeposit = validityofsecurdeposit;
}
public String getValueofcontract() {
return valueofcontract;
}
public void setValueofcontract(String valueofcontract) {
this.valueofcontract = valueofcontract;
}
public String getWorldbankapproval() {
return worldbankapproval;
}
public void setWorldbankapproval(String worldbankapproval) {
this.worldbankapproval = worldbankapproval;
}
public Date getDuedateofmeterialworks() {
return duedateofmeterialworks;
}
public void setDuedateofmeterialworks(Date duedateofmeterialworks) {
this.duedateofmeterialworks = duedateofmeterialworks;
}
public boolean isSearchCommTableEnabled() {
return searchCommTableEnabled;
}
public void setSearchCommTableEnabled(boolean searchCommTableEnabled) {
this.searchCommTableEnabled = searchCommTableEnabled;
}
public List<CommencementworkBean> getSearchCommencementBeanList() {
return searchCommencementBeanList;
}
public void setSearchCommencementBeanList(
List<CommencementworkBean> searchCommencementBeanList) {
this.searchCommencementBeanList = searchCommencementBeanList;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getHeaderName() {
return headerName;
}
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
public String getValueName() {
return valueName;
}
public void setValueName(String valueName) {
this.valueName = valueName;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Map<String, Object> getCommencementList() {
return commencementList;
}
public void setCommencementList(Map<String, Object> commencementList) {
this.commencementList = commencementList;
}
}
What should i do to get key and value from the selection list.
Exception
java.lang.String cannot be cast to xxx.xxx.xxx.bean.SelectionBean
java.lang.ClassCastException: java.lang.String cannot be cast to xxx.xxx.xxx.bean.SelectionBean
at org.gov.tnwrd.utils.PickListConvertor.getAsString(PickListConvertor.java:26)
at org.richfaces.component.util.InputUtils.getConvertedStringValue(InputUtils.java:96)
at org.richfaces.component.util.InputUtils.getConvertedStringValue(InputUtils.java:88)
at org.richfaces.renderkit.SelectHelper.generateClientSelectItem(SelectHelper.java:80)
at org.richfaces.renderkit.SelectManyHelper.getClientSelectItems(SelectManyHelper.java:254)
at org.richfaces.renderkit.SelectManyRendererBase.getClientSelectItems(SelectManyRendererBase.java:60)
at org.richfaces.renderkit.html.PickListRenderer.encodeEnd(PickListRenderer.java:202)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at org.richfaces.renderkit.RendererBase.renderChildren(RendererBase.java:276)
at org.richfaces.renderkit.html.PanelRenderer.encodeEnd(PanelRenderer.java:181)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at org.richfaces.renderkit.RendererBase.renderChildren(RendererBase.java:276)
at org.richfaces.renderkit.html.AjaxOutputPanelRenderer.encodeChildren(AjaxOutputPanelRenderer.java:57)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at org.richfaces.context.ExtendedPartialViewContextImpl$RenderVisitCallback.visit(ExtendedPartialViewContextImpl.java:504)
at org.richfaces.context.BaseExtendedVisitContext.invokeVisitCallback(BaseExtendedVisitContext.java:321)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1612)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at org.richfaces.component.AbstractTogglePanel.visitTree(AbstractTogglePanel.java:743)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1623)
at org.richfaces.context.ExtendedPartialViewContextImpl.processPartialRenderPhase(ExtendedPartialViewContextImpl.java:272)
at org.richfaces.context.ExtendedPartialViewContextImpl.processPartial(ExtendedPartialViewContextImpl.java:194)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:981)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1779)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:409)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:124)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
I'm trying to parse lint-result.xml produced by Jenkins. I created stand-alone project that takes lint result file and parse it with XStream 1.4.1 (version that is currently used by Jenkins from what I seen in documentation) this works absolutely fine. However when I move code to Jenkins plugin (it is post-build plugin) I'm getting following error
com.thoughtworks.xstream.mapper.CannotResolveClassException: com.peter.android_lint.parser.LintIssues : com.peter.android_lint.parser.LintIssues
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:71)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:86)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:96)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:56)
at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:136)
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:926)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:912)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:864)
at com.peter.android_lint.parser.LintParser.parse(LintParser.java:25)
at com.peter.ReportPublisher.findFiles(ReportPublisher.java:61)
at com.peter.ReportPublisher.perform(ReportPublisher.java:48)
at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:36)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:814)
at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:786)
at hudson.model.Build$BuildExecution.post2(Build.java:183)
at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:733)
at hudson.model.Run.execute(Run.java:1592)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
at hudson.model.ResourceController.execute(ResourceController.java:88)
at hudson.model.Executor.run(Executor.java:237)
Parser class
public class LintParser {
private File lintResult;
public void parse(String fileName) {
lintResult = new File(fileName);
XStream xstream = new XStream();
xstream.alias("issues", LintIssues.class);
xstream.alias("issue", LintIssue.class);
xstream.alias("location", Location.class);
//xstream.processAnnotations(new Class[]{LintIssues.class, LintIssue.class, Location.class});
LintIssues lintIssues = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(lintResult);
bis = new BufferedInputStream(fis);
lintIssues = (LintIssues) xstream.fromXML(bis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<LintIssue> issueList = lintIssues.getIssueList();
for (LintIssue issue : issueList) {
printIssue(issue);
}
if(bis != null){
try{
bis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void printIssue(LintIssue issue) {
System.out.println("ID= " + issue.getId() + " , severity= " + issue.getSeverity() + " , priority= " + issue.getPriority());
for (Location location : issue.getLocations()) {
printLocation(location);
}
}
private void printLocation(Location location) {
System.out.println("\t Location file=" + location.getFilename());
}
}
LintIssues class
//#XStreamAlias("issues")
public class LintIssues {
#XStreamImplicit(itemFieldName = "issue")
private List<LintIssue> issueList = new ArrayList<LintIssue>();
public LintIssues(List<LintIssue> issueList) {
this.issueList = issueList;
}
public List<LintIssue> getIssueList() {
return issueList;
}
}
LintIssue class
//#XStreamAlias("issue")
public class LintIssue {
#XStreamAlias("id")
#XStreamAsAttribute
private String id;
#XStreamAlias("severity")
#XStreamAsAttribute
private String severity;
#XStreamAlias("category")
#XStreamAsAttribute
private String category;
#XStreamAlias("priority")
#XStreamAsAttribute
private int priority;
#XStreamAlias("summary")
#XStreamAsAttribute
private String summary;
#XStreamAlias("explanation")
#XStreamAsAttribute
private String explanation;
#XStreamAlias("message")
#XStreamAsAttribute
private String message;
#XStreamAlias("errorLine1")
#XStreamAsAttribute
private String errorLine1;
#XStreamAlias("errorLine2")
#XStreamAsAttribute
private String errorLine2;
#XStreamImplicit(itemFieldName = "location")
private List<Location> locations = new ArrayList<Location>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getExplanation() {
return explanation;
}
public void setExplanation(String explanation) {
this.explanation = explanation;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getErrorLine1() {
return errorLine1;
}
public void setErrorLine1(String errorLine1) {
this.errorLine1 = errorLine1;
}
public String getErrorLine2() {
return errorLine2;
}
public void setErrorLine2(String errorLine2) {
this.errorLine2 = errorLine2;
}
public List<Location> getLocations() {
return locations == null ? new ArrayList<Location>() : locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
}
Location class
//#XStreamAlias("location")
public class Location implements Serializable {
private static final long serialVersionUID = 1128640353127613495L;
#XStreamAlias("file")
#XStreamAsAttribute
private String filename;
#XStreamAlias("line")
#XStreamAsAttribute
private int lineNumber;
#XStreamAlias("column")
#XStreamAsAttribute
private int column;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
}
You might have better luck getting a good answer to this question by participating in the jenkinsci-dev mailing list.
The problem I have is that I am trying to have a multi select data grid column which will have a List objects (productsEntitled).
I've got the products to display properly by providing a buildSelect custom function to populate my Edit Dialog Box when a user click edit on a record.
When I have the column with the multi select <sjg:gridColumn name="productsEntitledListModel on my grid, the save functionality does not work and does not save. I don't see any errors on the browser console nor on the java console.
Any help will be appreciated as I am unable to find out what the problem is, I de-compiled the entire show case jar and nothing that helps with this issue.
My model look like this:
#Entity
#Table ( name = "USERS")
public class User {
private Long id;
private String name;
private String username;
private String password;
private String sourceIp;
private Device device;
private List<Product> productsEntitled;
This is my grid on a jsp page:
<s:url id="remoteurl" action="loadUsersJson"/>
<s:url id="editurl" action="editGridUserEntry"/>
<s:url id="selectproductsurl" action="loadProductsJson"/>
<sjg:grid gridModel="users"
id="gridUsers"
dataType="json"
width="1150"
href="%{remoteurl}"
draggable="true"
pager="true"
resizable="true"
navigatorAddOptions="{height:525, width:425, readAfterSubmit:true, draggable:true, resizable:true}"
navigatorEditOptions="{height:525, width:425, reloadAfterSubmit:true, draggable:true, resizable:true}"
navigatorDeleteOptions="{height:200, width:200, reloadAfterSubmit:true, draggable:true, resizable:true}"
editurl="%{editurl}"
navigator="true"
navigatorEdit="true"
navigatorAdd="true"
navigatorView="true"
navigatorDelete="true"
rowList="10,15,20"
rowNum="15"
multiselect="false"
onSelectRowTopics="rowselect">
<sjg:gridColumn name="id" editable="true" index="id" hidden="true" key="true" title="ID"/>
<sjg:gridColumn name="name" index="name" editable="true" edittype="text" title="NAME"/>
<sjg:gridColumn name="sourceIp" index="sourceIp" editable="true" edittype="text" title="SOURCE IP"/>
<sjg:gridColumn name="username" index="username" editable="true" edittype="text" title="USERNAME"/>
<sjg:gridColumn name="password" index="password" editable="true" edittype="password" title="PASSWORD"/>
<sjg:gridColumn name="role" index="role" editable="true" edittype="select" editoptions="{value:'Admin:Admin;User:User;'}" title="ROLE"/>
<sjg:gridColumn name="deviceId" jsonmap="device.id" key="true" hidden="true" editable="text" title="DEVICE ID"/>
<sjg:gridColumn name="deviceIp" jsonmap="device.ip" editable="true" edittype="text" title="DEVICE IP"/>
<sjg:gridColumn name="productsEntitledListModel"
width="300"
editable="true"
edittype="select"
editoptions="{dataUrl: '%{selectproductsurl}', multiple:true, buildSelect:customBuildSelect}"
title="PRODUCTS"/>
</sjg:grid>
These are my action classes:
Show the grid:
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class AdminAction extends ActionSupport implements ServletRequestAware {
private static final long serialVersionUID = -1090720652366248768L;
private static final Log logger = LogFactory.getLog(AdminAction.class);
private HttpServletRequest request;
private AuthenticationTicket ticket;
private AdminService adminService;
private List<User> users;
private List<Product> products;
//private List<String>productsAllList;
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public AuthenticationTicket getTicket() {
return ticket;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void setTicket(AuthenticationTicket ticket) {
this.ticket = ticket;
}
#Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public String redirectUsersTab() {
return "users";
}
public String redirectProductsTab() {
return "products";
}
private void initAdminService () {
logger.debug("initAdminService()...");
if (adminService == null) {
adminService = (AdminService)ServiceFinder.getContext(request).getBean("adminService");
}
}
public String loadUsersJson() {
initAdminService();
this.users = adminService.getUsersAll();
return "success";
}
public String loadProductsJson() {
initAdminService();
this.products = adminService.getProductsAll();
return "success";
}
//TODO: clean up
public String getAllProductsList() {
logger.debug("testParam, userId: " + this.userId);
initAdminService();
List<Product> temp = adminService.getProductsAll();
if (userId != null) {
User userTemp = new User();
userTemp.setId(new Long(userId));
List<Product> prodEntitled = adminService.getProductsByUser(userTemp);
logger.debug("Products entitled: " + prodEntitled);
}
//TODO: merge prod and prod entitled to Model to populate the grid
products = temp;
/*
if (temp != null && temp.size() > 0) {
this.productsAllList = new ArrayList<String>();
for (Product p : temp) {
this.productsAllList.add(p.getName());
}
}
*/
//logger.debug("this.productsAllList: " + this.productsAllList);
return "success";
}
}
Class to edit the grid:
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class EditUsersGridAction extends ActionSupport implements ServletRequestAware {
private static final Log logger = LogFactory.getLog(EditUsersGridAction.class);
private static final long serialVersionUID = -5485382508029951644L;
private HttpServletRequest request;
private AdminService adminService;
private String oper = "";
private Long id;
private String name;
private String sourceIp;
private String password;
private String username;
private Long deviceId;
private String deviceIp;
private String devicePortDescription;
private String devicePortLayer;
private String deviceType;
private List<Product>productsEntitled;
private List<GridColumnListModel> productsEntitledListModel;
private List<Product>productsAvailable;
public List<GridColumnListModel> getProductsEntitledListModel() {
try {
if (productsEntitled != null && productsEntitled.size() > 0) {
productsEntitledListModel = new ArrayList<EditUsersGridAction.GridColumnListModel>();
for (Product p : productsEntitled) {
GridColumnListModel tmp = new GridColumnListModel();
tmp.setName(p.getName());
tmp.setValue(p);
productsEntitledListModel.add(tmp);
}
return this.productsEntitledListModel;
}else {
return null;
}
} catch (Exception ex) {
logger.error("Exception in getProductsEntitledString", ex);
return null;
}
}
public void setProductsEntitledListModel(List<GridColumnListModel> productsEntitledListModel) {
this.productsEntitledListModel = productsEntitledListModel;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public String getDeviceIp() {
return deviceIp;
}
public void setDeviceIp(String deviceIp) {
this.deviceIp = deviceIp;
}
public String getDevicePortDescription() {
return devicePortDescription;
}
public void setDevicePortDescription(String devicePortDescription) {
this.devicePortDescription = devicePortDescription;
}
public String getDevicePortLayer() {
return devicePortLayer;
}
public void setDevicePortLayer(String devicePortLayer) {
this.devicePortLayer = devicePortLayer;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceIp() {
return sourceIp;
}
public void setSourceIp(String sourceIp) {
this.sourceIp = sourceIp;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Product> getProductsEntitled() {
return productsEntitled;
}
public void setProductsEntitled(List<Product> productsEntitled) {
this.productsEntitled = productsEntitled;
}
public List<Product> getProductsAvailable() {
return productsAvailable;
}
public void setProductsAvailable(List<Product> productsAvailable) {
this.productsAvailable = productsAvailable;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
#Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
private void initAdminService () {
logger.debug("initAdminService()...");
if (adminService == null) {
adminService = (AdminService)ServiceFinder.getContext(request).getBean("adminService");
}
}
public String execute() throws Exception {
logger.debug("#### IN EditGridUsersAction ###");
initAdminService();
productsAvailable = adminService.getProductsAll();
User user = new User();
user.setName(name);
user.setPassword(password);
user.setUsername(username);
user.setSourceIp(sourceIp);
Device device = new Device();
device.setId(deviceId);
device.setIp(deviceIp);
device.setPortDescription(devicePortDescription);
device.setType(deviceType);
user.setDevice(device);
if (id != null) {
user.setId(id);
}
if (oper.equalsIgnoreCase("add")) {
logger.debug("products selected");
//user.setProductsEntitled(adminService.getProductsAll());
adminService.addUser(user);
} else if ( oper.equalsIgnoreCase("edit")) {
//TODO: convert model to products and add to user
logger.debug("now in edit");
List<Product> tempProd = new ArrayList<Product>();
for (GridColumnListModel gridColModel : productsEntitledListModel) {
tempProd.add(gridColModel.getValue());
}
user.setProductsEntitled(tempProd);
adminService.updateUser(user);
//return "input";
}else if (oper.equalsIgnoreCase("del")) {
logger.debug("in delete");
adminService.deleteUser(user);
}
return "success";
}
public class GridColumnListModel {
private String name;
private Product value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Product getValue() {
return value;
}
public void setValue(Product value) {
this.value = value;
}
}
}