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
Amarkov
Jun 21, 2010
Can you explain, in as much detail as possible, what your SQL query is supposed to do? It doesn't make sense; I think you're making some fundamental mistakes about what an SQL database does.

Amarkov fucked around with this message at 23:03 on Nov 14, 2013

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

A Tartan Tory posted:

Another small question if I can get away with double posting this once. I'm now trying to make a dynamically generated table using SQL and java by doing the following.


However, I have a feeling my SQL is balls, because I keep getting exceptions when trying to use statistics.accessdata, pictures.ShortName, categories.ShortName from my container jcg. Can anyone give me an example of an SQL query that would work in this situation, to call up accessdata and the two different shortnames and then create a table displaying them ordered by the accesscount integer?

If your SQL has problems, then test it in SQL outside of any code first. Try executing that statement as is, by its lonesome, to prove the SQL isn't the problem or isolate it to that. (Plus then you get to see how the output is going to be formatted and double check that your code is going to receive what it expects) I don't have your database schema, but trying to execute that line of code gives me errors. Those errors tell you what you need to change.

What's going on here? Is jcg your database name, or is it a table? What's with all this 'statistics.accessdata' and 'pictures.shortname', are those supposed to be column names? I don't think those are valid. Are statistics and pictures themselves tables? Or are they supposed to be aliases? Or column names?

Your SQL syntax is way off, I don't even know what this is. :smith:

On the bright side, your code looks fine. I think your query is just fubar.

Zaphod42 fucked around with this message at 23:11 on Nov 14, 2013

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Amarkov posted:

Can you explain, in as much detail as possible, what your SQL query is supposed to do? It doesn't make sense; I think you're making some fundamental mistakes about what an SQL database does.

I most likely am because like I said, my SQL knowledge is balls and is about two weeks old at this point, I'm really just trying to learn how to use the very basics of it in conjunction with Java.

What I am trying to do is access my sql database, get the values from the rows AccessCount (in table statistics), ShortName (in table categories) and ShortName (in table pictures) and to use these to dynamically generate a table using java with it. I also want it to be ordered from highest to lowest by the integer in the AccessCount row. In a separate case, I'm also trying to use row AccessCount (in table Statistics), PictureNo (in table statistics) and ShortName (in table pictures) to generate a html link to certain pictures using the ShortName and AccessCount as what people are seeing as a link and the picture number at the end of the url like this 'ShowPicture?picture=1'. I have a feeling that once I understand how to do the first query, I will be able to understand the second.

jcg is Indeed my database that all of these tables are under, if that helps.

I hope this is enough information for you, like I said, I'm pretty new at this and still learning.

Zaphod42 posted:

On the bright side, your code looks fine. I think your query is just fubar.

Well at least I'm improving somewhere. :unsmith:

Amarkov
Jun 21, 2010

A Tartan Tory posted:

I most likely am because like I said, my SQL knowledge is balls and is about two weeks old at this point, I'm really just trying to learn how to use the very basics of it in conjunction with Java.

What I am trying to do is access my sql database, get the values from the rows AccessCount (in table statistics), ShortName (in table categories) and ShortName (in table pictures) and to use these to dynamically generate a table using java with it. I also want it to be ordered from highest to lowest by the integer in the AccessCount row. In a separate case, I'm also trying to use row AccessCount (in table Statistics), PictureNo (in table statistics) and ShortName (in table pictures) to generate a html link to certain pictures using the ShortName and AccessCount as what people are seeing as a link and the picture number at the end of the url like this 'ShowPicture?picture=1'. I have a feeling that once I understand how to do the first query, I will be able to understand the second.

jcg is Indeed my database that all of these tables are under, if that helps.

I hope this is enough information for you, like I said, I'm pretty new at this and still learning.

This doesn't make any sense. I don't know where you learned about SQL, but it went horribly wrong; I'm typing up an effortpost explaining the issues here, but you may just want to start over from the beginning. Do you need a link to some resources?

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Amarkov posted:

This doesn't make any sense. I don't know where you learned about SQL, but it went horribly wrong; I'm typing up an effortpost explaining the issues here, but you may just want to start over from the beginning. Do you need a link to some resources?

I guess so because I really don't understand where I'm going wrong here.

Volguus
Mar 3, 2009

A Tartan Tory posted:

I guess so because I really don't understand were I'm going wrong here.

From your previous posts it looks like you have multiple tables where that information is stored. Can you post the tables structure?
Here's one possibility:
Table statistics has columns pictureid, accessdata,AccessCount.
Table pictures has columns pictureid, shortname, longname, picture_blob, categoryid.
Table categories has columns categoryid, shortname.

Now, a query that will return all the pictures with the category and the accessdata can look something like:
code:
select st.accessdata, p.shortname, c.shortname from pictures p join statistics st on st.pictureid=p.pictureid join categories c on c.categoryid=p.categoryid order by st.AccessCount
As the others before me said, try running it against the database first and see what you get. This query posted by me most likely is wrong since i didn't test it, but it should look around these lines.

Then, to generate an HTML table from the servlet, you do:
code:
try {
 Statement stmt = con.createStatement();
 ResultSet rs;
 stmt = con.createStatement();
 rs = stmt.executeQuery(query);
 out.println("<table>");
 while (rs.next()) {
  out.println("<tr>");
  out.println("<td>"+rs.getString(1)+"</td>");//accessdata
  out.println("<td>"+rs.getString(2)+"</td>");//picture short name
  out.println("<td>"+rs.getString(3)+"</td>");//category shortname
  out.println("</tr>");
 }
 out.println("</table>");
 stmt.close();//should put this in a finally statement
}

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Thanks rhag, that was really helpful, I'll let you know how I get on. I think I see how I can do it now.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

A Tartan Tory posted:

jcg is Indeed my database that all of these tables are under, if that helps.

Yeah your SQL syntax is just like, entirely wrong. You don't reference the database name in a query, you're querying against a single database already. You can't query one database from another.

Go lookup SQL queries and read about the syntax for awhile, and make sure you really understand what a table and a column are.

SELECT <column>, <column> FROM <table> WHERE <condition> ORDER BY <condition>

Nowhere do you list <database> as part of the query. All of the columns, used in SELECT or WHERE or ORDER BY, MUST be listed as part of the FROM clause. (unless you do joins, which is more efficient, but more complicated syntax)

Periods should only be used for referencing table names or aliases, so SELECT a.name FROM person a would work, or otherwise without the alias you have to specify the full table name, SELECT person.name FROM person

Zaphod42 fucked around with this message at 23:48 on Nov 14, 2013

Amarkov
Jun 21, 2010
e: but I love teaching people basic SQL :(

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Amarkov posted:

e: but I love teaching people basic SQL :(

Aw your answer was better than mine was. :smith:

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Also check out the Database Megathread, some really helpful folks over there.

Don't worry A Tartan Tory, you'll be well on your way once you get a few things straightened out. I usually don't bother sticking queries in my code until I've run the query on the MySQL command line client first. MySQL Workbench is a pretty GUI utility if you prefer to go that route. (assuming you are using MySQL of course!)

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Thanks again guys, I know I'm really goddamn bad at this and appear to not have understood stuff (which I know is probably frustrating the poo poo outta you), but I really do appreciate your help. :unsmith:

fletcher posted:

Also check out the Database Megathread, some really helpful folks over there.

Don't worry A Tartan Tory, you'll be well on your way once you get a few things straightened out. I usually don't bother sticking queries in my code until I've run the query on the MySQL command line client first. MySQL Workbench is a pretty GUI utility if you prefer to go that route. (assuming you are using MySQL of course!)

I'm trying to how to use learn phpmyadmin, emphasis on the 'trying'.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

A Tartan Tory posted:

Thanks again guys, I know I'm really goddamn bad at this and appear to not have understood stuff (which I know is probably frustrating the poo poo outta you), but I really do appreciate your help. :unsmith:


I'm trying to how to use learn phpmyadmin, emphasis on the 'trying'.

Great choice, phpMyAdmin is really popular and has a lot of functionality. Just make sure that your instance of phpMyAdmin is not publicly accessible on the internet (even just to get to the login page). Put it behind basic http auth or something. I get random bots looking for exploitable phpMyAdmin instances on my server all day every day.

Your questions are not frustrating, we just have a lot that we want to teach you and sometimes it comes out a bit terse :) So bang on it a bit and when you get stuck, ask away! (you're gonna have tons more questions)

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

fletcher posted:

Great choice, phpMyAdmin is really popular and has a lot of functionality. Just make sure that your instance of phpMyAdmin is not publicly accessible on the internet (even just to get to the login page). Put it behind basic http auth or something. I get random bots looking for exploitable phpMyAdmin instances on my server all day every day.

Your questions are not frustrating, we just have a lot that we want to teach you and sometimes it comes out a bit terse :) So bang on it a bit and when you get stuck, ask away! (you're gonna have tons more questions)

Hah yeah, a friend of mine recommended it to me and showed me how to set it up relatively securely (I'm taking his word on it at the moment).

I'll keep banging on tomorrow and see what I can get done, I need a bit of a rest for my head because I'm making stupid mistakes now like not adding ; to the end of poo poo, so I'll probably see you all again tomorrow with much more questions!

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

rhag posted:

From your previous posts it looks like you have multiple tables where that information is stored. Can you post the tables structure?

Might as well do this before bed.

Tables: categories, pictures, statistics

categories has columns: CategoryNo, ShortName, Description, Folder
pictures has columns: PictureNo, CategoryNo, ShortName, Description and FileName
statistics has columns: PictureNo and AccessCount

Using your template I modified it to the following, which seemed to work when I queried the database outside the code.

quote:

select st.AccessCount, p.ShortName, c.ShortName from pictures p join statistics st on st.PictureNo=p.PictureNo join categories c on c.CategoryNo=p.CategoryNo order by st.AccessCount

Again, all I am trying to do is query the database to get the AccessCount integers, display the ShortName string associated with the AccessCount/PictureNo (the PictureNo in pictures and statistics have the same variables) and finally display the Category ShortName associated with the AccessCount/PictureNo/CategoryNo. Which is then turned into a table in java, ordered by the highest AccessCount integer to the lowest. So I *think* this is correct, if not, I'll try again tomorrow (and take it to the database thread so I don't keep annoying you fine java people with non-java, thanks fletcher!).

A Tartan Tory fucked around with this message at 00:53 on Nov 15, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Looks good to me :thumbsup:

Your code before looked good so now that you've tested your SQL query against the database itself, plug that sucker in! You didn't hardcode anything so even if the number of columns was off it'd still work, which is nice, but in other situations you'd wanna double check the output you get from the database itself to make sure its giving you the right format of output for your code to parse.

Also sorry if we sound critical; its totally okay you're making mistakes since you're learning. And if we're posting in these threads, it means we want to help people, so you don't have to feel bad or anything.

Zaphod42 fucked around with this message at 01:01 on Nov 15, 2013

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Zaphod42 posted:

Looks good to me :thumbsup:

Your code before looked good so now that you've tested your SQL query against the database itself, plug that sucker in! You didn't hardcode anything so even if the number of columns was off it'd still work, which is nice, but in other situations you'd wanna double check the output you get from the database itself to make sure its giving you the right format of output for your code to parse.

Also sorry if we sound critical; its totally okay you're making mistakes since you're learning. And if we're posting in these threads, it means we want to help people, so you don't have to feel bad or anything.

Thanks, I'll plug it in tomorrow after I get a little sleep, so I can tinker about with it after. Also posted it in the database thread to hopefully take the conversation outside the thread that really should be for java discussion (since I kinda do know how to translate the query into a table now thanks to all your help).

I'm sure I'll have more java related questions over the next few days though, g'night! Also be as critical as you need to be, I tend to learn by being told how moronic I am at something.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Hello, back again with another actual java related question!

quote:

try {
Statement stmt5 = con.createStatement();
ResultSet rs5;
stmt5 = con.createStatement();
rs5 = stmt5.executeQuery("select st.AccessCount, p.ShortName, p.PictureNo from pictures p join statistics st on st.PictureNo=p.PictureNo order by st.AccessCount");
out.println("<p><br><H3>Here are the most popular pictures recently, with access counts: (click to view)</H3>");
while (rs.next()) {
int pictureNo = rs.getInt("P.PictureNo");
int accessCount = rs.getInt("st.AccessCount");
String shortName = rs.getString("P.ShortName");
out.println("<a href=\"http://blahblah:80/jcg/ShowPicture.da?picture="+pictureNo+">"+shortName+" ("+accessCount+" )");
}
}

stmt.close() ;

I know this would probably work to display all the url's available in the database under those values, but can anyone give me an example where I can do this, but only 5 times before stopping? I assume I need some kind of 'for' in there but for the life of me I can't work it out.

pigdog
Apr 23, 2004

by Smythe
In your SQL you're using an "inner" join which requires there to be matching records in both "pictures" and "statistics" tables, thus it will only display the "pictures" for which there is a matching record in "statistics", too.

If you would want to display all of the "pictures", whether or not a matching "statistics" record exists, then you'd need an outer join, as in (not tested)

select st.AccessCount, p.ShortName, p.PictureNo from pictures p LEFT OUTER JOIN statistics st on st.PictureNo=p.PictureNo order by st.AccessCount

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

pigdog posted:

In your SQL you're using an "inner" join which requires there to be matching records in both "pictures" and "statistics" tables, thus it will only display the "pictures" for which there is a matching record in "statistics", too.

If you would want to display all of the "pictures", whether or not a matching "statistics" record exists, then you'd need an outer join, as in (not tested)

select st.AccessCount, p.ShortName, p.PictureNo from pictures p LEFT OUTER JOIN statistics st on st.PictureNo=p.PictureNo order by st.AccessCount

Bleh, so it was the sql again, thanks pigdog I appreciate it.

Zorro KingOfEngland
May 7, 2008

Quick tip: When you're posting code, use the code tags because they'll preserve your formatting. If you do it like this:

pre:
[code=java]
public static void main(String args[]) {
   System.out.println("butts");
}
[/code]
It'll even do syntax highlighting, like so:

Java code:
public static void main(String args[]) {
   System.out.println("butts");
}

LoneGun
Sep 18, 2003
St. Paddies is my most fav holiday evar! omg lol rolf
its been about 7-8 years since I have done any coding and my day to day job has numbed my mind when it comes to java.

What I am trying to do is examine a text file, search for a string and then examine the following 8 characters. If what I find is higher than a certain number I would like to move the file to a new folder. If anyone can help me out with this or give me some very basic pointers it would be much appreciated.
thanks in advance.

Volguus
Mar 3, 2009

A Tartan Tory posted:

Bleh, so it was the sql again, thanks pigdog I appreciate it.

And if you want only the first 5 records, you can use LIMIT in your query, such as "LIMIT 5". The next 5 could be shown with LIMIT 5,5, and so on.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

LoneGun posted:

its been about 7-8 years since I have done any coding and my day to day job has numbed my mind when it comes to java.

What I am trying to do is examine a text file, search for a string and then examine the following 8 characters. If what I find is higher than a certain number I would like to move the file to a new folder. If anyone can help me out with this or give me some very basic pointers it would be much appreciated.
thanks in advance.

How big are these files? Do they have any line breaks or other delimiters anywhere? If they're reasonably small, you could probably get away with reading each file's contents into a string and calling fileString.indexOf("my string") to get the start of your string, then do a substring and convert to an integer. If you know there is a delimiter (so that your string and the number would be between two delimiters) you could go delimiter to delimiter to save memory. java.nio.Files in Java 7 can move the file pretty concisely, but you could probably get away with opening a stream to a new file in the destination directory, write everything out, then delete the source file, all of which can be done with java.io.File if you're stuck on Java 6.

carry on then fucked around with this message at 17:28 on Nov 15, 2013

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

carry on then posted:

How big are these files? Do they have any line breaks or other delimiters anywhere? If they're reasonably small, you could probably get away with reading each file's contents into a string and calling fileString.indexOf("my string") to get the start of your string, then do a substring and convert to an integer. If you know there is a delimiter (so that your string and the number would be between two delimiters) you could go delimiter to delimiter to save memory. java.nio.Files in Java 7 can move the file pretty concisely, but you could probably get away with opening a stream to a new file in the destination directory, write everything out, then delete the source file, all of which can be done with java.io.File if you're stuck on Java 6.

You could just treat the string he's looking for as the delimeter, tokenize it based on that string, and then simply check the first 8 characters of each of the tokens.

Java code:
String input = "abunchoftextwhatever12345678andmoretextwhatever87654321";
String TARGET_STRING = "whatever";
StringTokenizer st = new StringTokenizer(str, TARGET_STRING);
while (st.hasMoreElements()) {
        try{
	    int value = Integer.parseInt(st.nextElement().subString(0,8));
        //if(value == something){ do something }
        }
        catch(Exception e){ System.out.println("NaN"); continue;}
}

Zaphod42 fucked around with this message at 17:41 on Nov 15, 2013

lamentable dustman
Apr 13, 2007

🏆🏆🏆

A Tartan Tory posted:

Hello, back again with another actual java related question!


I know this would probably work to display all the url's available in the database under those values, but can anyone give me an example where I can do this, but only 5 times before stopping? I assume I need some kind of 'for' in there but for the life of me I can't work it out.

The correct way would be to add a limit to the SQL query so your result set is only 5 rows. Since you are learning Java though you could exit the loop prematurely with the break key word

Java code:
int count = 0;
while (rs.next()) {
	// stuff
	count++;
	if(count == 5) {
		break;
	}
}
Or add conditionals to the while section

Java code:
int count = 0;
while (rs.next() && count < 5) {
	// stuff
	count++;
}

lamentable dustman fucked around with this message at 18:46 on Nov 15, 2013

Volguus
Mar 3, 2009

lamentable dustman posted:

The correct way would be to add a limit to the SQL query so your result set is only 5 rows. Since you are learning Java though you could exit the loop prematurely with the break key word

Java code:
int count = 0;
while (rs.next()) {
	// stuff
	count++;
	if(count == 5) {
		break;
	}
}
Or add conditionals to the while section

Java code:
int count = 0;
while (rs.next() && count < 5) {
	// stuff
	count++;
}

That is the dumb and very incorrect way. Retrieve everything from the database, and let me handle it on the software side. Yea ... of course im smarter than the retards who write databases for a living.
If you're being paid to write code, please don't do this to your client unless he's a really lovely client.
(think about getting row 1000000 to 1000005, how efficient that is)


Every database has a limiting facility of some kind in a select statement (even sqlite). Use LIMIT. Learn a bit of SQL. Or not, and use an ORM, it'll do it for you.

Volguus fucked around with this message at 02:58 on Nov 16, 2013

Woodsy Owl
Oct 27, 2004
Is there an elegant way to escape the blocking java.net.ServerSocket.accept() ? I've got a thread dedicated to listening and it's got something like this going on:

Java code:
...run () {

    try {

        this.serverSocket = new ServerSocket(6661);

        while (!this.isInterrupted()) { //if this listener thread has had .interrupt() called

            Socket socket = serverSocket.accept();  //this method will block

            new DoStuffWithTheSocketThread(socket).start(); //instantiate a thread to do some work with the socket

        }

    } catch ...
I've done some research and there are a few suggestions that I've implemented to see how they work. I've tried just closing this.serverSocket from another method and then the .accept() will throw a SocketException which gets handled. I've also tried encapsulating the accepting socket outside the run() method of the thread and instantiating a new Socket.
These solutions work but the implementation is kind of messy. Is there a more elegant solution to this problem?

lamentable dustman
Apr 13, 2007

🏆🏆🏆

rhag posted:

That is the dumb and very incorrect way. Retrieve everything from the database, and let me handle it on the software side. Yea ... of course im smarter than the retards who write databases for a living.
If you're being paid to write code, please don't do this to your client unless he's a really lovely client.
(think about getting row 1000000 to 1000005, how efficient that is)


Every database has a limiting facility of some kind in a select statement (even sqlite). Use LIMIT. Learn a bit of SQL. Or not, and use an ORM, it'll do it for you.

Of course it is, that is why I said use a limit but he is learning Java so learning on how to control loop flow seemed more important

Volguus
Mar 3, 2009

lamentable dustman posted:

Of course it is, that is why I said use a limit but he is learning Java so learning on how to control loop flow seemed more important

Reading failure from my part, sorry.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Woodsy Owl posted:

Is there an elegant way to escape the blocking java.net.ServerSocket.accept() ? I've got a thread dedicated to listening and it's got something like this going on:

Disclaimer: I've never worked with sockets, and am approaching this purely as a "blocking call" problem. That being said, it seems to me like you could socket.setSoTimeout(somethingLow), and then just deal with your regular, expected SocketTimeoutExceptions.

Java code:
this.serverSocket = new ServerSocket(1234);
serverSocket.setSoTimeout(10);
while (!Thread.interrupted()) {
    Socket socket = null;
    try {
        socket = serverSocket.accept();
    } catch (SocketTimeoutException expected) {
        continue;
    }
    new DoStuffWithSocket(socket).start();
}

This will basically give you a 10 ms of trying to accept before you go back and check the thread's interrupted status. Is this what you were trying to do?

Gravity Pike fucked around with this message at 23:09 on Nov 16, 2013

Volguus
Mar 3, 2009

Woodsy Owl posted:

Is there an elegant way to escape the blocking java.net.ServerSocket.accept() ? I've got a thread dedicated to listening and it's got something like this going on:

Java code:
...run () {

    try {

        this.serverSocket = new ServerSocket(6661);

        while (!this.isInterrupted()) { //if this listener thread has had .interrupt() called

            Socket socket = serverSocket.accept();  //this method will block

            new DoStuffWithTheSocketThread(socket).start(); //instantiate a thread to do some work with the socket

        }

    } catch ...
I've done some research and there are a few suggestions that I've implemented to see how they work. I've tried just closing this.serverSocket from another method and then the .accept() will throw a SocketException which gets handled. I've also tried encapsulating the accepting socket outside the run() method of the thread and instantiating a new Socket.
These solutions work but the implementation is kind of messy. Is there a more elegant solution to this problem?

The way you have it looks ok. Another way it could be to connect to yourself (unblocking the accept()) and exit the loop at that time (via some variable of some kind let's say).
Or ... use nio. ServerSocketChannel can be set to non-blocking.

Woodsy Owl
Oct 27, 2004

Gravity Pike posted:

Disclaimer: I've never worked with sockets, and am approaching this purely as a "blocking call" problem. That being said, it seems to me like you could socket.setSoTimeout(somethingLow), and then just deal with your regular, expected SocketTimeoutExceptions.

Java code:
this.serverSocket = new ServerSocket(1234);
serverSocket.setSoTimeout(10);
while (!Thread.interrupted()) {
    Socket socket = null;
    try {
        socket = serverSocket.accept();
    } catch (SocketTimeoutException expected) {
        continue;
    }
    new DoStuffWithSocket(socket).start();
}

This will basically give you a 10 ms of trying to accept before you go back and check the thread's interrupted status. Is this what you were trying to do?

This is great, thanks! It's good to have many solutions to choose from.

rhag posted:

The way you have it looks ok. Another way it could be to connect to yourself (unblocking the accept()) and exit the loop at that time (via some variable of some kind let's say).
Or ... use nio. ServerSocketChannel can be set to non-blocking.

I'll take a look into nio

Woodsy Owl
Oct 27, 2004
I've got a "good Java coding practices" question. I'm working on a Server application that will be heavily threaded. The threads are probably only going to be called by the Server application. Right now the thread classes are nested inside the Server class. Is this the best practice? It sort of affects the readability of my code, so I'm tempted to declare them in their own file.

So, I guess the question boils down to this: if your supporting classes are only being used by one other class then is it a good idea to nest them inside that one other class or to declare them in a separate source file?

edit: A second coding practices/readability question: I try to add 'this.' to all calls to class member variable and method calls, but I notice that it is starting to affect the readability of my code. Is adding 'this.' a good habit to be in, is it considered standard practice?

Woodsy Owl fucked around with this message at 10:26 on Nov 17, 2013

Doctor w-rw-rw-
Jun 24, 2008

Woodsy Owl posted:

I've got a "good Java coding practices" question. I'm working on a Server application that will be heavily threaded. The threads are probably only going to be called by the Server application. Right now the thread classes are nested inside the Server class. Is this the best practice? It sort of affects the readability of my code, so I'm tempted to declare them in their own file.

So, I guess the question boils down to this: if your supporting classes are only being used by one other class then is it a good idea to nest them inside that one other class or to declare them in a separate source file?
As a matter of personal style I go hog wild on declaring packages, so tons of files is no big deal. Nesting classes that are never used anywhere else is a bit tricky, but my signpost is that if there is a tight integration of logic between the class and the inner class, I keep them in the same file. Else, I split them out.

Woodsy Owl posted:

edit: A second coding practices/readability question: I try to add 'this.' to all calls to class member variable and method calls, but I notice that it is starting to affect the readability of my code. Is adding 'this.' a good habit to be in, is it considered standard practice?
A matter of taste, I used to explicitly specify 'this' religiously, but then I stopped. Note that in inner classes, getting a reference to the outer class involves qualifying it as SomeParentClass.this.whatever.

Woodsy Owl
Oct 27, 2004

Doctor w-rw-rw- posted:

in inner classes, getting a reference to the outer class involves qualifying it as SomeParentClass.this.whatever.

I might not be understanding you right. I didn't think you could call out of a nested class to the parent class unless you passed it as some parameter through some constructor or method. I think that's part of the point of encapsulation, right? Is there some voodoo to access the parent class in the nested class without having to pass the instance of the parent class through some method/constructor?

Java code:
class Foo {

	class Bar {
		
		Foo parent;
		
		Bar (Foo parent) {
			this.parent = parent;
		}
		
		void doBarStuff () {
			System.out.println(parent.magicNumber);
		}
		
	}
	
	int magicNumber = 10;
	
	void doFooStuff () {
		new Bar(this).doBarStuff();
	}
	
	public static void main (String[] args) {
		Foo foo = new Foo();
		foo.doFooStuff();
	}
	
}

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Well well well, I guess it's time to talk about the different kinds of inner classes :woop:

I don't want to make a big effort post since that was already done here:
http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class

Read it and then ask us any follow up questions if you want.

Btw there is glaring problem with the example code you posted that makes it not work as mentioned in that SO thread, maybe after reading that you'll spot it ;)

Woodsy Owl
Oct 27, 2004

Hard NOP Life posted:

Well well well, I guess it's time to talk about the different kinds of inner classes :woop:

I don't want to make a big effort post since that was already done here:
http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class

Read it and then ask us any follow up questions if you want.

Btw there is glaring problem with the example code you posted that makes it not work as mentioned in that SO thread, maybe after reading that you'll spot it ;)

Cool man, I worked my way through that thread. Does this look any better to you? I think the glaring problem you were talking about was how I was instantiating an instance of Bar, and also unnecessarily passing in the parent object. This works just fine:

Java code:
class Foo {

    class Bar {
             
        void doBarStuff () {
            System.out.println(Foo.this.magicNumber);
        }
        
    }
    
    int magicNumber = 10;
    
    void doFooStuff () {
        new Foo.Bar().doBarStuff();
    }
    
    public static void main (String[] args) {
        Foo foo = new Foo();
        foo.doFooStuff();
    }
    
}
Compiles just fine and the output is as expected.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Yeah that was it, you weren't creating an instance of Foo. I'm glad you figured it out :)

Adbot
ADBOT LOVES YOU

pr0metheus
Dec 5, 2010
Why does this print c and not a?

code:
var items = ["a","b","c"];
var obj = {};
 
for( var i = 0; i < items.length; ++i )
{
        var item = items[i];
        obj[item] = function(){ console.log(item);};
}
 
obj.a();
while the following one prints out a as expected?

code:
var items = ["a","b","c"];
var obj = {};

function makeIt( arg )
{
	return function(){console.log(arg);};
}

for( var i = 0; i < items.length; ++i )
{
	var item = items[i];
	obj[item] = makeIt(item);
}

obj.a();

pr0metheus fucked around with this message at 06:12 on Nov 20, 2013

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