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
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
If I have an ArrayList of Objects, and I want to sort them by one of the fields (string) in the Object, how would I do that?

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MEAT TREAT posted:

If you can change your objects you can have them implement the Comparator interface. Now you can use the sort the function in java.util.Collections class.

Ok cool, that led me to this

code:
	private class AlphaComparator implements Comparator {
		public String compare(Object obj1, Object obj2) {
			Product prod1 = (Product) obj1;
			Product prod2 = (Product) obj2;
			String name1 = (String) prod1.name;
			String name2 = (String) prod2.name;
			return name1.compareTo(name2);
		}
	}
What's wrong with my code? It's telling me type mismatch, cannot convert from int to string.

fletcher fucked around with this message at 04:49 on Mar 5, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Hah well I feel like an rear end. Thank you! Works great now.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

triplekungfu posted:

What type is name in the Product class? If it's a String already, you don't need those casts to String. It's only a minor issue, but every time I see stuff like that at work I die a little.

Thanks for the tip. Normally I'd try it both ways, but not when I needed to get that code checked in ASAP. I was just copying the example code from the link up above.

fletcher fucked around with this message at 15:21 on Mar 5, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to do this without int count?

code:
Iterator accountIds = accounts.keySet().iterator();
int count = 0;
while (accountIds.hasNext()) {
	if (count>0)
		qry+=",";
	qry += "'"+accountIds.next()+"'";
	count++;
}

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
edit: nevermind

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Thank you to all the replies about my previous question. I've got another one for you guys.

I want to find unique values from a collection SomeCollection. Right now I'm just iterating through the collection and throwing every value into a HashMap<String, String> SomeUniqueCollection, where the key and value are both the key from SomeCollection. Should I be using a different type of collection for SomeUniqueCollection since I don't really need a K,V but just a K? Or is there a better way to approach this?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

1337JiveTurkey posted:

HashSet does exactly what you're looking for.

Right on, thanks!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm looking to implement some charts on a Java web application. Right now I'm reading about JFreeChart. What are some others worth looking into? I'd prefer to go down either the static images route or possibly flash based for some user interaction, no applet type stuff.

fletcher fucked around with this message at 23:58 on Apr 25, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm trying to initiate a file download after a POST to a servlet, but it doesn't seem to work. What am I doing wrong? Almost the exact same code works for initiating a download from a GET request, just not for a POST. The only difference I see in firebug is Transfer-Encoding chunked. Do I need to set the content length?

response is my HttpServletResponse object.

code:
byte[] data = Base64Coder.decode(image.getBytes());
response.setContentType("image/jpeg");
response.setHeader("Content-disposition", "attachment; filename=\"something.jpg\"");
response.getOutputStream().write(data);
response.getOutputStream().close();

fletcher fucked around with this message at 01:57 on Jun 3, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to define an operator in java? It's not really necessary for what I'm doing, I was just curious...

Instead of:

ArrayList<Double> pointsList = divide(aggregatedPoints, dataSetSum);

Doing something like:

ArrayList<Double> pointsList = aggregatedPoints/dataSetSum;

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

BELL END posted:

You'd probably have to cast one or both of the variables as a double for it to return a double, this should work with Java5 or later.

I want it to return an ArrayList of Doubles, aggregatedPoints and dataSetSum are both ArrayList<Double>'s

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
If I'm writing a function that looks like:

code:
private LinkedHashMap<String, LinkedHashMap<String, Double>> getTerritoryTimeOff(Connection connection, GetUserInfoResult user, 
			HashMap<String, HashMap<String, String>> syncInfo, Integer scale, Boolean isSummary) {}
am I necessarily doing something wrong or designing this poorly? Is there something I should think about to make it simpler or is this already pretty simple? this function basically builds a SQL query, executes it, and returns the results.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Entheogen posted:

make your own class that encapsulates results of the query and return ArrayList< query_encapsulation_class >

you could probably do the same for syncInfo.

Also check if there are already classes out there in the standard API or the libraries you are using that already encapsulate the info you are dealing with here.

Could you elaborate a little more? I'm a bit confused on your explanation.

Do you mean doing something like:

SyncInfo syncInfo, instead of having it be a HashMap<String, HashMap<String, String>> and put some logical methods for accessing the content of it? What about with the query results?

fletcher fucked around with this message at 01:29 on Jun 26, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's a good way to store a table of information? I want to use the same function and be able to output the results as an HTML table or as an excel spreadsheet using the POI HSSF stuff. There's a mix between strings, ints, etc that are going to go in the table.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

epswing posted:

You might want to consider something out of the Swing library, namely the model that JTables use, TableModel. You can write your own implementation, or extend the existing DefaultTableModel to suit your needs.

Sweet, thank you!

Another question - I want to attempt to parse a date multiple times. If the first one fails I want to try a different format. The parse method throws a ParseException. What's the proper way to do what I want? It seems like it could be done with another try/catch inside the first catch, but that seems like the wrong way to do it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
How do I make a copy of a LinkedHashMap?

I want to modify products, but keep a copy of what the LinkedHashMap looked like before I modified the products. I thought declaring a new instance of a LHM and passing in the old one would work, but when I modify products, originalProducts is also modified. The clone() method for a LinkedHashMap doesn't seem at all useful, since it doesn't copy keys/values (what is it for?).

code:
LinkedHashMap<String, Product> originalProducts = new LinkedHashMap<String, Product>(products);
System.out.println(originalProducts);
products.get("something").name = "new product name";
System.out.println(originalProducts);
//originalProducts reflects the changes to products, not what I want

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's an easy way to encode html entities with java?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I have a string that contains some HTML that has <input> and <img> tags that aren't properly closed with a />

I'm thinking I can use the string.replaceAll(regex, replacement). I found a pattern that I want on regexlib.

It seems to find them just fine, but I'm not sure what to put for the replacement string that will preserve what the rest of the attributes.

somehtml = somehtml.replaceAll("<input([^>]*[^/])>", "<input />");

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a good way to figure out what is wrong with the html I am trying to render as a PDF with Flying Saucer and ITextRenderer? I have to deal with these issues every now and then and it's always a pain trying to figure out what it's throwing up on when I get a stack trace like:

code:
com.caucho.xml.XmlParseException: anonymous.xml:1: expected name at ` '
        at com.caucho.xml.XmlParser.error(XmlParser.java:2972)
        at com.caucho.xml.XmlParser.parseEntityReference(XmlParser.java:1069)
        at com.caucho.xml.XmlParser.parseNode(XmlParser.java:349)
        at com.caucho.xml.XmlParser.parseInt(XmlParser.java:256)
        at com.caucho.xml.AbstractParser.parseImpl(AbstractParser.java:736)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:909)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:890)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:873)
        at com.caucho.xml2.parsers.AbstractDocumentBuilder.parse(AbstractDocumentBuilder.java:81)
Before I've just dumped the html to a text file, and then just comb through that by hand to try to figure out whats wrong. I'm having trouble doing that with this one though...any suggestions?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm having an issue using the POI HSSF library to write to an Excel file. There are 10,000+ rows that I am trying to output, each row is identified with a username. It appears one of the usernames is not playing nice with the HSSF stuff, and I get a "This spreadsheet has unreadable content..." message. I've been trying to narrow down which username is causing problems and I'm not getting anywhere. What is strange is I found that replacing every character:

code:
username = username.replaceAll(".", "A");
will cause the spreadsheet to output and open fine, with no error message, but if I do something like:

code:
username = username.replaceAll("[^A-Za-z0-9]", "A");
it will still produce the same error message.

Any suggestions?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've never done anything concurrently with threads and such in java. What's a good small project I can do to learn about them?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's a good way of figuring out the difference between two calendar objects and offsetting another calendar object by that amount?

Right now I'm using Calendar.getTimeInMillis(), which returns a long, and then just casting it to an int and using Calendar.add(). There's got to be a better way than that. Maybe using a loop and increment it one day at a time and just count the number of iterations to get to the other calendar?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got a string with an HTML snippet in it. I need a List of innerHTML for all the table cell elements. A regexp seems like the right tool, I'm just horrible at it. Can anybody help me out?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Save the whales posted:

Like this?

code:
String html = "<table><tr><td><a href=\"#\">foo</a><span>bar</span></td><td><div>baz</div></td></tr></table>";
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(?<=<td>).*?(?=</td>)").matcher(html);
while (m.find()) System.out.println(m.group());
I find this serves as a good reference for regex syntax: http://www.regular-expressions.info/reference.html

Doesn't seem to work when the cell has an attribute: <td onclick="what()"></td>

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

epswing posted:

Ensure you have jdom and jaxen on the classpath.

Thanks to both of you guys for the help, but I think I'm gonna have to go with epswing's solution for this one! Thank you!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What is the best way to copy part of a byte array into another byte array? Do I have to loop through it and copy it 1 by 1?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Mustach posted:

java.util.Arrays.copyOf()
java.util.Arrays.copyOfRange()
java.lang.System.arrayCopy()
The first two create the copy, the third takes the destination as a parameter

Sweet! Worked great. Thank you!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

wwqd1123 posted:

What I don't understand is why don't you have to go paint(Graphics g = new Graphics()) { because earlier on they mentioned that any object has to be created with the new command. I noticed that any time they create a new object from a class they always use the new command but not here?

You could, but it would look more like:

code:
paint(new Graphics());
But what would happen to "g" after paint() is done? It would disappear! You would probably want something like:

code:
Graphics graphics = new Graphics();
paint(graphics);
//now you can do something else with the graphics object

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm trying to find a good tutorial on using the org.w3c.dom stuff to output HTML. Is this not the correct tool for what I want to do? Or is there a template engine I should look at?

edit: I found StringTemplate, looks like it should do just fine.

fletcher fucked around with this message at 23:57 on Feb 1, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Looking for a way to generate some charts in Java and output to an image. JFreeChart looks pretty sweet, anything else I should check out before diving in?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Parantumaton posted:

Is pure image a necessity or are you doing a Web UI?

Just need a static image for this one. Already using Open Flash Chart for the web stuff.

necrobobsledder posted:

It doesn't actually fit your requirements, but if it has anything to do with showing a chart on a web page, you should probably look at Google Charts. The caveat is that it does require the user have some access to the Internet, so it breaks if they're in, say, a closed off datacenter.

That's what I used for the proof of concept. Google Charts are pretty neat, but it seems a bit limited in what you can do. Plus passing everything into the URL is a bit of a pain.

Fly posted:

We've been using http://jcharts.sourceforge.net/ for nearly a decade. It seems to work quite well.

I saw that one but I wasn't really impressed with their samples. They look so...Excel 97.

I've been playing around some more with JFreeChart. The amount of customization you can do seems to be very thorough. I think this might be the right engine.

JFreeChart + data URI scheme = :cool:

fletcher fucked around with this message at 00:04 on Feb 13, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Coredump posted:

I thought I was using Arraylist. The idea is I want to make a loop where I feed in a number and it spits out the number of arraylist for me. The program I'm working on is supposed to let someone enter in a bunch of names and specify a number of groups. Then the program is supposed to randomly take the names from the big list and stick them evenly into the number of list the user specifies. The idea is this program will be used in a situation where a teacher needs to split up everyone in class into even random groups.

So far my line of thinking was to stick all the names into an arraylist and use collections.shuffle to randomize the big list of arrays. Then I wanted to make a for loop to make the number of arraylist the user specifies. Then make some kind of loop that just goes through my big arraylist and copies, or moves the names into the newly created list.

Why do you need more than 1 ArrayList for this? Load all the names in a single ArrayList. Use Collections.shuffle to randomize the order. Then just loop through it and after x names, increase the group #.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Fly posted:

I'll check out JFreeChart when it comes time to redo our current charts.

I ended up buying the JFreeChart developer guide. They really put a lot of work into it, and you can do pretty much whatever you want with the charts. I'm really liking using it so far.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm trying to log some database queries that are generated using a custom class, QueryBuilder. I want to log some information about the user logged into my app executing the query as well as how long the query took etc.

Essentially I'm doing this:

code:
QueryBuilder queryBuilder = new QueryBuilder(bunch, of, stuff);
queryBuilder.setSomething(something);
String query = queryBuilder.getQuery();

Statement statement = connection.prepareStatement(query);
ResultSet resultSet = statement.executeQuery(query);

if (resultSet != null) {
    while (resultSet.next()) {
        //do stuff
    }
}

if (resultSet != null)
    resultSet.close();

if (statement != null)
    statement.close();
I do this all over the place, using my QueryBuilder class to generate a lot of different looking queries, with some similarities. I'm trying to think of a way to add the logging I want in as simple of a way as possible, but everything I come up with seems pretty messy. Any ideas?

edit: How about adding a getResultSet() to my QueryBuilder class? Is there a way to automatically have it call resultSet.close() and statement.close() when the QueryBuilder gets garbage collected? Do I even need to do that?

fletcher fucked around with this message at 20:27 on Feb 19, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm looking at different ways of making objects persistent in Java. I'm not sure if I want to go the RDBMS route and just use MySQL again and write my on SQL. JDO sounds interesting but I think MemcacheDB might be the way to go. What do you guys think? The idea of not having to write any SQL sounds nice, but I feel like I will run into limitations down the road.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Why does this work fine the first time, but subsequent calls give me the "you must be a registered user to view this page..."

code:
public static String fetchPage(String urlString) {
	StringBuilder page = new StringBuilder();
	try {
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("Cookie", "bbuserid=38563; bbpassword=editedout");
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			page.append(line);
		}
		reader.close();
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return page.toString();
}

String page = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");
			
String page2 = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

fletcher posted:

Why does this work fine the first time, but subsequent calls give me the "you must be a registered user to view this page..."

code:
public static String fetchPage(String urlString) {
	StringBuilder page = new StringBuilder();
	try {
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		conn.setRequestProperty("Cookie", "bbuserid=38563; bbpassword=editedout");
		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line;
		while ((line = reader.readLine()) != null) {
			page.append(line);
		}
		reader.close();
	} catch (MalformedURLException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return page.toString();
}

String page = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");
			
String page2 = SomethingAwful.fetchPage("http://forums.somethingawful.com/member.php?action=getinfo&userid=38563");

Bump! This is driving me nuts!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

I am in posted:

I looked at the cookie that is sent with Firebug. These keys have values: sessionid, __utma, aduserid, bbuserid, bbpassword and sessionhash.

Try to catch them all from your browser and see if it works. It's hard to say why it works the first time without knowing the internals of the forums software.

I was doing it before in PHP with just the bbuserid and bbpassword so I don't think that's the issue. I'm trying to do this on Google App Engine now.

fletcher fucked around with this message at 00:11 on Mar 17, 2010

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to check and see if anything has been written to a HttpServletResponse?

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