Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
CJ
Jul 3, 2007

Asbungold
When i try to add this package to my project, Maven is telling me "DependencyResolutionException: Could not find artifact net.openhft:Java-Thread-Affinity:jar:3.2.3 in central (https://repo1.maven.org/maven2/)". I can see the jar on maven central https://repo.maven.apache.org/maven2/net/openhft/affinity/3.2.3/. It can download the pom fine, but not the jar. Am i missing something incredibly obvious? This is what i have in my pom:

<dependency>
<groupId>net.openhft</groupId>
<artifactId>Java-Thread-Affinity</artifactId>
<version>3.2.3</version>
</dependency>

Adbot
ADBOT LOVES YOU

BabyFur Denny
Mar 18, 2003

CJ posted:

When i try to add this package to my project, Maven is telling me "DependencyResolutionException: Could not find artifact net.openhft:Java-Thread-Affinity:jar:3.2.3 in central (https://repo1.maven.org/maven2/)". I can see the jar on maven central https://repo.maven.apache.org/maven2/net/openhft/affinity/3.2.3/. It can download the pom fine, but not the jar. Am i missing something incredibly obvious? This is what i have in my pom:

<dependency>
<groupId>net.openhft</groupId>
<artifactId>Java-Thread-Affinity</artifactId>
<version>3.2.3</version>
</dependency>

Shouldn't artifact id be 'affinity'?

CJ
Jul 3, 2007

Asbungold

BabyFur Denny posted:

Shouldn't artifact id be 'affinity'?

God dammit, you're right. I was pointing at this one https://repo.maven.apache.org/maven2/net/openhft/Java-Thread-Affinity/3.2.3/. I knew it would be something incredibly loving stupid like that. Thanks.

FateFree
Nov 14, 2003

Another question about WSDL/CXF/JAXB. So I can consume the wsdl, generate java objects, but its creating invalid requests when I invoke service operations and the difference is that in SoapUI I'm seeing one name for the elements and in CXF's ouput I'm seeing different names.

So take this field for example:

code:
@XmlElementRef(name = "Items", namespace = "http://blahblah", type = JAXBElement.class, required = false)
    protected JAXBElement<ArrayOfNewOrderItem> items;
In SoapUI, the sample request has:

code:
<Items>...</Items>
but in the CXF output it has:

code:
<ArrayOfNewOrderItem>...</ArrayOfNewOrderItem>
which I'm guessing is breaking things. How can I force CXF to use the name in that annotation instead of the actual generated class name?

EDIT:
Some extra info, this is apparently happening because I'm creating the item through objectFactory.createArrayOfItems() which is internally using a QName of that long name. I don't know if I can change that QName generation somehow. I can just make JaxbElements myself with the right names but its annoying and tedious, so I'd love any suggestions.

EDIT:
Nevermind, its all figured out. There are apparently nested objects I was supposed to use, like objectFactor.createOrderArrayOfItems and whatnot. No wonder this poo poo went extinct.

FateFree fucked around with this message at 10:58 on Jun 18, 2021

Good Will Hrunting
Oct 8, 2012

I changed my mind.
I'm not sorry.
I'm trying to spin my own very small queue listener and don't remember how we did things at my last job. Is there anything wrong with registering a thread pool with a schedule to run a Runnable every X seconds for polling SQS? If I go that route, is the JVM smart enough to not shut down since there will always be work to be done?

On top of that, is a shutdown hook the idiomatic way to terminate a "daemon" like this running in a remote EC2 instance or ECS task or something where I want to log and write out info upon shutdown? Not sure I'm aware of a better way.

adaz
Mar 7, 2009

Good Will Hrunting posted:

I'm trying to spin my own very small queue listener and don't remember how we did things at my last job. Is there anything wrong with registering a thread pool with a schedule to run a Runnable every X seconds for polling SQS? If I go that route, is the JVM smart enough to not shut down since there will always be work to be done?

On top of that, is a shutdown hook the idiomatic way to terminate a "daemon" like this running in a remote EC2 instance or ECS task or something where I want to log and write out info upon shutdown? Not sure I'm aware of a better way.

The way to do this in AWS is to register a lambda to respond to the SQS event, the lambda would spin up read message do stuff then shut down.

There are a couple frameworks explicitly built for this - quarkus, Micronauts - type of very ephemeral short lived processing .

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
xpost from the webdev thread, maybe someone could chime in if they have Java-specific solutions to the request parameters question.

Volguus
Mar 3, 2009

Paul MaudDib posted:

xpost from the webdev thread, maybe someone could chime in if they have Java-specific solutions to the request parameters question.

Better way? Other than the suggested Map<String, String> or MultiValueMap<String, String> ? This is probably the best way if you want to keep the values that you're sending (specific parameters). Another way, what I have done a long time ago to implement a (primitive) search for a website was to send a query string (?search="....")to the backend, parse it with ANTLR (simple grammar, nothing fancy), construct my "AST" essentially and generate the needed SQL from that.
Is it better? No idea honestly. But it was interesting at the time, to dive a bit into ANTLR. It was working and it was cool, I can say that. Easy to extend too.

Objective Action
Jun 10, 2007



If you are already using Spring it might be worthwhile to look at something like the GraphQL integration to see another way to go about handling that problem as well. Even if you decide not to use it just looking at the way they built the API might give you some ideas.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
Spring @Transactional seems to come with an awful lot of caveats (transactions aren’t managed for self referential @transactional calls, public methods only, etc). It’s been annoying to try and figure out what works - it seems like you need to leave it with a transaction open (because it wants to commit or rollback after), and we have also had some potentially leaking connections that we think might be related to it (it’s either that or hikaripool it seems - we have threads that wait and can’t get connections until after timeout).

https://www.baeldung.com/transaction-configuration-with-jpa-and-spring

I feel like I have to be making this way more complicated than it needs to be. What’s the successful pattern here, transactional annotation on top level methods only, leave the transaction open (marked for rollback if desired) and if you want to manually commit a transaction (to guarantee deferred constraint checks, etc) and take some response to what happens you have to open a second one for the after-method-return interceptor to work with?

Or do people scatter transactional deeper in their code as well as some high level methods (controllers/etc) and the transaction only gets committed when exiting from transactional code back to non-proxied code?

Paul MaudDib fucked around with this message at 07:33 on Oct 5, 2021

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Paul MaudDib posted:

Spring @Transactional seems to come with an awful lot of caveats ...

It's been quite some time since I used this, so I might be misremembering some details.

I'm pretty sure we used some kind of configuration that allowed it to work with private methods. Cglib proxies or something.

By self-referential transactional calls, do you mean recursive ones, where a transactional is nested inside of itself? I don't remember that being a problem, but there are different settings for handling nested transactions as well.

I also seem to remember Spring Transactional having some weird issues with exception handling. Like it only works properly with certain types of exceptions, unless you add some extra config. It might be possible that something throwing an exception somewhere is causing those transactions to hang because you expect them to be getting rolled back but they aren't, and end up just sitting there waiting for either a commit or rollback.

Pedestrian Xing
Jul 19, 2007

Paul MaudDib posted:

had some potentially leaking connections that we think might be related to it (it’s either that or hikaripool it seems - we have threads that wait and can’t get connections until after timeout)

Is this related to the "clock skew detected" error messages?

WRT @Transactional, if you need fine-grained control you might be better using a TransactionTemplate. Does the same thing but let's you control the boundaries instead of them being fixed to the entry and exit of a proxied method.

Twerk from Home
Jan 17, 2009

This avatar brought to you by the 'save our dead gay forums' foundation.
I feel great shame in asking this, but what's the best way to run java web start on a Mac in 2021?

I'm giving https://openwebstart.com/ a shot, which looks promising, is currently supported on latest java 11, and has active development so I would assume that there's years of support ahead of them, along with a move to Java 17.

Anybody else have solutions for using java web start applications?

Small White Dragon
Nov 23, 2007

No relation.
Which JDK is best for use on Apple Silicon?

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Small White Dragon posted:

Which JDK is best for use on Apple Silicon?

I would use the one from https://adoptium.net/releases.html, but your question sounds like there is some hidden implication that I'm not aware of.

Small White Dragon
Nov 23, 2007

No relation.

Wheany posted:

I would use the one from https://adoptium.net/releases.html, but your question sounds like there is some hidden implication that I'm not aware of.

I haven't needed to grab a new one in a while, and I know Oracle had been imposing some license changes that people were upset about. I'm not sure which variants (OpenJDK? Zulu?) are good these days.

...I'd not heard of Adoptium, honestly.

I just need to run some data processing tools that are either CLI-based or have very simple AWT/Swing UIs.

Small White Dragon fucked around with this message at 20:56 on Oct 29, 2021

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
Oracle finally backed off those changes a few weeks ago, back to CDDL iirc. I assume at this point the damage is done though.

Big companies where the CTO golfs with the Oracle rep, yeah Oracle tactics work there, but I can’t imagine they got any significant number of home users to sign up for a $200/year license for freaking Java.

adaz
Mar 7, 2009

All the major JDKs pass the full suite of regression tests and are functionally more or less identical. I tend to stick with AdoptOpenJDK (now known as Eclipse Temurin) because it simply has the most widespread usage, bunch of prebuilt docker images and im lazy. Oracle can gently caress off and would never use their stuff in a million years ever again so that's a no from me.


I got annoyed with Amazon's JDK because they didn't by default shut off TLS10 and it pissed me off when it showed up in a security audit.

adaz fucked around with this message at 21:12 on Oct 29, 2021

ulmont
Sep 15, 2010

IF I EVER MISS VOTING IN AN ELECTION (EVEN AMERICAN IDOL) ,OR HAVE UNPAID PARKING TICKETS, PLEASE TAKE AWAY MY FRANCHISE

Paul MaudDib posted:

Oracle finally backed off those changes a few weeks ago, back to CDDL iirc.

Link?

Edit: nevermind, https://blogs.oracle.com/java/post/free-java-license

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Small White Dragon posted:

...I'd not heard of Adoptium, honestly.

AdoptOpenJDK rebranded :nallears:

Twerk from Home
Jan 17, 2009

This avatar brought to you by the 'save our dead gay forums' foundation.

Small White Dragon posted:

Which JDK is best for use on Apple Silicon?

I cannot believe I have to say this, but it depends, and I'm having to juggle multiple JDKs depending on usage case, above and beyond having both 8 and 11 available.

If you are running a packaged application that uses JNI and has a native component, it probably doesn't have ARM binaries included if it targets desktop/laptop/server. This means that you need to use an x86_64 JVM, because Rosetta cannot handle inter-mixing aarch64 and x86_64 in a single application, so you need the whole thing to be x86. If you are compiling the application yourself, is the native part portable? Are you sure? A ton of JNI code assumes x86, and in a best case you may be able to slap something in there like sse2neon, which I've used with several applications, or worst case it will die in cryptic ways. In this situation, you want an x86 JDK again.

The crappy part is that running x86 code is markedly harder on battery life, so if you have an application that is pure Java, no JNI, or explicitly targets Apple Silicon, then you really do want to run an aarch64 JVM and enjoy better performance and longer battery life.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
two questions, the second may obsolete the first but I've been wondering about #1 anyway so an answer would be great if possible:

1. We have a List<Object[ ]>. What I want is a list of stream.map(row -> row[0]) - each element in the list is an array, I want the first element from the array. Can't quite figure the syntax on that.

2. In hibernate, when you are doing a "SELECT a, b FROM ..." what you get is an array by default. I can't remember, is there a nicer syntax for telling a query that it's going to return a Tuple<MyEntity, String> or something like that?

Objective Action
Jun 10, 2007



Paul MaudDib posted:

two questions, the second may obsolete the first but I've been wondering about #1 anyway so an answer would be great if possible:

1. We have a List<Object[ ]>. What I want is a list of stream.map(row -> row[0]) - each element in the list is an array, I want the first element from the array. Can't quite figure the syntax on that.

2. In hibernate, when you are doing a "SELECT a, b FROM ..." what you get is an array by default. I can't remember, is there a nicer syntax for telling a query that it's going to return a Tuple<MyEntity, String> or something like that?

1. For a List<Object[]> your proposed syntax should be correct. List<> foo; foo.stream().map(arr -> arr[0]) should go from List<Object[]> to Stream<Object>?

2. If the object you want has a no argument public constructor and is a bean that matches all the field names you can just make the return type of the query the object and Hibernate will map it:
Thing t = query.execute("select blah1, blah2 from OtherThing").

Otherwise you can call a constructor from HQL directly:
Thing t = query.execute("select new Thing(o.blah1, o.blah2) from OtherThing o").

asur
Dec 28, 2012
1. As Objective Action said the syntax looks correct to get a Stream of objects. If you want List<Object> you then need .collect(Collectors.toList()) after. You should also probably filter for the size of the array is at least 1 before accessing it unless you can safely assume it is.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
So, we have the basic setup where there's a shared jar with common/library code, and then multiple services that depend on that jar.

When you declare a class as @Controller or @ControllerAdvice, unlike (eg) a bean/service where it's only instantiated if autowired by something else, if that lives in the common jar, that basically becomes active whether you wanted to or not. Is there a way to offer the class to other jars but not actually force it to be utilized merely by including the library?

One option would obviously be to move it to its own package space - so you can include everything in com.ourCoolApp.common.* but not include com.ourCoolApp.commonControllers. And I guess maybe you could further break every class into its own package so they could be included like com.ourCoolApp.uncommon.controllers, com.ourCoolApp.uncommon.controllerAdvice, etc but that seems like a hack since it depends on people knowing they can't just include "com.ourCoolApp.*".

Can you declare the annotations inside the classes (eg @RequestMapping, etc) but not actually do the final @Controller that tells Spring to pay attention inside the library code, and then just have a MyControllerImplementation extends MyControllerAbstract and put the annotation on that?

Or maybe you can not put the annotations on the class, but somewhere in the configuration there's also a programmatic way to say "this specific class should be included as a ControllerAdvice even though it's not annotated?"

What's the "standard" way to do this here?

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.
The standard way, if you're using Spring Boot, is to create autoconfiguration classes that instantiate the controllers, controlleradvices, etc. You'd remove the annotations, you'd instantiate them in an autoconfiguration class in the shared jar, and that autoconfiguration itself can be made conditional on all sorts of things (e.g. a configuration property, the existence of a certain class in the classpath, etc).

See this for more info.

Esran
Apr 28, 2008

Paul MaudDib posted:

Oracle finally backed off those changes a few weeks ago, back to CDDL iirc. I assume at this point the damage is done though.

Big companies where the CTO golfs with the Oracle rep, yeah Oracle tactics work there, but I can’t imagine they got any significant number of home users to sign up for a $200/year license for freaking Java.

As I understand it, that wasn't their goal. Since somewhere around Java 11, the OpenJDK has had all the bits and pieces like JFR or Mission Control that used to be exclusive to the Oracle build. Since there is no longer anything special about the Oracle build compared to any other OpenJDK build, they switched to providing their build under the more restrictive license requiring a support contract. I think the idea was if you don't pay Oracle for support, there is no reason to download their build, and you should just grab one of the free builds instead.

The changes they made by open-sourcing the parts that used to be reserved for the Oracle build was a good thing. Not sure how they managed to gently caress up communication on this so badly.

Mycroft Holmes
Mar 26, 2010

by Azathoth
Working on a project for class. I have to change part of the work from composition to inheritance. I have no idea how to do that. The only hint I am given is that Class CarLot should have no attributes when I'm done. Here are the relevant classes.

code:
package carlot;
import java.io.*;
import java.util.*;

public class CarLot {
	private ArrayList<Car> inventory = new ArrayList<Car>();
	File file = new File("c:\\cars.csv");
    
	public ArrayList<Car> getInventory() {
		return inventory;
	}

	public void setInventory(ArrayList<Car> inventory) {
		this.inventory = inventory;
	}
	
	public void addCar(String ID, int mileage, int MPG, double cost, double salesprice) {
		Car c = new Car(ID, mileage, MPG, cost, salesprice);
	    inventory.add(c);
	}
	
	public void sellCar(String identifier, double priceSold) throws Exception{
		Car c = null; boolean Sold=false;
	    ListIterator<Car> it = inventory.listIterator();
	    while(it.hasNext()) {
	      c = (Car)it.next();
	      if(!c.isSold() & identifier.equalsIgnoreCase(c.getID())) {
	        c.sellCar(priceSold);
	        Sold = true;
	           }
	       }
	       if(!Sold) {
	           throw new Exception("Car can't be sold.");
	       }
	}
	
	 public Car findCarByIdentifier(String identifier) {
	       Car c = null;
	       ListIterator<Car> it = inventory.listIterator();
	       while(it.hasNext()) {
	           c = (Car)it.next();
	           if(identifier.equalsIgnoreCase(c.getID())) {
	               break;
	           }
	       }
	       return c;
	   }
	   public ArrayList<Car> getCarsInOrderOfEntry() {
	       ArrayList<Car> inventoryCopy = inventory;
	       return inventoryCopy;
	   }
	   public ArrayList<Car> getCarsSortedByMPG() {
	       ArrayList<Car> inventoryCopy = inventory;
	      inventoryCopy.sort(Comparator.comparingInt(Car::getMPG));
	       return inventoryCopy;
	   }
	   public Car getCarWithBestMPG() throws Exception{
	       Car bestMPGCar = inventory.get(0); Car c = null;
	       ListIterator<Car> it = inventory.listIterator();
	       while(it.hasNext()) {
	           c = (Car)it.next();
	           if(bestMPGCar!=null && c.compareMPG(bestMPGCar)>0) {
	               bestMPGCar=c;
	           }
	       }
	       return bestMPGCar;
	   }
	   public Car getCarWithHighestMileage() throws Exception{
	       Car highestMileageCar = inventory.get(0); Car c = null;
	       ListIterator<Car> it = inventory.listIterator();
	       while(it.hasNext()) {
	           c = (Car)it.next();
	           if(highestMileageCar!=null && c.compareMileage(highestMileageCar)>0) {
	               highestMileageCar=c;
	           }
	       }
	       return highestMileageCar;
	   }
	   public double getAverageMPG() throws Exception{
	       double averageMPG=0; double totalMPG=0; Car c=null;
	       ListIterator<Car> it = inventory.listIterator();
	       while(it.hasNext()) {
	           c = (Car)it.next();
	           totalMPG+=c.getMPG();
	       }
	       averageMPG=totalMPG/(inventory.size());
	       return averageMPG;
	   }
	   public double getTotalProfit() throws Exception {
	       double totalProfit = 0; Car c=null;
	       ListIterator<Car> it = inventory.listIterator();
	       while(it.hasNext()) {
	           c = (Car)it.next();
	           if(c.isSold()) {
	               totalProfit+=c.getProfit();
	           }
	       }
	       return totalProfit;
	   }
	        
			   


	public void loadFromDisk() throws IOException {
		try(BufferedReader br = new BufferedReader(new FileReader(file))) {
			String line = "";
			ArrayList<Car> Copy = new ArrayList<Car>();
	        while ((line = br.readLine()) != null) {
	        	String array[] = line.split(",", 0);
	        	String ID = array[0];
	        	int mileage = Integer.parseInt(array[1]);
	        	int MPG = Integer.parseInt(array[2]);
	        	Double cost = Double.parseDouble(array[3]);
	        	Double salesprice = Double.parseDouble(array[4]);
	        	Boolean sold = Boolean.parseBoolean(array[5]);
	        	Double pricesold = Double.parseDouble(array[6]);
	        	Double profit = Double.parseDouble(array[7]);
	    		Car c = new Car(ID, mileage, MPG, cost, salesprice);
	    		c.setSold(sold);
	    		c.setPriceSold(pricesold);
	    		c.setProfit(profit);
	    	    Copy.add(c);
	        }
	        inventory = Copy;
		}
		}

	public void saveToDisk() throws IOException {

		   FileWriter fw = new FileWriter(file);
	        for(int i=0;i<inventory.size();)
	        {
	        	 Car c = inventory.get(i);
	        	 fw.append(c.getID() + ",");
	        	 fw.append(c.getMileage() + ",");
	        	 fw.append(c.getMPG() + ",");
	        	 fw.append(c.getCost() + ",");
	        	 fw.append(c.getSalesPrice() + ",");
	        	 fw.append(c.isSold() + ",");
	        	 fw.append(c.getPriceSold() + ",");
	        	 fw.append(c.getProfit() + ",");
	        	 fw.append("\n");
	        	 i++;
	        }
	        fw.close();
	}

	}

code:
package carlot;


public class Car {
	private String ID;
	private int mileage;
	private int MPG;
	private double cost;
	private double salesPrice;
	private boolean Sold;
	private double priceSold;
	private double profit;
	
	public Car() {
		this.ID = null;
		this.mileage = 0;
		this.MPG = 0;
		this.cost = 0;
		this.salesPrice = 0;
		this.Sold = false;
		this.priceSold = 0;
		this.profit = 0;
	}
	
	public Car(String ID, int mileage, int MPG, double cost, double salesPrice) {
		this.ID = ID;
		this.mileage = mileage;
		this.MPG = MPG;
		this.cost = cost;
		this.salesPrice = salesPrice;
	}
	
	public java.lang.String toString() {
		String full = "";
		if (Sold){
			full = "\nCar: " + ID + " Mileage: " + mileage + " MPG: " + MPG + " Sold: Yes Cost: $" + String.format("%.2f", cost) +  " Sales price: $" + String.format("%.2f", salesPrice) +" Price Sold: $" + String.format("%.2f", priceSold) + " Profit: $" + String.format("%.2f", profit);	
		}
		else {
			full = "\nCar: " + ID + " Mileage: " + mileage + " MPG: " + MPG + " Sold: No Cost: $" + String.format("%.2f", cost) + " Sales price: $"+ String.format("%.2f", salesPrice);
		}
		return full;
		
	}
	
	
	public void sellCar(double priceSold) {
		Sold = true;
		this.priceSold = priceSold;
		this.profit = priceSold - cost;
		
	}
	
	public int compareMPG(Car otherCar) {
		int compare = 0;
		if (MPG > otherCar.MPG) {
			compare = 1;
		}
		else if (MPG < otherCar.MPG) {
			compare = -1;
		}
		else {
			compare = 0;
		}
		return compare;
	}
	
	public int compareMileage(Car otherCar) {
		int compare1 = 0;
		if (mileage > otherCar.mileage) {
			compare1 = 1;
		}
		else if (mileage < otherCar.mileage) {
			compare1 = -1;
		}
		else {
			compare1 = 0;
		}
		return compare1;

	}
	
	public double compareSalesprice(Car otherCar) {
		int compare2 = 0;
		if (salesPrice > otherCar.salesPrice) {
			compare2 = 1;
		}
		else if (salesPrice < otherCar.salesPrice) {
			compare2 = -1;
		}
		else {
			compare2 = 0;
		}
		return compare2;
	}

	
	public String getID() {
		return ID;
	}

	public void setID(String iD) {
		ID = iD;
	}

	public int getMileage() {
		return mileage;
	}

	public void setMileage(int mileage) {
		this.mileage = mileage;
	}

	public int getMPG() {
		return MPG;
	}

	public void setMPG(int mPG) {
		MPG = mPG;
	}

	public double getCost() {
		return cost;
	}

	public void setCost(double cost) {
		this.cost = cost;
	}

	public double getSalesPrice() {
		return salesPrice;
	}

	public void setSalesPrice(double salesPrice) {
		this.salesPrice = salesPrice;
	}

	public boolean isSold() {
		return Sold;
	}

	public void setSold(boolean sold) {
		this.Sold = sold;
	}

	public double getPriceSold() {
		return priceSold;
	}

	public void setPriceSold(double priceSold) {
		this.priceSold = priceSold;
	}

	public double getProfit() {
		return profit;
	}

	public void setProfit(double profit) {
		this.profit = profit;
	}

}
What should I extend and how do I change CarLot?

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

Mycroft Holmes posted:

Working on a project for class. I have to change part of the work from composition to inheritance. I have no idea how to do that. The only hint I am given is that Class CarLot should have no attributes when I'm done. Here are the relevant classes.
...
What should I extend and how do I change CarLot?

as someone who works on java every day, this assignment makes no sense. A CarLot isn't really a "kind of" car nor is a car a "kind of" CarLot.

The only thing I can figure out is they want you to have CarLot extend ArrayList<Car>? A CarLot is a "kind of' CarCollection I guess. And then you don't have to hardcode the filename, you can move it into a method and some other class (main?) calls it with a filename that it'd want to be used for output - nobody in the real world hardcodes a fixed value for where files should be written into the actual object, you pass a filename and hardcode it somewhere else (:haw:)

You can also trivially move everything in CarLot into an abstract CarCollection type and CarLot just extends CarCollection (technically correct, you smartass). But generally this assignment makes no sense and isn't really how inheritance would actually be used. I hate that about a lot of CS 101 inheritance/polymorphism and composition examples.

I'd email your professor and bring up the "extends ArrayList<Car>" approach and see what they say, because that's not a clear assignment at all just because those objects really make no sense in any other context except maybe a CarLot being a collection of cars with some extra functionality.

Paul MaudDib fucked around with this message at 00:39 on Dec 1, 2021

Objective Action
Jun 10, 2007



Specification is ambiguous but I had inferred that the problem was that a Car Lot is a specification of an ItemInventory<Item> and a Car is an Item, so therefore CarLot | ItemInventory<Car> and Car | Item or equivalent.

Makes more sense that way at least.

edit:

Also please stop returning and specifying concrete return types when you don't use any of the concrete methods. Return List<> and not ArrayList<>!

Objective Action fucked around with this message at 00:49 on Dec 1, 2021

Mycroft Holmes
Mar 26, 2010

by Azathoth
The specification is this:

quote:

Enhancement 1 - Change CarLot to Use Inheritance
The CarLot class currently has one attribute, inventory, which is of type ArrayList<Car>. CarLot HAS-A ArrayList<Car>.

Change the CarLot class so that it uses inheritance instead of composition. In other words, CarLot IS-A ArrayList<Car>. If required, modify the CarLotTester class as well.
Hint: Remove the inventory attribute
Grading Elements:
CarLot successfully uses inheritance
The CarLot tester runs successfully
CarLot has not attributes

DELETE CASCADE
Oct 25, 2017

i haven't washed my penis since i jerked it to a phtotograph of george w. bush in 2003
code:
	   public ArrayList<Car> getCarsInOrderOfEntry() {
	       ArrayList<Car> inventoryCopy = inventory;
	       return inventoryCopy;
	   }
	   public ArrayList<Car> getCarsSortedByMPG() {
	       ArrayList<Car> inventoryCopy = inventory;
	      inventoryCopy.sort(Comparator.comparingInt(Car::getMPG));
	       return inventoryCopy;
	   }
d...does he think that actually makes a deep copy of the list?

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
those who can, do; those who can't... :whitewater:

ivantod
Mar 27, 2010

Mahalo, fuckers.
Please, for god's sake, never ever ever code like this in real life! This is insanely bad and I can't believe this is how they are teaching you to do it.

For a moment I thought I confused this thread with the other one where we post people's bad code!

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

Sagacity posted:

The standard way, if you're using Spring Boot, is to create autoconfiguration classes that instantiate the controllers, controlleradvices, etc. You'd remove the annotations, you'd instantiate them in an autoconfiguration class in the shared jar, and that autoconfiguration itself can be made conditional on all sorts of things (e.g. a configuration property, the existence of a certain class in the classpath, etc).

See this for more info.

I can't figure out a way to programmatically configure a class as ControllerAdvice, only via the annotation.

what if I whipped up a method which takes a bean (clearly not a ControllerAdvice as you can tell from the plastic moustache and glasses) and uses reflection to walk it for methods containing the ExceptionHandler annotation and then register them all via an ExceptionHandlerExceptionResolver?

Mycroft Holmes
Mar 26, 2010

by Azathoth

ivantod posted:

Please, for god's sake, never ever ever code like this in real life! This is insanely bad and I can't believe this is how they are teaching you to do it.

For a moment I thought I confused this thread with the other one where we post people's bad code!

Can you be more specific as to what is wrong with my code? I'd like to improve.

hooah
Feb 6, 2006
WTF?

Mycroft Holmes posted:

Can you be more specific as to what is wrong with my code? I'd like to improve.

A few things from my point of view:
  • The formatting is very inconsistent (at least in what's pasted here), which makes reading a lot harder than it needs to be.
  • Stylistically, you shouldn't be starting variable or parameter names with capital letters (e.g. MPG or Sold). The convention is that class names start with capitals and variables with lower-case.
  • Functionally, there's very rarely a reason to use an iterator. Check out the for-each loop
  • A small thing, but in your comparison functions, you can just return the value immediately in the if/else branches.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Mycroft Holmes posted:

Can you be more specific as to what is wrong with my code? I'd like to improve.

I think ivantod is mainly talking about the unnecessary inheritance you're being asked to implement. Using inheritance like this is an approach that is often tantalizingly easy to begin with, but ultimately makes programs very inflexible and difficult to maintain, and has fallen out of favour in many professional circles for that reason.

It's challenging to offer criticism here because a lot of the bigger issues are likely to have been dictated to you by the assignment rather than something you have control over.

For example, two fundamental isues are:
- You wouldn't really write a CarLot class to begin with. You'd just have a List<Car>, and some utility methods that accept a List<Car>. Some of the methods you've been asked to implement you wouldn't even write in the first place - you'd just use some of the more generic collections methods that accomplish the same thing.
- You wouldn't write a mutable Car class with getters and setters. You'd write an immutable (can never be changed) Car class, that only has getters. For state that is expected to change, such as whether the car has been sold, you might track that in some other location rather than as a field in the Car class.

But it's likely that both of those decisions aren't ones that you made - they're things dictated to you, that you need to do even though they're not modern best practice.

Mycroft Holmes
Mar 26, 2010

by Azathoth

Jabor posted:

I think ivantod is mainly talking about the unnecessary inheritance you're being asked to implement. Using inheritance like this is an approach that is often tantalizingly easy to begin with, but ultimately makes programs very inflexible and difficult to maintain, and has fallen out of favour in many professional circles for that reason.

It's challenging to offer criticism here because a lot of the bigger issues are likely to have been dictated to you by the assignment rather than something you have control over.

For example, two fundamental isues are:
- You wouldn't really write a CarLot class to begin with. You'd just have a List<Car>, and some utility methods that accept a List<Car>. Some of the methods you've been asked to implement you wouldn't even write in the first place - you'd just use some of the more generic collections methods that accomplish the same thing.
- You wouldn't write a mutable Car class with getters and setters. You'd write an immutable (can never be changed) Car class, that only has getters. For state that is expected to change, such as whether the car has been sold, you might track that in some other location rather than as a field in the Car class.

But it's likely that both of those decisions aren't ones that you made - they're things dictated to you, that you need to do even though they're not modern best practice.

Yeah, that's what my teacher told me to do. Do you have any suggestions on how to complete the assignment?

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
It sounds like you need to make CarLot extend ArrayList<Car>, delete the inventory field, and then just refer to this anywhere you were previously referring to inventory. If it sounds dumb as hell then you're right, it is, because the assignment is dumb as hell.

And probably fix all the places you're trying to copy the list so that they actually make a copy.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply