Mocking File.listFiles using Mockito3.3.3 and Junit 5.6 - mockito

Method for testing
public int check() {
File f =new File("as.txt");
File[] arr = f.listFiles();
return arr.length;
}
Test class
#ExtendWith(MockitoExtension.class)
public class TestDataService {
#InjectMocks
private DataService dataService;
#Test
void chett() {
File[] arr = {new File("we.txt")};
File ff =Mockito.mock(File.class);
when(ff.listFiles()).thenReturn(arr);
assertEquals(1, dataService.check());
}
}
I am getting null pointer exception at File[] arr = f.listFiles();

You need to change the implementation of your check() method
public int check() {
File f = new File("C:\\");
File[] arr = f.listFiles();
return arr.length;
}
As per listFiles() documentations it should contain the directory, otherwise it will return you null.
If this abstract pathname does not denote a directory, then this method returns null. Otherwise, an array of File objects is returned, one for each file or directory in the directory. Pathnamesdenoting the directory itself and the directory's parent directory are not included in the result.
Then you can create your test class like this
#ExtendWith(MockitoExtension.class)
public class TestDataService {
#InjectMocks
private DataService dataService;
#Mock
private File f;
#Test
void chett() {
File[] arr = { new File("C://") };
when(f.listFiles()).thenReturn(arr);
assertEquals(1, dataService.check());
}
}
OR this
#ExtendWith(MockitoExtension.class)
public class TestDataService {
#InjectMocks
private DataService dataService;
#Mock
private File f;
#Test
void chett() {
File[] arr = { new File("C://") };
File ff = Mockito.mock(File.class);
when(ff.listFiles()).thenReturn(arr);
assertEquals(1, dataService.check());
}
}

Related

JAXB not unmarshalling all fields

I am working on a JavaFX application which facilitates all kind of sport related training sessions. Each session consists of multiple exercises, whereas each exercise is repeated multiple times in a few sets. I created some test data and marshalled it. As it turned out, some fields of the Exercise class objects were written but not all of them. By adding the #XmlElement(name="someTagName") tag to each getter of each field I managed that all fields are marshalled and the xml file looks like expected. However, when I unmarshall the xml file, only those fields, which were written without the #XmlElement tag are read and most of the fields only have the default value from the constructor. What am I missing in order to unmarshall all fields?
Here is the class that I want to marshall/unmarshall
package domain;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Exercise extends SelectableDomainObj {
protected StringProperty name;
protected StringProperty mediaFilePath;
protected IntegerProperty repsPerSet;
protected IntegerProperty numOfSets;
protected IntegerProperty breakBetweenSetsInSecs;
protected IntegerProperty displayTimeInSecs;
protected DoubleProperty startSpeed;
protected DoubleProperty endSpeed;
protected BooleanProperty withMetronom;
protected BooleanProperty showIntro;
/**
* Set some reasonable default values from lifting domain
*/
public Exercise() {
mediaFilePath = new SimpleStringProperty();
name = new SimpleStringProperty();
numOfSets = new SimpleIntegerProperty(3);
repsPerSet = new SimpleIntegerProperty(8);
breakBetweenSetsInSecs = new SimpleIntegerProperty(60);
displayTimeInSecs = new SimpleIntegerProperty(-1);
startSpeed = new SimpleDoubleProperty(1.0);
endSpeed = new SimpleDoubleProperty(1.0);
withMetronom = new SimpleBooleanProperty(false);
showIntro = new SimpleBooleanProperty(false);
}
#XmlElement(name="name")
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
#XmlElement(name="mediaFilePath")
public String getMediaFilePath() {
return mediaFilePath.get();
}
public void setMediaFilePath(String mediaFilePath) {
this.mediaFilePath.set(mediaFilePath);
}
public StringProperty mediaFilePathProperty() {
return mediaFilePath;
}
#XmlElement(name="repsPerSet")
public Integer getRepsPerSet() {
return repsPerSet.get();
}
public void setRepsPerSet(int repsPerSet) {
this.repsPerSet.set(repsPerSet);
}
public IntegerProperty repsPerSetProperty() {
return repsPerSet;
}
#XmlElement(name="numOfSets")
public int getNumOfSets() {
return numOfSets.get();
}
public void setNumOfSets(int numOfSets) {
this.numOfSets.set(numOfSets);
}
public IntegerProperty numOfSetsProperty() {
return numOfSets;
}
#XmlElement(name="breakBetweenSetsInSec")
public Integer getBreakBetweenSetsInSecs() {
return breakBetweenSetsInSecs.get();
}
public void setBreakBetweenSetsInSecs(int breakBetweenSetsInSecs) {
this.breakBetweenSetsInSecs.set(breakBetweenSetsInSecs);
}
public IntegerProperty displayTimeInSecsProperty() {
return displayTimeInSecs;
}
#XmlElement(name="displayTimeInSecs")
public Integer getDisplayTimeInSecs() {
return displayTimeInSecs.get();
}
public void setDisplayTimeInSecs(int displayTime) {
this.displayTimeInSecs.set(displayTime);
}
public IntegerProperty breakBetweenSetsInSecsProperty() {
return breakBetweenSetsInSecs;
}
#XmlElement(name="showIntro")
public Boolean isShowIntro() {
return showIntro.getValue();
}
public void setShowIntro(boolean showIntro) {
this.showIntro.set(showIntro);
}
public BooleanProperty showIntroProperty() {
return showIntro;
}
#XmlElement(name="withMetronom")
public Boolean isWithMetronom() {
return withMetronom.getValue();
}
public void setWithMetronom(boolean withMetronom) {
this.withMetronom.set(withMetronom);
}
public BooleanProperty withMetronomProperty() {
return withMetronom;
}
#XmlElement(name="startSpeed")
public Double getStartSpeed() {
return startSpeed.get();
}
public void setStartSpeed(double startDuration) {
this.startSpeed.set(startDuration);
}
public DoubleProperty startSpeedProperty() {
return startSpeed;
}
#XmlElement(name="endSpeed")
public Double getEndSpeed() {
return endSpeed.get();
}
public void setEndSpeed(double endDuration) {
this.endSpeed.set(endDuration);
}
public DoubleProperty endSpeedProperty() {
return endSpeed;
}
public double getSpeed(int rep) {
if(getStartSpeed().equals(getEndSpeed())) {
return getStartSpeed();
}
double min, max;
if(getStartSpeed() > getEndSpeed()) {
max = getStartSpeed();
min = getEndSpeed();
} else {
min = getStartSpeed();
max = getEndSpeed();
}
double diff = max - min;
double increment = diff / (getRepsPerSet()-1);
return min + rep * increment;
}
#Override
public String toString() {
return getName();
}
}
I used this to marshall
public void save(Session session) {
try {
JAXBContext jc = JAXBContext.newInstance(Session.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(session, new File(System.getProperty("user.home"), ".sifuSays/sessions/" + session.getName() + ".xml"));
} catch (JAXBException e) {
System.err.println("Cannot save session " + session.getName());
e.printStackTrace();
}
}
which generates the following xml file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Session>
<exerciseList>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>-1</displayTimeInSecs>
<endSpeed>3.0</endSpeed>
<mediaFilePath>Tan Pak Gan.mp4</mediaFilePath>
<name>Solo Tan Pak Gan Drill</name>
<numOfSets>2</numOfSets>
<repsPerSet>3</repsPerSet>
<showIntro>false</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>false</withMetronom>
</exercise>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>-1</displayTimeInSecs>
<endSpeed>1.0</endSpeed>
<mediaFilePath>Chain Punches.mp4</mediaFilePath>
<name>Solo Ein-Arm-Zyklus</name>
<numOfSets>2</numOfSets>
<repsPerSet>4</repsPerSet>
<showIntro>true</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>true</withMetronom>
</exercise>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>10</displayTimeInSecs>
<endSpeed>1.0</endSpeed>
<mediaFilePath>birddogs.jpg</mediaFilePath>
<name>Stetching</name>
<numOfSets>1</numOfSets>
<repsPerSet>1</repsPerSet>
<showIntro>true</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>false</withMetronom>
</exercise>
</exerciseList>
<breakBetweenExercisesInSec>10</breakBetweenExercisesInSec>
<name>MMA - Solo</name>
</Session>
and this is the unmarshaller code
public ObservableList<Session> loadSessions() {
sessions = FXCollections.observableArrayList();
try {
List<File> xmlSessionFiles = Stream.of(
new File(System.getProperty("user.home"), ".sifuSays/sessions/").listFiles())
.filter(file -> !file.isDirectory())
.filter(file -> file.getName().endsWith("xml"))
.collect(Collectors.toList());
for(File xmlSessionFile: xmlSessionFiles) {
JAXBContext jc = JAXBContext.newInstance(Session.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Session session = (Session) unmarshaller.unmarshal(xmlSessionFile);
sessions.add(session);
}
} catch (JAXBException e) {
System.err.println("Cannot load sessions");
e.printStackTrace();
}
return sessions;
}
While numOfSets is marshalled, repsPerset is not. Neither startSpeed or stopSpeed are unmarshalled and neither withMetronom or showIntro. But name and mediaFilePath are marshalled. What's wrong?
You are mixing up boxed (Double, Integer) and unboxed (double, int) types. I recommend sticking to boxed types for marshalling since otherwise you'll end up with things set to 0 that you weren't expecting.

without resolveStrategy=DELEGATE_FIRST properties end up as binding variables

I'm trying to write java beans that can be loaded from a Groovy config file. The config format expects properties in closures and if I don't call c.setResolveStrategy(Closure.DELEGATE_FIRST) then all properties set inside the closures end up as binding variables. My program outputs:
In closure
confpojo.myTestProp: null
binding.myTestProp: true
confpojo.app.myOther.myTestSubProp: null
binding.myTestSubProp: true
In this answer https://stackoverflow.com/a/10761284/447503 they don't change the default resolveStrategy and it seems to work. What's the difference? configaaa.groovy:
app {
println 'In closure'
myTestProp = true
myOther {
myTestSubProp = true
}
}
_
public abstract class AaaTestGroovyConfig extends Script {
public static class App {
public void myOther(final Closure c) {
c.setDelegate(myOther);
// c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.call();
}
private Boolean myTestProp;
private final Other myOther = new Other();
public Boolean getMyTestProp() {
return myTestProp;
}
public void setMyTestProp(final Boolean active) {
this.myTestProp = active;
}
}
public void app(final Closure c) {
c.setDelegate(app);
// c.setResolveStrategy(Closure.DELEGATE_FIRST);
c.call();
}
private App app = new App();
public static void main(final String[] args) throws Exception {
final CompilerConfiguration cc = new CompilerConfiguration();
cc.setScriptBaseClass(AaaTestGroovyConfig.class.getName());
// final ClassLoader cl = AaaTestGroovyConfig.class.getClassLoader();
final Binding binding = new Binding();
final GroovyShell shell = new GroovyShell(binding, cc);
final Script script = shell.parse(new File("configaaa.groovy"));
final AaaTestGroovyConfig confpojo = (AaaTestGroovyConfig) script;
// ((DelegatingScript) script).setDelegate(confpojo);
script.run();
System.out.println("confpojo.myTestProp: " + confpojo.app.myTestProp);
printBindingVar(binding, "myTestProp");
System.out
.println("confpojo.app.myOther.myTestSubProp: " + confpojo.app.myOther.myTestSubProp);
printBindingVar(binding, "myTestSubProp");
}
private static void printBindingVar(final Binding binding, final String name) {
System.out
.println(
"binding." + name + ": " + (binding.hasVariable(name)
? binding.getVariable(name)
: ""));
}
public static class Other {
private Boolean myTestSubProp;
public Boolean getMyTestSubProp() {
return myTestSubProp;
}
public void setMyTestSubProp(final Boolean myTestSubProp) {
this.myTestSubProp = myTestSubProp;
}
}
public App getApp() {
return app;
}
public void setApp(final App app) {
this.app = app;
}
}
because the default value is OWNER_FIRST
https://docs.groovy-lang.org/latest/html/api/groovy/lang/Closure.html#OWNER_FIRST
and you have 2 levels of closures so - owners are different for them
try something like this and you'll see the difference
app {
println "delegate=$delegate owner=${owner.getClass()}"
myOther {
println "delegate=$delegate owner=${owner.getClass()}"
}
}
PS: let me suggest you to make your code groovier:
//generic config class
class MyConf {
private HashMap objMap
static def build(HashMap<String,Class> classMap, Closure builder){
MyConf cfg = new MyConf()
cfg.objMap = classMap.collectEntries{ k,cl-> [k, cl.newInstance()] }
cfg.objMap.each{ k,obj->
//define method with name `k` and with optional closure parameter
cfg.metaClass[k] = {Closure c=null ->
if(c) {
// call init closure with preset delegate and owner
return c.rehydrate(/*delegate*/ obj, /*owner*/cfg, /*this*/cfg).call()
}
return obj //return object itself if no closure
}
}
cfg.with(builder) // call root builder closure with cfg as a delegate
return cfg
}
}
//bean 1
#groovy.transform.ToString
class A{
int id
String name
}
//bean 2
#groovy.transform.ToString
class B{
int id
String txt
}
//beans init
def cfg = MyConf.build(app:A.class, other:B.class){
app {
id = 123
name = "hello 123"
other {
id = 456
txt = "bye 456"
}
}
}
//get initialized beans
println cfg.app()
println cfg.other()

"No such property: for class: Script1" during using Groovy(String to reflection code)

I am trying to use Groovy in order to convert string to the reflection code but I have "No such property" exception.
I have tried to make global all variables, change the reflection code and put #Field notation but problem still remaining. I put Groovy code inside "runTestSamples()".
MainClass - Test2
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.jacoco.agent.AgentJar;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IClassCoverage;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.data.SessionInfoStore;
import org.jacoco.core.instr.Instrumenter;
import org.jacoco.core.runtime.IRuntime;
import org.jacoco.core.runtime.LoggerRuntime;
import org.jacoco.core.runtime.RuntimeData;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
public class Test2 {
private Runnable targetInstance;
public Class<?> targetClass;
private static HashMap<Integer, String> testSamples;
private static HashMap<String, Integer> coverageData;
public String targetName;
public IRuntime runtime;
public Instrumenter instr;
public InputStream original;
public byte[] instrumented;
public RuntimeData data;
public MemoryClassLoader memoryClassLoader;
static Test2 t2 = new Test2();
int a;
public static void main(String[] args) throws Exception {
testSamples = new HashMap<Integer, String>();
coverageData = new HashMap<String, Integer>();
try {
t2.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute() throws Exception {
testSamples = new HashMap<Integer, String>();
coverageData = new HashMap<String, Integer>();
targetName = SUTClass.class.getName();
runtime = new LoggerRuntime();
instr = new Instrumenter(runtime);
original = getTargetClass(targetName);
instrumented = instr.instrument(original, targetName);
original.close();
data = new RuntimeData();
runtime.startup(data);
memoryClassLoader = new MemoryClassLoader();
memoryClassLoader.addDefinition(targetName, instrumented);
targetClass = (Class<? extends Runnable>) memoryClassLoader.loadClass(targetName);
targetInstance = (Runnable) targetClass.newInstance();
// Test samples
runTestSamples();
targetInstance.run();
final ExecutionDataStore executionData = new ExecutionDataStore();
final SessionInfoStore sessionInfos = new SessionInfoStore();
data.collect(executionData, sessionInfos, false);
runtime.shutdown();
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(executionData, coverageBuilder);
original = getTargetClass(targetName);
analyzer.analyzeClass(original, targetName);
original.close();
for (final IClassCoverage cc : coverageBuilder.getClasses()) {
coverageData.put("coveredInstructions", cc.getInstructionCounter().getCoveredCount());
}
System.out.println(coverageData.get("coveredInstructions"));
System.out.println(a);
}
public static class MemoryClassLoader extends ClassLoader {
private final Map<String, byte[]> definitions = new HashMap<String, byte[]>();
public void addDefinition(final String name, final byte[] bytes) {
definitions.put(name, bytes);
}
#Override
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
final byte[] bytes = definitions.get(name);
if (bytes != null) {
return defineClass(name, bytes, 0, bytes.length);
}
return super.loadClass(name, resolve);
}
}
private InputStream getTargetClass(final String name) {
final String resource = '/' + name.replace('.', '/') + ".class";
return getClass().getResourceAsStream(resource);
}
public void runTestSamples() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException, ClassNotFoundException {
// Test case
targetClass.getMethod("f", int.class, int.class).invoke(targetInstance, 2, 9);
// Groovy String to code
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("targetClass.getMethod(\"f\", int.class, int.class).invoke(targetInstance, 2, 9);");
}
}
Exception
groovy.lang.MissingPropertyException: No such property: targetClass for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:65)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:309)
at Script1.run(Script1.groovy:1)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:437)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:475)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:446)
at Test2.runTestSamples(Test2.java:119)
at Test2.execute(Test2.java:66)
at Test2.main(Test2.java:43)
the problem in this code:
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("targetClass.getMethod(\"f\", int.class, int.class).invoke(targetInstance, 2, 9);");
when you call shell.evaluate imagine that you call absolutely new class that doesnot know anything about your current variables like targetClass
so, GroovyShell telling that there is no such property: targetClass
to fix it - you have just to populate binding - pass the variables values and names that should be visible inside the shell.evaluate(...).
Binding binding = new Binding();
binding.setVariable("target", targetClass) //pass targetClass as target variable name
binding.setVariable("instance", targetInstance)
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("target.getMethod(\"f\", int.class, int.class).invoke(instance, 2, 9)");
another point - groovy is already dynamic language and you could simplify your nested script from this:
target.getMethod("f", int.class, int.class).invoke(instance, 2, 9)
to this:
instance."f"(2, 9)
and finally maybe you don't need to use the groovyshell because the following code dynamycally calls the method:
class A{
def f(int a, int b){ a+b }
}
def instance = new A()
def method = "f"
def params = [2,9]
println instance."${method}"(params)

JAXB define java class for a xml file with attributes in nested elements

I want to define a java class and then use JAXB to marshalling its instances to a xml file.
The output I want looks like:
<paths>
<path action="R" kind="file" copyfrom-path="file1" copyto-path="file2">file2</path>
<path action="M" kind="file">file3</path>
</paths>
I defined a java class as follows:
#XmlRootElement(name = "paths")
#XmlAccessorType(FIELD)
public class changed_paths
{
private List<String> path;
public changed_paths()
{
path = new ArrayList<String>();
}
public List<String> getPath()
{
return path;
}
public void setPath(List<String> path)
{
this.path = path;
}
public void addPath(String p)
{
path.add(p);
}
}
Using the above java class, I can generate output xml file without the attributes of <path></path> elements. Like below:
<paths>
<path>file2</path>
<path>file3</path>
</paths>
I tried to define the attributes in changed_paths class like below :
#XmlAttribute
private String kind;
public void setKind(String kind){
this.kind = kind;
}
public String getKind(){
return this.kind;
}
But this will output a xml file with attributes "kind" in tag <paths></paths> but not in its nested <path></path> tags.
The other problem is that when the attribute name contains "-" (e.g. copyfrom-path), java won't allow me to define such variables with "-" in its name.
Can someone please tell me how to define:
1. attributes in <path></path>?
2. attributes with "-" in their names?
Can someone please give me some help?
Thank you very much!
I find the answers. To create attributes for <path></path>, I defined class path for this tag. And defined another class paths for <paths></paths> .
To create attributes with "-" in their names, I use annotation #XmlAttribute(name = "copyfrom-path")
#XmlAccessorType(FIELD)
public class path
{
#XmlAttribute
private String kind;
#XmlAttribute
private String action;
#XmlAttribute(name = "copyfrom-path")
private String copyfrom;
#XmlAttribute(name = "copyfrom-rev")
private String copyto;
#XmlValue
private String value;
public void setKind(String kind)
{
this.kind = kind;
}
public String getKind()
{
return this.kind;
}
public void setAction(String action)
{
this.action = action;
}
public String getAction()
{
return this.action;
}
public void setValue(String value)
{
this.value = value;
}
public String getValue()
{
return this.value;
}
public void setCopyfrom(String p)
{
this.copyfrom = p;
}
public String getCopyfrom()
{
return this.copyfrom;
}
public void setCopyto(String p)
{
this.copyto = p;
}
public String getCopyto()
{
return this.copyto;
}
}
#XmlRootElement(name = "paths")
#XmlAccessorType(FIELD)
public class paths
{
private List<path> paths;
public paths()
{
paths = new ArrayList<path>();
}
public List<path> getPaths()
{
return paths;
}
public void setPaths(List<path> paths)
{
this.paths = paths;
}
public void addPath(path p)
{
paths.add(p);
}
}

#XmlAttribute/#XmlValue need to reference a Java type that maps to text in XML

how to pick the value of an attribute 'name' which is a PriceEventName class type in the below case, FYI if i put #XmlAttribute above it this is turn out to an exception "an error #XmlAttribute/#XmlValue need to reference a Java type that maps to text in XML"
I looking heavily on the internet but I didn't find something similar to my case
PriceEvent class
package somepackage
import ...
import
#XmlAccessorType(XmlAccessType.FIELD)
public class PriceEvent {
#XmlElement(name="Message",namespace="someValue")
private String color;
private PriceEventName name;// this is an attribute
.
.
}
PriceEventName class
Imports ...
public class PriceEventName {
public static final int PRICEUPDATE_TYPE = 0;
public static final PriceEventName PRICEUPDATE = new PriceEventName(PRICEUPDATE_TYPE, "X-mas");
private static java.util.Hashtable _memberTable = init();
private static java.util.Hashtable init() {
Hashtable members = new Hashtable();
members.put("X-mas", PRICEUPDATE);
return members;
}
private final int type;
private java.lang.String stringValue = null;
public PriceEventName(final int type, final java.lang.String value) {
this.type = type;
this.stringValue = value;
}
public static PriceEventName valueOf(final java.lang.String string) {
java.lang.Object obj = null;
if (string != null) {
obj = _memberTable.get(string);
}
if (obj == null) {
String err = "" + string + " is not a valid PriceEventName";
throw new IllegalArgumentException(err);
}
return (PriceEventName) obj;
}
}
This is how you declare the field as an attribute with an adapter:
#XmlJavaTypeAdapter(PenAdapter.class)
#XmlAttribute
protected PriceEventName name;
public PriceEventName getName() { return name; }
public void setName(PriceEventName value) { this.name = value; }
Add you'll need to add a getter to PriceEventName:
public String getStringValue(){ return stringValue; }
And here is the adapter class:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class PenAdapter extends XmlAdapter<String,PriceEventName> {
public PriceEventName unmarshal(String v) throws Exception {
return PriceEventName.valueOf( v );
}
public String marshal(PriceEventName v) throws Exception {
return v.getStringValue();
}
}

Resources