I want to implement a method which returns JAXBElement following is the code
#XmlRootElement(name = "history")
#XmlAccessorType(XmlAccessType.FIELD)
public class IBHistoryInfo {
#XmlElement(name="trade")
private List<IBTradeInfo> mTrade;
public void updateTradeValue(int reqId, String date, double open, double high, double low,
double close, int volume, int count, double WAP, boolean hasGaps){
IBTradeInfo info = new IBTradeInfo();
info.setReqId(reqId);
info.setDate(date);
info.setOpen(open);
info.setHigh(high);
info.setLow(low);
info.setClose(close);
info.setVolume(volume);
info.setCount(count);
info.setWap(WAP);
info.setHasGaps(hasGaps);
this.setTradeInfo(info);
}
public void setTradeInfo(IBTradeInfo tradeinfo){
mTrade.add(tradeinfo);
}
public List<IBTradeInfo> getTradeInfo(){
if (mTrade == null) {
mTrade = new ArrayList<IBTradeInfo>();
}
return this.mTrade;
}
}
Now i don't know how to creat a method which returns JAXBElement in the above class
for example
public JAXBElement<IBTradeInfo> getTradeXML(){
return mTrade
}
The following is how you could implement the getTradeXML() method:
public JAXBElement<IBTradeInfo> getTradeXML(){
if(null == mTrade || mTrade.size() == 0) {
return null;
}
IBTradeInfo tradeInfo = mTrade.get(0);
QName qname = new QName("http://www.example.com", "trade-info");
return new JAXBElement(qname, IBTradeInfo.class, tradeInfo);
}
I believe, you can only return 1 element at a time. In this case, you possibly need to write something like:
public JAXBElement<IBTradeInfo> getTradeXML(){
return new JAXBElement<IBTradeInfo>(mTrade.get(0), IBTradeInfo.class);
}
Just a guess.
Related
I'm writing a function to check multiple conditions in an array, if they are all true then return true.
For example:
public class Attribute {
private final String key;
private final String value;
//...
}
boolean canContactDogOwner(List<Attribute> attributes) {
boolean hasDog = false;
boolean isSubscribed = false;
boolean isOkToCall = false;
for (var attribute : attributes) {
if (attribute.key().equals("dogName")) {
hasDog = true;
} else if (attribute.key().equals("isSubscribed") && attribute.value().equals("Y")) {
isSubscribed = true;
} else if (attribute.key().equals("okToCall") && attribute.value().equals("Y")) {
isOkToCall = true;
}
// 1.
}
return hasDog && isSubscribed && isOkToCall;
}
void foo() {
List<Attribute> attributes = new ArrayList<>();
attributes.add(new Attribute("isSubscribed", "Y"));
attributes.add(new Attribute("okToCall", "Y"));
attributes.add(new Attribute("mobile", "12345678"));
attributes.add(new Attribute("landline", "1346346"));
attributes.add(new Attribute("email", "white#email.com"));
attributes.add(new Attribute("dogName", "Alex"));
boolean canContact = canContactDogOwner(attributes);
}
Two questions:
When all conditions are meet, the loop can be break, but if I add a check there, we would be checking every step in the loop, which doesn't look good. Any suggestions?
Is there a better / concise way to do it?
Like following?
boolean canContactDogOwner(List<Attribute> attributes) {
return attributes.stream().allMatch(A,B,C);
}
You can modify method canContactDogOwner to be like this,
boolean canContactDogOwner(List<Attribute> attributes) {
List<Attribute> conditions = new ArrayList<>();
conditions.add(new Attribute("isSubscribed", "Y"));
conditions.add(new Attribute("okToCall", "Y"));
return attributes.containsAll(conditions) &&
attributes.stream().anyMatch((attribute -> attribute.key.equals("dogName")));
}
A working and cleaner approach (IMO) will be to use some abstract data type like Map in this case..
static boolean canContactDogOwner(List<Attribute> attributes){
Map<String, String> attributeMap = new HashMap<>(); // empty map
attributes.forEach(attr -> attributeMap.put(attr.getKey(), attr.getValue())); // populate map
return attributeMap.containsKey("dogName") &&
"Y".equals(attributeMap.get("isSubscribed")) &&
"Y".equals(attributeMap.get("okToCall")); // Constant-String-first on equals check to avoid nullPointerExc with less code, yet clean
}
The code above with the comment is self-explanatory, so not adding details of the code.
But it is worth mentioning that
the complexity is still O(n) like other solutions here, n - number of elements (attribute objects)
flexibility to add or remove more conditions in the return statement
map as a chosen data-type and <Constant>.equals check avoids key validation and nullPointerException respectively.
If you are fascinated with Java-Streams, you can modify the code like this too..
static boolean canContactDogOwner(List<Attribute> attributes){
Map<String, String> attributeMap = attributes.stream()
.collect(Collectors.toMap(Attribute::getKey, Attribute::getValue));
return attributeMap.containsKey("dogName") &&
"Y".equals(attributeMap.get("isSubscribed")) &&
"Y".equals(attributeMap.get("okToCall"));
}
You could check if all condition is meet only when you set a value to true,
it will happen only 3 time.
And more concise way, probably with stream().anyMatch() but i'm not sure it will be more readable
Stream and allMatch(Predicate predicate) is a better way to do it in my opinion, but keep in mind that allMatch() take a Predicate as an argument, so you need to provide one.
I would suggest you encapsulate the attributes and create a class
something like Owner.
public class Owner {
private boolean isSubscribed;
private boolean okToCall;
private String mobile;
private String landline;
private String email;
private Optional<String> dogName;
public Owner(boolean isSubscribed, boolean okToCall, String mobile, String landline, String email, Optional<String> dogName) {
this.isSubscribed = isSubscribed;
this.okToCall = okToCall;
this.mobile = mobile;
this.landline = landline;
this.email = email;
this.dogName = dogName;
}
public boolean canContact() {
return this.isSubscribed && this.okToCall;
}
public boolean hasDog() {
return dogName.isPresent();
}
}
This way you do not have to deal with the if loops, the Owner object will say if they have a dog and can be contacted, etc.
public static void main(String[] args) {
Owner owner = new Owner(true, true, "12345678", "1346346", "white#email.com", Optional.of("Alex"));
boolean canContact = owner.hasDog() && owner.canContact();
}
I think you can have two lists of your conditions and attributes and then check whether attributes contain all condition or not.
public static Boolean allConditionsExist(List<String> attributes, List<String> conditions) {
return attributes.containsAll(conditions);
}
To convert your conditions and attributes to a list you can do something like this.
List<String> conditions = Arrays.asList("dogName","isSubscribed", "okToCall"); // add all your conditions
and
List<String> attributeKeys = attributes.stream().map(Attribute::getKey).collect(Collectors.toList());
Then call
allConditionExist(attributeKeys, conditions);
Assuming that every attribute is present only once, you could write
boolean canContactDogOwner(List<Attribute> attributes) {
int matches = 0;
for (var attribute : attributes) {
if (attribute.key().equals("dogName")) ||
attribute.key().equals("isSubscribed") && attribute.value().equals("Y") ||
attribute.key().equals("okToCall") && attribute.value().equals("Y"))
{
matches++;
if (matches >= 3) {
return true;
}
}
}
return false;
}
For the stream way you could write a Collector, constructed with a list of Predicates and returning a boolean. Wouldn't be the fastest...
Something like:
public class AllMatch<T> implements Collector<T, Set<Predicate<T>>, Boolean>
{
private Set<Predicate<T>> filter;
public AllMatch(Predicate<T>... filter)
{
super();
this.filter = new HashSet(Arrays.asList(filter));
}
#Override
public Supplier<Set<Predicate<T>>> supplier()
{
return () -> new HashSet<>();
}
#Override
public BinaryOperator<Set<Predicate<T>>> combiner()
{
return this::combiner;
}
#Override
public Set<Characteristics> characteristics()
{
return Stream.of(Characteristics.UNORDERED).collect(Collectors.toCollection(HashSet::new));
}
public Set<Predicate<T>> combiner(Set<Predicate<T>> left, Set<Predicate<T>> right)
{
left.addAll(right);
return left;
}
public Set<Predicate<T>> accumulator(Set<Predicate<T>> acc, T t)
{
filter.stream().filter(f -> f.test(t)).forEach(f ->
{
acc.add(f);
});
return acc;
}
#Override
public Function<Set<Predicate<T>>, Boolean> finisher()
{
return (s) -> s.equals(filter);
}
#Override
public BiConsumer<Set<Predicate<T>>, T> accumulator()
{
return this::accumulator;
}
public static void main(String[] args) {
Integer[] numbers = {1,2,3,4,5,6,7,8};
System.out.println(Arrays.stream(numbers).collect(new AllMatch<Integer>((i)-> i.equals(5),(i)-> i.equals(6))));
System.out.println(Arrays.stream(numbers).collect(new AllMatch<Integer>((i)-> i.equals(5),(i)-> i.equals(9))));
}
}
I have a model like below:
public class Shifts{
private double h00;
private double h01;
private double h02;
private double h03;
public Shifts() {
}
public Shifts(double h00, double h01, double h02, double h03) {
this.h00 = h00;
this.h01 = h01;
this.h02 = h02;
this.h03 = h03;
}
public double getH00() {
return h00;
}
public void setH00(double h00) {
this.h00 = h00;
}
public double getH01() {
return h01;
}
public void setH01(double h01) {
this.h01 = h01;
}
public double getH02() {
return h02;
}
public void setH02(double h02) {
this.h02 = h02;
}
public double getH03() {
return h03;
}
public void setH03(double h03) {
this.h03 = h03;
}
}
I'm calling this model in a recycle adapter to update the UI and on the onBindViewHolder, I do like this:
holder.h00.setText(fooList.get(position).getH00()));
holder.h01.setText(fooList.get(position).getH01()));
holder.h02.setText(fooList.get(position).getH02()));
holder.h03.setText(fooList.get(position).getH03()));
In reality, this model has a lot of getters and setters and I was trying to loop through them so I can do something like this:
for (int i = 0; i < holder.shift_layout.getChildCount(); i++) {
//shift_layout is the Layout which holds all the views
View v = holder.shift_layout.getChildAt(i);
if (v instanceof TextView) {
v.setText(Hour(fooList.get(position).getGetter()));
}
}
Is there a way to use Java reflection or any method to loop through all getters of a model and then invoke them?
Looking over the SO I found some answers but with not any success to invoke the getters.
The other answers provided, especially Magnus, definitely get the job done. They are valid answers. The only difference between this solution and the others is that this will ensure that the method name starts with getH which seems to be pattern. It also checks if the return type is of type double to help ensure the correct method is being returned.
Shifts shifts = new Shifts(1, 2, 3, 4);
Method[] methods = shifts.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().startsWith("getH") && method.getReturnType() == double.class) {
double value = (double) method.invoke(shifts);
}
}
This code iterates over all methods of the class obj and if method name starts with 'get' it invokes the method m on instance obj and assigns the result to object:
final Object obj;
for (Method m : obj.getClass().getMethods())
if (m.getName().startsWith("get") && m.getParameterTypes().length == 0) {
final Object object = m.invoke(obj);
// do something
}
}
Yes, there is a way you can loop through getters by reflections. You should first make some kind of list with names of attributes.
I did it once with HashMap and setters, then I iterated through that hash map with:
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
var setterName = "set" + entry.getKey().toUpperCase();
Method setter = instanceOfMyClassWithSetters.getClass().getMethod(setterName, Integer.class);
setter.invoke(instanceOfMyClassWithSetters, entry.getValue());
}
That Integer.class is a setter parameter so I suppose you don't need that part.
For a project, which generates XML-files based on a XSD-file, I want to automatically generate the documentation. *
In this documentation I list the different elements defined in the XSD.
And for each element I want to show an example of that element.
The problem is, that the XML-example might be quite long and contains a lot of children.
Therefore I want to shorten the example by:
limiting the shown depth
limiting the amount of elements in a list
For the root-element that example might look like the following:
<root>
<elements>
<element>...<element>
<element>...<element>
<element>...<element>
...
</elements>
</root>
My approach:
To generate classes from the XSD and to generate and validate the XML files I use JAXB.
But I could not figure out how to marshal a Non-Root element.
Therefore I am generating my examples with XStream.
To limit the XML-example I am trying to decorate the PrettyPrintWriter, but that seems to be quite cumbersome.
The two decorators can be seen in my answer.
I just did not expect to care about the internals of a library for such a (common?) feature.
Is there an easier way to do this? (I can also use another library than XStream, or none at all.)
*
My approach is influenced by Spring Auto Rest Docs
To limit the shown depth I created the following XStream WriterWrapper. The class can wrap for example a PrettyPrintWriter and ensures that the wrapped writer only receives the nodes above a given depth threshold.
public class RestrictedPrettyPrintWriter extends WriterWrapper {
private final ConverterLookup converterLookup;
private final int maximalDepth;
private int depth;
public RestrictedPrettyPrintWriter(HierarchicalStreamWriter sw, ConverterLookup converterLookup, int maximalDepth) {
super(sw);
this.converterLookup = converterLookup;
this.maximalDepth = maximalDepth;
}
#Override public void startNode(String name, Class clazz) {
Converter converter = this.converterLookup.lookupConverterForType(clazz);
boolean isSimpleType = converter instanceof SingleValueConverter;
_startNode(name, !isSimpleType);
}
#Override public void startNode(String name) {
_startNode(name, false);
}
#Override public void endNode() {
if (_isLessDeepThanMaximalDepth() || _isMaximalDepthReached()) {
super.endNode();
}
depth--;
}
#Override public void addAttribute(String key, String value) {
if (_isLessDeepThanMaximalDepth() || _isMaximalDepthReached()) {
super.addAttribute(key, value);
}
}
#Override public void setValue(String text) {
if (_isLessDeepThanMaximalDepth() || _isMaximalDepthReached()) {
super.setValue(text);
}
}
/**
* #param name name of the new node
* #param isComplexType indicates if the element is complex or contains a single value
*/
private void _startNode(String name, boolean isComplexType) {
depth++;
if (_isLessDeepThanMaximalDepth()) {
super.startNode(name);
} else if (_isMaximalDepthReached()) {
super.startNode(name);
/*
* set the placeholder value now
* setValue() will never be called for complex types
*/
if (isComplexType) {
super.setValue("...");
}
}
}
private boolean _isMaximalDepthReached() {
return depth == maximalDepth;
}
private boolean _isLessDeepThanMaximalDepth() {
return depth < maximalDepth;
}
}
To limit the lists, I tried, in a first attempt, to modify the XStream CollectionConverter. But this approach was not general enough because implicit lists do not use this converter.
Therefore I created another WriterWrapper which counts the consecutive occurrences of elements with the same name.
public class RestrictedCollectionWriter extends WriterWrapper {
private final int maxConsecutiveOccurences;
private int depth;
/** Contains one element per depth.
* More precisely: the current element and its parents.
*/
private Map < Integer, Elements > elements = new HashMap < > ();
public RestrictedCollectionWriter(HierarchicalStreamWriter sw, int maxConsecutiveOccurences) {
super(sw);
this.maxConsecutiveOccurences = maxConsecutiveOccurences;
}
#Override public void startNode(String name, Class clazz) {
_startNode(name);
}
#Override public void startNode(String name) {
_startNode(name);
}
#Override public void endNode() {
if (_isCurrentElementPrintable()) {
super.endNode();
}
depth--;
}
#Override public void addAttribute(String key, String value) {
if (_isCurrentElementPrintable()) {
super.addAttribute(key, value);
}
}
#Override public void setValue(String text) {
if (_isCurrentElementPrintable()) {
super.setValue(text);
}
}
/**
* #param name name of the new node
*/
private void _startNode(String name) {
depth++;
Elements currentElement = this.elements.getOrDefault(depth, new Elements());
this.elements.put(depth, currentElement);
Elements parent = this.elements.get(depth - 1);
boolean parentPrintable = parent == null ? true : parent.isPrintable();
currentElement.setName(name, parentPrintable);
if (currentElement.isPrintable()) {
super.startNode(name);
}
}
private boolean _isCurrentElementPrintable() {
Elements currentElement = this.elements.get(depth);
return currentElement.isPrintable();
}
/**
* Evaluates if an element is printable or not.
* This is based on the concurrent occurences of the element's name
* and if the parent element is printable or not.
*/
private class Elements {
private String name = "";
private int concurrentOccurences = 0;
private boolean parentPrintable;
public void setName(String name, boolean parentPrintable) {
if (this.name.equals(name)) {
concurrentOccurences++;
} else {
concurrentOccurences = 1;
}
this.name = name;
this.parentPrintable = parentPrintable;
}
public boolean isPrintable() {
return parentPrintable && concurrentOccurences <= maxConsecutiveOccurences;
}
}
}
The following listing shows, how the two classes can be used.
XStream xstream = new XStream(new StaxDriver());
StringWriter sw = new StringWriter();
PrettyPrintWriter pw = new PrettyPrintWriter(sw);
RestrictedCollectionWriter cw = new RestrictedCollectionWriter(pw, 3);
xstream.marshal(objectToMarshal, new RestrictedPrettyPrintWriter(cw, xstream.getConverterLookup(), 3));
I am fairly new to java and working on a project to simulate a CPU scheduler in Java and i am using a linked list to store each process object that is read in from a external master list. When I test print the processes and the variables they contain, everything comes out as expected but whenever I try and do something with them it stops working.
public class process
String ID;
int Arrive;
int ExecSize;
int Execstore;
int Tstart;
int Tend;
int quant;
public process(String ID,int Arrive,int ExecSize) {
this.ID = ID;
this.Arrive = Arrive;
this.ExecSize = ExecSize;
this.Execstore=ExecSize;
this.Tend = 0;
this.Tstart = 0;
this.quant = 4;
}
public void setquant(int update) {
this.quant = update;
}
public int getquant() {
return quant;
}
public void setExecSize(int update) {
this.ExecSize = update;
}
public void setTend(int update) {
this.Tend = update;
}
public void setTstart(int update) {
this.Tstart = update;
}
String getID() {
return ID;
}
int getArrive() {
return Arrive;
}
int getExecSize() {
return ExecSize;
}
int getTstart() {
return Tstart;
}
int getTend() {
return Tend;
}
int getExecstore() {
return Execstore;
}
and this is the class used for the simulation
public class fcfs {
int disp;
int Ttotal = 0;
int Exec;
int Turn;
int Wait;
String output;
LinkedList<process> Que = new LinkedList<process>();
LinkedList<process> Quecleared = new LinkedList<process>();
public fcfs(LinkedList<process> B,int D) {
Que.addAll(B);
disp=D;
}
public void run()
{
while (Que != null)
{
Ttotal = Ttotal + disp;
System.out.println(Que.getFirst().getExecSize());
Exec=Que.getFirst().getExecSize();
output += String.format("T%d: %s\n",Ttotal,Que.getFirst().getID());
Que.getFirst().setTstart(Ttotal);
Ttotal = Ttotal+Exec;
Que.getFirst().setTend(Ttotal);
Quecleared.add(Que.poll());
}
}
So whenever i use System.out.println I get the expected result that I read into the list. But anything else I try to do in reference to elements of the process object will not work. Any help would be greatly appreciated
while (!Que.isEmpty())
{
Ttotal = Ttotal + disp;
System.out.println(Que.peekFirst().getExecSize());
Exec=Que.peekFirst().getExecSize();
output += String.format("T%d: %s\n",Ttotal,Que.peekFirst().getID());
Que.peekFirst().setTstart(Ttotal);
Ttotal = Ttotal+Exec;
Que.peekFirst().setTend(Ttotal);
Quecleared.add(Que.pollFirst());
}
This shouldn't throw an error on Exec = Que.peekFirst().getExecSize();
That error is thrown when your container is empty.
EDIT
In your code you specified the condition Que != null. In java once an object has been instantiated it is no longer considered null even if it IS empty. Most likely what was happening here is you continued iterating through your while(Que != null) loop until you had called Que.poll() on all elements of the list.
After clearing the list you did not exit the loop because Que still was not null. Then calling getFirst() on the empty instance of a LinkedList threw an exception.
A similar situation can be seen here with null vs empty strings:
Difference between null and empty ("") Java String
EDIT 2
It also appears that your class methods for getID(), getExecSize(), etc are passing values by reference as opposed to copying their value. Thus any change you make after passing the reference from queue will alter any copies you tried to make of it.
This can be best avoided by creating a new instance of an object and returning that from your function. Shown in an answer on the question linked below:
class Foo {
private Bar myBar;
public Foo deepCopy() {
Foo newFoo = new Foo();
newFoo.myBar = myBar.clone(); //or new Bar(myBar) or myBar.deepCopy or ...
return newFoo;
}
}
For more information on ways to pass values as opposed to reference values of your pre-existing instances, as well as what a shallow copy actually is, check this link: In Java, what is a shallow copy?
I have made a Java class where I have defined a constructor and some methods but I get a NullPointer Exception, and I don't know how I could fix It.
public class Job {
String idJob;
int time;
int timeRun;
Job j1;
List<Job> startBeforeStart;
List<Job> restricted;
Job(String idJob, int time){
this.idJob=idJob;
this.time=time;
}
public boolean isRestricted() {
return restricted.size() != 0;
}
public void startsBeforeStartOf(Job job){
startBeforeStart.add(job);
job.restricted.add(this);
}
public void startsAfterStartOf(Job job){
job.startsBeforeStartOf(this);
}
public void checkRestrictions(){
if (!isRestricted()){
System.out.println("+\n");
}
else{
Iterator<Job> itR = restricted.iterator();
while(itR.hasNext()){
Job j1 = itR.next();
if(time>timeRun){
System.out.println("-\n");
time--;
}
else {
restricted.remove(j1);
}
}
}
}
#Override
public boolean equals(Object obj) {
return obj instanceof Job && ((Job) obj).idJob.equals(idJob);
}
public void run() {
timeRun++;
}
}
PS
Looking in a forum a user says that to fix the error I should make an ArrayList inside the constructor (without modify the received parameters that should remain String id and int time), but I haven't understand what He mean.
You are not creating an instrance of List<Job> for both the lists startBeforeStart and restricted - you only declare a variable, which is assigned with a null pointer.
Thus, whenever you try to access this List [for example: return restricted.size() != 0;] - you are trying to dereference a null pointer - which causes your NPE.
You should create an instance of the List - using the new operator [probably in the constructor].
Have a look at ArrayList and LinkedList and chose which is better for you.
For example, if you use to use an ArrayList for both, your c'tor should be something like:
Job(String idJob, int time){
this.idJob=idJob;
this.time=time;
startBeforeStart = new ArrayList<Job>();
restricted= new ArrayList<Job>();
}