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
zootm
Aug 8, 2006

We used to be better friends.

adante posted:

Howdy, if I have some Class<?> object (in my case, returned from a Field#getType() during reflection), how can I tell if the class represented by this object implements a particular interface or class? I guess this is the equivalent to the instanceof operator, except for the class type and not an object.
what you want is Class.isAssignableFrom( Class<?> ).

So something like the following, based on your example.
code:
boolean bIsAnA = A.class.isAssignableFrom( bClass );
boolean bIsAC = C.class.isAssignableFrom( bClass );
Both variables should be true.

Adbot
ADBOT LOVES YOU

adante
Sep 18, 2003

zootm posted:

what you want is Class.isAssignableFrom( Class<?> ).
too easy! thanks.

Another question: I am doing something which is probably insane and stupid where I have an abstract base class with a method that reflects on itself, collects all the fields and does many strange things with them (for the sake of this example, suppose the function prints them out)

The idea is I can then extend this class and add new fields, and then call the method which will print these newly added fields. However I want to automate this so that the method is called as soon as the object is instantiated!

I tried throwing this in the constructor of the abstract class but this is called before the derived class is instantiated.

So at the moment I have to instantiate the class, then call the method explicitly. I'm just wondering, is there a normal pattern for handling this (maybe with factory methods?) or am I just silly/insane for wanting to do it in the first place?

Some example code to hopefully explain the problem. The A() constructor calls reflect(), but the B fields are not yet initialized. When you call it after B() has finished it is fine, but I am anal and do not want to do this explicitly if possible.
code:

import java.lang.reflect.*;

public class test5 {

	public static void main (String [] args)
	{
		B b = new B();
		b.reflect();
	}
}

abstract class A {
	public A() {
		System.out.println("A constructor");
		reflect();
	}
	
	public void reflect()
	{
		for (Field f : this.getClass().getFields())
			try {
			System.out.println(f.getName() + " : " + f.get(this));
			} catch (IllegalAccessException e) {}
	}
}

class B extends A {
	public B() { System.out.println("B constructor"); }
	public String B_STRING = "hello this is B_STRING";
}

zootm
Aug 8, 2006

We used to be better friends.
I'm pretty sure that can't be done. And I don't think it's something that would be good to have in code anyone would use in any case.

dancavallaro
Sep 10, 2006
My title sucks
Just for shits and giggles, I'm writing a proxy server in Java. Well, it would even be a stretch to call it a proxy server - I guess my ultimate goal is to just be able to gently caress with my brother by sneaking on his computer and changing his Firefox proxy settings to use my server, and do things like send him to random websites, etc.

Right now, I just have a ServerSocket listening on port 12345 in an infinite loop, and when a client connects, it sends the client Socket off to a new thread, courtesy of a worker class. Right now all the worker class does is listen for HTTP GET requests, and then send back some stupid text like "sorry, teh internets is broken". This works fine so far and I understand what's going on. Then as an experiment, I tried to send the contents of CNN.com, no matter what page the client requested. But what happens is this: say for example the client is trying to go to http://www.yahoo.com. If the images and such on CNN are using relative URLs, so for example /images/CNNbanner.jpg, the client browser tries to fetch http://www.yahoo.com/images/CNNbanner.jpg, which is obviously wrong. I feel like maybe I'm going about this the wrong way, so what should I be doing?

tef
May 30, 2004

-> some l-system crap ->

dancavallaro posted:

I feel like maybe I'm going about this the wrong way, so what should I be doing?

You can always run a search and replace on the files coming back from the browser,
or if it is html you can add <base href="http://www.cnn.com/"> at the top

dancavallaro
Sep 10, 2006
My title sucks
Well gently caress me, I've never even heard of the base tag. That sounds perfect, exactly what I need. Thanks a lot, and I'll post back here if I have any problems.

epswing
Nov 4, 2003

Soiled Meat
dancavallaro that sounds like a fun project, are you using a library to interpret the request and send the response?

dancavallaro
Sep 10, 2006
My title sucks

epswing posted:

dancavallaro that sounds like a fun project, are you using a library to interpret the request and send the response?

If you know of a good library for that, I would love to hear about it. I'm at the very preliminary, experimental, loving-around stage right now. It's very naive and doesn't do any interpreting of requests.. all I want right now is to be able to successfully route *something* through the proxy server to the client, which I've sort of been able to do.

epswing
Nov 4, 2003

Soiled Meat
Well the first thing that comes to mind in the Java realm is Tomcat. I'm sure somewhere in servlet.jar there are classes to deal with HTTP requests/responses.

e: http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html
http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletRequestWrapper.html

epswing fucked around with this message at 18:58 on May 16, 2008

tef
May 30, 2004

-> some l-system crap ->

dancavallaro posted:

If you know of a good library for that

If you want to look at other languages there is HTTP::Proxy in perl, and twisted does stuff for python

dancavallaro
Sep 10, 2006
My title sucks

tef posted:

If you want to look at other languages there is HTTP::Proxy in perl, and twisted does stuff for python

Oh god, I'm not touching Perl with a ten-foot pole. I might look into twisted, and I'll check out Tomcat too. Thanks guys.

lekki
Mar 29, 2008

dancavallaro posted:


Right now, I just have a ServerSocket listening on port 12345 in an infinite loop...

That's not such a good idea. Check your cpu usage , it should be 100%. Let the thread sleep for some time or use wait().

epswing
Nov 4, 2003

Soiled Meat

lekki posted:

That's not such a good idea. Check your cpu usage , it should be 100%. Let the thread sleep for some time or use wait().

Untrue, ServerSocket's accept() blocks like wait(). http://java.sun.com/javase/6/docs/api/java/net/ServerSocket.html#accept()

quote:

Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

epswing fucked around with this message at 21:30 on May 18, 2008

lekki
Mar 29, 2008
Thanks, i was mistakenly comparing that listener to some queue listener is used some time ago.

shodanjr_gr
Nov 20, 2007
I am writing some SWING code for a UI and i have an issue.

I am using a custom container, which is basically a JPanel viewed through a JScrollPane (this class extends JScrollPane). On this JPanel i add another custom component (which extends JComponent and is a combination of JPanels and JTextPanes) multiple times.

My issue is the following.

Lets assume that the container has a heigth of X, and the component a height of X/4. If i add less than 4 components in the container, then, instead of leaving the rest of the viewport empty, the components somehow "stretch" to fill the viewport (which screws up their appearance big-time). If i add 4 or more, everything is fine and dandy...

Ive tried various layouts for the container, and it doesnt seem to be helping...

Any ideas fellow Java-goons?

If anyone needs code snippets let me know and ill post it.

PuTTY riot
Nov 16, 2002

shodanjr_gr posted:

I am writing some SWING code for a UI and i have an issue.

I am using a custom container, which is basically a JPanel viewed through a JScrollPane (this class extends JScrollPane). On this JPanel i add another custom component (which extends JComponent and is a combination of JPanels and JTextPanes) multiple times.

My issue is the following.

Lets assume that the container has a heigth of X, and the component a height of X/4. If i add less than 4 components in the container, then, instead of leaving the rest of the viewport empty, the components somehow "stretch" to fill the viewport (which screws up their appearance big-time). If i add 4 or more, everything is fine and dandy...

Ive tried various layouts for the container, and it doesnt seem to be helping...

Any ideas fellow Java-goons?

If anyone needs code snippets let me know and ill post it.

The code would probably help. Have you tried something like setLayout(new GridLayout 0,4)? If your component's size is not fixed that could have something to do with it too.

shodanjr_gr
Nov 20, 2007

American Jello posted:

The code would probably help. Have you tried something like setLayout(new GridLayout 0,4)? If your component's size is not fixed that could have something to do with it too.

Thing is, i dont have a fixed amount of components in the container, so i cant use Gridbag Layout beforehand... (i could try re-creating the layout every time the contents change though).

The size of the component is set during it's construction.

Ive "fixed" the problem, by adding filler-components when the actual contents are fewer than the number that fits inside viewport, but this is a dirty way to do things in my book...

Which parts of the code do you need? Its a bit heft (1k lines roughly) and intertwined between several classes/packages. Let me know and ill get it :)

epswing
Nov 4, 2003

Soiled Meat
Try and code yourself a working example independent of your real project. It should contain only the code necessary for what you want to do. If that example doesn't work, it's easy to pass around to others and ask "why doesn't line XX do what I think it's supposed to do?"

joojoo2915
Jun 3, 2006
Ok, so I am working on a program that displays some information for different places on a google map and I would like the user to be able to transfer that information to a form by hitting the submit button that shows up on the little google map information popup. I can get the button to pass information so long as there isn't a space anywhere in the string. If there is a space the information will not pass and firebug says the error is an Unterminated Literal String Error, and will show code up to the space in the string. The offending bit of code is:

info = <%= chr(34) & company(mm) & "<br>" & address(mm) & "<br>" & city(mm) & ", " & state(mm) & "<br>" & "Phone: " & phone(mm) & "<br>" & email(mm) & "<br>" & "<FORM NAME=myform ACTION= METHOD=GET><input type = button Name = SelectButton Value = Select this market onClick = writeText("Grain","100" & "street","Bozeman","2225799")></form>" & chr(34)%>;

<script type = "text/javascript">
function writeText (company, address, city, phone, marketnum) {
document.pushform.textbox_companyname.value = company;
document.pushform.textbox_address.value = address;
document.pushform.textbox_city.value = city;
document.pushform.textbox_phone.value = phone;

}


I hope to one day put variables in place of the text in the writeText function, but as it is this will work so long as there are no spaces. Any ideas?

the onion wizard
Apr 14, 2004

I'm not entirely clear on what you're trying to do, is that part of a JSP?

You should probably throw some apostrophes or quotes around your attributes, and the parameters for your form don't look right at all ('ACTION= METHOD=GET').

Edit: and your semicolon's inside the bracket in the onclick.

oh no computer
May 27, 2003

triplekungfu posted:

I'm not entirely clear on what you're trying to do, is that part of a JSP?
Looks like it's a javascript question and he's in the wrong thread (apologies if I'm wrong!) it's happened a few times in this thread already. Maybe zootm could add a quick "Java != Javascript" and a link to the web development thread to the OP?

zootm
Aug 8, 2006

We used to be better friends.

BELL END posted:

Looks like it's a javascript question and he's in the wrong thread (apologies if I'm wrong!) it's happened a few times in this thread already. Maybe zootm could add a quick "Java != Javascript" and a link to the web development thread to the OP?
Done. :)

I'm interested to know what language the stuff within the <%= %>-delimited block is; I know Rails uses that but I don't think & concatenates strings in Ruby. The only think I could think of which would be used for web programming is VB?

epswing
Nov 4, 2003

Soiled Meat

zootm posted:

I'm interested to know what language the stuff within the <%= %>-delimited block is

In JSP, <% out.println("this"); %> is the same as <%= "this" %>, like PHP short-tags.

e: Whoops, I didn't see those ampersands. What the hell is that, then?

epswing fucked around with this message at 19:12 on May 21, 2008

poopiehead
Oct 6, 2004

My guess would be ASP/VBScript :(

...could be ASP.NET/VB also though but not likely since there's a raw form tag...

poopiehead fucked around with this message at 00:54 on May 22, 2008

joojoo2915
Jun 3, 2006
ASP/VBScript it is! Thank you guys for the help and very sorry for posting in the wrong thread.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
A question to which there may be no good answer: in short, are there any good tools for translating C++ to Java?

In long: I have a large project in C++ that it's time to bring into the 21st century. Nothing clever about it, no tricky constructs, no magical pre-processor trick, just a big commandline app. I'm under no illusions that anything will be able to magically convert my code into a fully working program, but it would be good to have something to grind out boilerplate for the bulk of it, that I can use as a start and a structure to build around.

Things I've looked at:

* C2J: this gets mentioned a lot, but it's a bit flaky and works a file at a time.
* Mocha and Cappucino: two academic projects that seem to be no longer available.
* Jazillion: a commercial project with a good reputation and a "contact us for a quote!" price.

Any further ideas?

Led
Jan 30, 2004
Sjoebiedoewap
First of all, what's the reason to move it from C++ to Java ?
Second of all, I'd never trust a program to just "convert" it from one language to another.
I'd say - port it yourself but only if you really, really have a good reason why Java would be better than C++.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

Led posted:

First of all, what's the reason to move it from C++ to Java ?
Second of all, I'd never trust a program to just "convert" it from one language to another.
I'd say - port it yourself but only if you really, really have a good reason why Java would be better than C++.

I don't expect it to "just convert" - but to give me a body of code to start working on. If I'm porting the program, any sort of a legup would be a help.

My many reasons for the jump:

1) This is the first stage in converting it to an app with a fully blown GUI. Sure, I could use go for one of the GUI libraries for C++ but see the next point.

2) I've ended up supplying it on multiple platforms, which has turned into a bit of a nightmare. My users largely can't use make files, so it really has to be pre-compiled. This has turned into a lot of maintenance effort, especially in the case of Windows which I don't use often at all. (Fix a bug, build it on the Mac. Copy code to Linux box and build it there. Copy app back to Mac. Copy code to Windows box and build it there. Copy app back to Mac. Upload all three files. Get a new bug report ...) It'd be nice to do one build for all.

3) I want to use some particular Java libraries for visualisation and output.

4) Having projects scattered across several languages (C, C++, Python, RealBasic, Java, Obj-C and more), I've decided to let some of the languages go fallow and shift what I can to Java and Python. The mental shift and keeping up with all of them has proved to be too much of a strain. And having to solve the same problem in multiple languages is a waste of time. ("Hey, I could do this with that library I wrote in Python. Pity this program's in Realbasic ...")

nonathlon fucked around with this message at 16:52 on May 22, 2008

epswing
Nov 4, 2003

Soiled Meat
As long as you don't think that a Java app will magically be cross platform. You'll have to be diligent when working with line endings, file io, stdin/stdout, OS paths, etc. The facilities are there for you to work with, you just have to remember to use them.

Phillyt
Dec 2, 2006

by Tiny Fistpump
I'm doing a homework assignment that requires file input and output. I kind of want to know if I've got the right idea with what I should program. I have a text file which is organized as follows: 'name student_id login_id email_address'. An example would be: Doe, John H. 123-45-6789 doe6789 jdoe@foo.net . I need to output a file which will have all the entries of my text file displayed like this '"name", <email address enclosed in angle brackets>'. The previous example would be: "Doe, John H.", <jdoe@foo.net>.

Anyways, the thing that makes this challenging (I think) is the teacher specifies: You can see that the name field is problematic with 2, 3 or more names and initials listed. You should not assume anything about the field delimiters - specifically do not assume tab characters. After typing this through, I really have no idea how to parse this. I had originally had an idea to check for numbers but that doesn't work with the login ID. If we can't assume tab characters, how exactly can I parse this file? I don't want code written but I am curious what someone would do.

Incoherence
May 22, 2004

POYO AND TEAR

Phillyt posted:

If we can't assume tab characters, how exactly can I parse this file? I don't want code written but I am curious what someone would do.
If you are guaranteed nothing at all about the format, then you can't possibly parse it, because someone could have the name "123 45" and then you're pretty well hosed. Obviously you are guaranteed SOMETHING about the format, even if it's not what you would like, unless this is a trick question in which case you should have already asked the teacher for clarification. For example, "each field is separated by some sort of whitespace, not necessarily a tab" is sufficient. To make your problem somewhat easier, as I understand it you don't actually care about the format of the student ID or the login ID, only that you can distinguish the student ID from the name and the login ID from the email.

Basically, you want to tokenize "words" such that each word belongs to exactly one field, even if each field is not contained in a single word. So, in your example:
code:
Doe,
John
H.
123-45-6789
doe6789
jdoe@foo.net

Phillyt
Dec 2, 2006

by Tiny Fistpump

Incoherence posted:

If you are guaranteed nothing at all about the format, then you can't possibly parse it, because someone could have the name "123 45" and then you're pretty well hosed. Obviously you are guaranteed SOMETHING about the format, even if it's not what you would like, unless this is a trick question in which case you should have already asked the teacher for clarification. For example, "each field is separated by some sort of whitespace, not necessarily a tab" is sufficient. To make your problem somewhat easier, as I understand it you don't actually care about the format of the student ID or the login ID, only that you can distinguish the student ID from the name and the login ID from the email.

Basically, you want to tokenize "words" such that each word belongs to exactly one field, even if each field is not contained in a single word. So, in your example:
code:
Doe,
John
H.
123-45-6789
doe6789
[email]jdoe@foo.net[/email]

How would you distinguish between the three words at the top to make it the name? I am probably going to just write the program assuming /t as the token and just get partial credit. Seems a lot easier.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Well if you assume that a person can't have a number in his name and that the student ID is made up of all numbers then you can reasonably separate the fields. The hardest part would be separating the ID from the email since an email can start with a number, so there would have to be some whitespace between the id and the email.

Janitor Prime fucked around with this message at 05:09 on May 23, 2008

such a nice boy
Mar 22, 2002

Since you know the format of the student ID, you can use that as a reference point. Look for 3 numbers, a dash, two numbers, a dash, four numbers (use a regex!). Everything before that is the name. After that, you'll have two fields separated by whitespace, so that's easy to parse.

Phillyt
Dec 2, 2006

by Tiny Fistpump

such a nice boy posted:

Since you know the format of the student ID, you can use that as a reference point. Look for 3 numbers, a dash, two numbers, a dash, four numbers (use a regex!). Everything before that is the name. After that, you'll have two fields separated by whitespace, so that's easy to parse.

What's a regex?

Phillyt
Dec 2, 2006

by Tiny Fistpump
I can't really figure out where to put the tokens. I have a .txt file named hello which is basically made up of entries like above but I am really bad at using tokens to scan it. Right now all I'm trying to do is check for \t delimiters. Here's my code:
code:
public class Main 
{
    public static void main(String[] args) throws IOException 
    {
        BufferedReader inputStream = null;
        PrintWriter outputStream = null;
        try 
        {
            inputStream = new BufferedReader(new FileReader("hello.txt"));
            outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
            String l;
            while ((l = inputStream.readLine()) != null) 
            {
                outputStream.println(l);
            }
        } 
        finally 
        {
            if (inputStream != null) 
            {
                inputStream.close();
            }
            if (outputStream != null) 
            {
                outputStream.close();
            }
        }
    }

such a nice boy
Mar 22, 2002

Phillyt posted:

What's a regex?

A "regular expression". It's a way of matching text. I googled a bit and this looked like a good page for beginners:

http://gnosis.cx/publish/programming/regular_expressions.html

and here's the Java Regex lesson:

http://java.sun.com/docs/books/tutorial/essential/regex/

Regexes are incredibly useful when trying to parse text. Every decent programming language has support for them. You need to know how to use them.

such a nice boy
Mar 22, 2002

Phillyt posted:

I can't really figure out where to put the tokens. I have a .txt file named hello which is basically made up of entries like above but I am really bad at using tokens to scan it. Right now all I'm trying to do is check for \t delimiters. Here's my code:
code:
...
            while ((l = inputStream.readLine()) != null) 
            {
                outputStream.println(l);
            }
...

OK, so this is the core of your program. All it's doing right now is reading a line from inputStream and writing it to outputStream. What do you want it to do?

Well, you want to write the output in a standardized way. You want to be able to use something like this:

code:
outputStream.println("\"" + name + "\", <" + emailaddress + ">");
There's probably a better way to do that using some string formatting stuff but I haven't worked in Java in a while. Anyway, that line presupposes that the variables "name" and "emailaddress" have the right information in them. Let's write the code to make that true...

code:
// we're going to use a regex to find the student ID:
Pattern idpattern = Pattern.compile("\d{3}-\d{2}-\d{4}");
// then we split the original string at the student ID:
String[] items = idpattern.split(l);
String beforeID = items[0];
String afterID = items[1];
// and then you write some code here that figures out the name and address because I can't do homework for you...
String name = ????
String emailaddress = ????
Hope that helps. Use that Java Regex guide to figure out what I did with "Pattern" up there. I can't guarantee that this code compiles or works because I haven't tried it but the idea is right.

Phillyt
Dec 2, 2006

by Tiny Fistpump
Edit: Solved it. Needed two \\. Not one.

Adbot
ADBOT LOVES YOU

Phillyt
Dec 2, 2006

by Tiny Fistpump
And I loving spoke too soon! By the way such a nice boy, PM me and I'll buy you some forum goody or whatever!

Phillyt fucked around with this message at 06:47 on May 23, 2008

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