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
rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I would probably do:

code:
class CostTracker<T extends Enum> {
  public static <T> CostTracker<T> create(Class<T extends Enum> cls) {
    int count;
    try {
      count = ((Object[]) cls.getMethod("values").invoke(null)).length;
    } catch (Exception e) {
      throw new IllegalArgumentException("not an enum class: " + cls.getName(), e);
    }
    return new CostTracker<T>(new float[count]);
  }

  private CostTracker(float[] costArray) {
    costs_ = costArray;
  }

  public void set(T costKind, float cost) {
    costs_[costKind.ordinal()] = cost;
  }

  public float sum() {
    float total = 0;
    for (float e : costs_) total += e;
    return total;
  }

  private final float[] costs_;
}
It's ugly but not unreasonable if you really want the generality.

EDIT: Oh, you're using EnumMap already. Well, saving the object allocations is nice but probably not that important. You should definitely be taking float as a parameter, though; taking Number is not a good idea if you're not guaranteeing to preserve the argument's precision.

Anyway, your class design is fine at the micro level; it's basically impossible to judge whether it's worthwhile at a macro level without knowing more about what you're doing.

EDIT2: Although with little loss of generality, any architecture that involves classes to track a finite set of costs in a generalized way is probably over-engineered.

rjmccall fucked around with this message at 22:34 on Aug 5, 2009

Adbot
ADBOT LOVES YOU

1337JiveTurkey
Feb 17, 2005

It's possible to make those <T extends Enum> into <T extends Enum & CostTypeInterface>. (Syntax might be off) The interface can have whatever methods you want for the user to implement, allowing for some specialized behavior.

Gabbo
Jul 5, 2008
Hey, just a quick question here-

I'm in my first quarter of java programming at the U right now, and I'm having a strange problem getting java to read text files. The problem is simple, but weird as hell- the TA for the class thinks it might be an issue with the actual java runtime itself.

My code looks like this:

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

public class ClassWork7 {
	public static void main(String[] args) throws FileNotFoundException {
		File f = new File("tas.txt");
		Scanner stuff = new Scanner(f);
	}
}
Simple enough. It loads in "tas.txt" and reads it with a Scanner object. The text file is in the same directory as ClassWork7.java (I'm absolutely sure of this).

This compiles fine, but when I run it, I get this error:

code:
Exception in thread "main" java.io.FileNotFoundException: tas.txt (The system cannot find the file specified)
	at java.io.FileInputStream.open(Native Method)
	at java.io.FileInputStream.<init>(FileInputStream.java:106)
	at java.util.Scanner.<init>(Scanner.java:636)
	at ClassWork7.main(ClassWork7.java:7)
I have no idea how to interpret this error or deal with it. Nothing I've tried has managed to resolve this issue... I'm thinking about just completely reinstalling java and seeing if that changes anything. I'm using the jGrasp 1.8.6_15 IDE if it matters.

Thanks for your help.

Gabbo fucked around with this message at 04:29 on Aug 7, 2009

baquerd
Jul 2, 2007

by FactsAreUseless

quote:

The text file is in the same directory as ClassWork7.java (I'm absolutely sure of this).

But is it in the same directory as ClassWork7.class?

Gabbo
Jul 5, 2008

quadreb posted:

But is it in the same directory as ClassWork7.class?

Yep, just checked it. Good question though

Outlaw Programmer
Jan 1, 2008
Will Code For Food
For a problem like this, the first thing you might want to do is specify an absolute path instead of a relative one (i.e. use C:/Users/You/tas.txt). This way you can rule out the possibility that maybe your IDE is running the application in some way that would cause the relative paths to be messed up.

baquerd
Jul 2, 2007

by FactsAreUseless

Outlaw Programmer posted:

For a problem like this, the first thing you might want to do is specify an absolute path instead of a relative one (i.e. use C:/Users/You/tas.txt). This way you can rule out the possibility that maybe your IDE is running the application in some way that would cause the relative paths to be messed up.

Use this to get the current relative path:
code:
System.getProperty("user.dir")

Gabbo
Jul 5, 2008

Outlaw Programmer posted:

For a problem like this, the first thing you might want to do is specify an absolute path instead of a relative one (i.e. use C:/Users/You/tas.txt). This way you can rule out the possibility that maybe your IDE is running the application in some way that would cause the relative paths to be messed up.

Another good idea- I tried it, and it's still no go. Back slashes and double forward slashes work for filepaths in java, right?

Either way, I got it to compile fine and I still get the runtime error.

Mill Town
Apr 17, 2006

What happens if you run it from the command line?

I'm about to suggest that you strace java and find out what file it's trying to open, but that's a horrible idea.

czg
Dec 17, 2005
hi
Try just printing out f.getAbsolutePath() to see where it's expecting to find the file.

1337JiveTurkey
Feb 17, 2005

Relative paths are determined from the working directory where the java command itself is run. For IDEs this usually isn't inside of the source path. NetBeans and IntelliJ both use the project root directory, so try there. If you've got the file in the same directory as the .class file and you only need to read from it, it can be reached using ClassWork7.class.getResourceAsStream("tas.txt").

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Are there any good guides/articles/tutorials about how the JVM is using RAM? I'm trying to compare the memory usage characteristics of a program written in Java with one written in Tcl, and I'm calling "ps h -p [PID] -o vsz" from within each at certain intervals to try to observe how much RAM each is using. Tcl grows more or less linearly with the number of "states" that I'm trying to keep track of, but Java just sits at/around 685 Mb the whole time, regardless of how much information I think I'm tracking.

(Please be kind, as this post probably reveals how little I know about Java, Linux, and Physical/Virtual Memory, all in one go.)

Gabbo
Jul 5, 2008

czg posted:

Try just printing out f.getAbsolutePath() to see where it's expecting to find the file.

Doing that gave me:

code:
C:\Users\Scott\Documents\Classwork 2009\CSE 142\Programs\Test programs\tas.txt
So I changed my code to:
code:
import java.io.*;
import java.util.*;

public class ClassWork7 {
	public static void main(String[] args) throws FileNotFoundException {
		File f = new File("C:\\Users\\Scott\\Documents\\Classwork 2009\\CSE 142\\Programs\\Test programs\\tas.txt");
		Scanner stuff = new Scanner(f);
	}
}
And got the exact same exception. There may be something obvious here I'm missing... I'm a n00b at this, so I might be making basic mistakes.

1337JiveTurkey posted:

Relative paths are determined from the working directory where the java command itself is run. For IDEs this usually isn't inside of the source path. NetBeans and IntelliJ both use the project root directory, so try there. If you've got the file in the same directory as the .class file and you only need to read from it, it can be reached using ClassWork7.class.getResourceAsStream("tas.txt").

Now this is interesting. I gave this a try, with my code looking like:

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

public class ClassWork7 {
	public static void main(String[] args) throws FileNotFoundException {
		File f = new File(ClassWork7.class.getResourceAsStream("tas.txt"));
		Scanner stuff = new Scanner(f);
	}
}
And I got a compiler error, saying:

code:
ClassWork7.java:6: cannot find symbol
symbol  : constructor File(java.io.InputStream)
location: class java.io.File
		File f = new File(ClassWork7.class.getResourceAsStream("tas.txt"));
		         ^
1 error
I tried getting rid of the File object and replaced "f" in the scanner with the line you just gave me, and got runtime error:

code:
Exception in thread "main" java.lang.NullPointerException
	at java.io.Reader.<init>(Reader.java:61)
	at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
	at java.util.Scanner.<init>(Scanner.java:590)
	at ClassWork7.main(ClassWork7.java:6)
I hope this is useful information. Haha, once again, I don't know a whole lot about what I'm doing here, so sorry if my noobish mistakes have muddled things up here. Thanks again for the help.

HFX
Nov 29, 2004

rjmccall posted:

3. There's a bug in the garbage collector. This is almost certainly not the problem — not that there aren't bugs in the collector, just that you are very unlikely to be running into one.

Strangely enough I had run into this one before with a project that ran 24 hours a day several weeks a time. It would crash randomly after running for 2-3 weeks and quit with out warning. Only once did I capture a message that it had run out of memory (but no stack trace or output beyond that). With no where to go, I made a decision to try out Java 6 instead of Java 5 (all other sites were doing fine with Java 6 and the same jar). Have never had the problem again.

hlfrk414
Dec 31, 2008
Gabbo, are you sure your file isn't tas.txt.txt ? That always seemed to be the problem for my groups when mysterious file issues started. Annoying as hell that the lab computers did not show file extensions.

czg
Dec 17, 2005
hi

Gabbo posted:

Doing that gave me:

code:
C:\Users\Scott\Documents\Classwork 2009\CSE 142\Programs\Test programs\tas.txt
So I changed my code to:
code:
import java.io.*;
import java.util.*;

public class ClassWork7 {
	public static void main(String[] args) throws FileNotFoundException {
		File f = new File("C:\\Users\\Scott\\Documents\\Classwork 2009
			\\CSE 142\\Programs\\Test programs\\tas.txt");
		Scanner stuff = new Scanner(f);
	}
}
And got the exact same exception. There may be something obvious here I'm missing... I'm a n00b at this, so I might be making basic mistakes.
Yeah, but did you verify that tas.txt actually does exist in that folder?

Also the Class.getResourceAsStream(...) method returns a InputStream, not a File, but Scanner has a constructor accepting a stream directly, so that's no problem:
code:
Scanner stuff = new Scanner(ClassWork7.class.getResourceAsStream("tas.txt"));

Gabbo
Jul 5, 2008

hlfrk414 posted:

Gabbo, are you sure your file isn't tas.txt.txt ? That always seemed to be the problem for my groups when mysterious file issues started. Annoying as hell that the lab computers did not show file extensions.

Hey! This was the problem!

That is unbelievably frustrating; I don't know if this is a feature of vista or what, but when I type in "C:\Users\Scott\Documents\Classwork 2009\CSE 142\Programs\Test programs\tas.txt" into an explorer window, it opens the file. But, when I delete the ".txt" at the end of the file and put the filepath in again, it still opens. After deleting the ".txt" at the end of it, the program compiles and runs successfully.

Hooray for not displaying the full filename in windows explorer. Really, that's cool. Makes my life a lot easier.

Gabbo fucked around with this message at 21:45 on Aug 7, 2009

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Gabbo posted:

Hey! This did the trick!

That is unbelievably frustrating; I don't know if this is a feature of vista or what, but when I type in "C:\Users\Scott\Documents\Classwork 2009\CSE 142\Programs\Test programs\tas.txt" into an explorer window, it opens the file. But, when I delete the ".txt" at the end of the file and put the filepath in again, it still opens. After deleting the ".txt" at the end of it, the program compiles and runs successfully.

Hooray for not displaying the full filename in windows explorer. Really, that's cool. Makes my life a lot easier.

Tools->Folder Options->View->Uncheck "Hide extensions for known file types". (You might also want to "Show hidden files and folders," but that one's up to you.) This is always the first thing I do when I'm working in a new account on Windows - I've had way too many problems due to not knowing what my extension actually is.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Shameful double post. :(

sonic bed head
Dec 18, 2003

this is naturual, baby!
I have a webapp using Spring, and Jawr and a few config files. I would like to have one location where I set Debug or Production modes and have it reflected throughout the application without having to manually change DB values or debug values in all of the configuration files. The problem that I'm finding is that all of these are set in XML files rather than programatically. How would you recommend that I conditionally select different values? If it was all done in Java, this would be easy, but I don't know how to do it in XML. I don't think that I can use XSLT because I don't think that they can be processed at deploy time.

tyane
Nov 16, 2008

Always Outnumbered,
Never Outgunned
hi
I am trying to optimize the way we get our images from the webserver for our applet. I have created a resource jar so instead of getting 4mb from the servlet each time i just have to get 60k. Also, I got it to once the images are cached, get them from the client. The problem is getting the original cache. It seems like the client hits the servlet for the resource jar for each image but from then on uses the local jar. Is there anyway i can just download the jar once and use the local from then on? Hopefully i did a good job of explaining this and thanks in advance for any help.

e: note: ive tried the applet tags archive,cache_archive,and cache_archive_ex

Outlaw Programmer
Jan 1, 2008
Will Code For Food

tyane posted:

hi
I am trying to optimize the way we get our images from the webserver for our applet. I have created a resource jar so instead of getting 4mb from the servlet each time i just have to get 60k. Also, I got it to once the images are cached, get them from the client. The problem is getting the original cache. It seems like the client hits the servlet for the resource jar for each image but from then on uses the local jar. Is there anyway i can just download the jar once and use the local from then on? Hopefully i did a good job of explaining this and thanks in advance for any help.

e: note: ive tried the applet tags archive,cache_archive,and cache_archive_ex

Can't you just bundle the images in the same JAR file as the code? Typically our JARs looks like:

code:
com/company/code/ (.class files here)
resources/ (images, property files, etc. here)
Then just do something like Class.getResourceAsStream("resources/myImages.png").

tyane
Nov 16, 2008

Always Outnumbered,
Never Outgunned
hey thanks for the response. Ive been working on this for a couple days now and of course i dont figure it out until i finally post a question. The problem was using conn.setUseCaches(true); instead of conn.setDefaultUseCaches(true); It seems the ladder does what i wanted.

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


Can someone tell me what the performance hit of printing a stack trace is? I've got a piece of code that dumps a stack trace into the logs for roughly ~13 exceptions per minute all day long. Developers want justification that there is a performance issue because apparently 20k exceptions per day isn't a good enough reason to fix the code. I wrote up some bullshit about how the machine is I/O bound so constantly writing to disk is worse performance than whatever in-memory operation usually takes place when the code succeeds. But I'm looking for specific information like printing a thread dump pausing processing while the trace is built, or interfering with garbage collection. Something more concrete than what I've pulled out of my rear end. If there isn't anything I guess I need to go with "Why are we tolerating code that throws so many exceptions? Who designed this crap?"

Volguus
Mar 3, 2009

HatfulOfHollow posted:

Can someone tell me what the performance hit of printing a stack trace is? I've got a piece of code that dumps a stack trace into the logs for roughly ~13 exceptions per minute all day long. Developers want justification that there is a performance issue because apparently 20k exceptions per day isn't a good enough reason to fix the code. I wrote up some bullshit about how the machine is I/O bound so constantly writing to disk is worse performance than whatever in-memory operation usually takes place when the code succeeds. But I'm looking for specific information like printing a thread dump pausing processing while the trace is built, or interfering with garbage collection. Something more concrete than what I've pulled out of my rear end. If there isn't anything I guess I need to go with "Why are we tolerating code that throws so many exceptions? Who designed this crap?"

I am not aware of any "special" operations that may occur when a program requests a stack dump. Those who know more than I do are welcome to bring their arguments to the table.

But...just look at the drat IO. the logs for christ sake. 20k exeptions per day are useless. Nobody will ever look through them all and try to figure out a problem. That's where...the real problems will come up and they will be lost in the mountain of exceptions that are not that important.

Exceptions ...are just that: EXCEPTIONS. Not the rule. If the programmers made that the rule...it's bad.

These reasons alone should be sufficient. If they are not and you need to come up with:" but the earth spins slower when you throw that many exceptions" argument, I think you have bigger problems on your hands than just a mountain of exceptions .

deedee megadoodoo
Sep 28, 2000
Two roads diverged in a wood, and I, I took the one to Flavortown, and that has made all the difference.


rhag posted:

I am not aware of any "special" operations that may occur when a program requests a stack dump. Those who know more than I do are welcome to bring their arguments to the table.

But...just look at the drat IO. the logs for christ sake. 20k exeptions per day are useless. Nobody will ever look through them all and try to figure out a problem. That's where...the real problems will come up and they will be lost in the mountain of exceptions that are not that important.

Exceptions ...are just that: EXCEPTIONS. Not the rule. If the programmers made that the rule...it's bad.

These reasons alone should be sufficient. If they are not and you need to come up with:" but the earth spins slower when you throw that many exceptions" argument, I think you have bigger problems on your hands than just a mountain of exceptions .

The only thing I found is that the thread pauses execution briefly while building the stack trace. 13 times per minute isn't much but it's something. Also, I should have mentioned that this is 20k exceptions from ONE METHOD. The total for all exceptions is much much much higher.

And this is why I started up the hunt for a new job a few weeks ago. Our developers are lazy as gently caress and our QA make more money than me yet I find more bugs than they do (which is bad because I find them in production).

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
The jvm needs to perform extra work when unwinding stack frames. From what I understand, it has to rediscover the call path when an exception is thrown, since it doesn't keep the path around during normal calls.

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost
Also, let's not forget that objects are objects and so require memory, and if you're running a heavily loaded system with this happening often enough, it can cause performance issues. But frankly, throwing exceptions is one of the last places to look for improving application performance, and if there is a problem, it's always been an I/O bottleneck that gets hit due to the exceptions (20k exceptions? Try 4TB of exception stacktrace data thrown / day to a single disk).

If you find little hope in the job you've got, it's in everyone's interest for you to move on. Don't think you're doing anyone a favor by staying. Just go. Even though the economy sucks, people are still hiring - several of my coworkers have left in the past 4 months and are obviously getting jobs, for instance.

huge sesh
Jun 9, 2008

Is there some kind of established best practice/API for storing client-side settings? I need my applet to be informed which directory to look in for some files, but I have no idea where I can be guaranteed read/write access (the applet is signed, btw).

gnaw at your paw
May 23, 2008
This is regarding the Blackberry Java API. (http://www.blackberry.com/developers/docs/4.3.0api/index.html)

I'm using a thread pool to execute a bunch of threads sequentially. The threads are downloading images into byte arrays and then encoding them to be displayed on the screen.

However, when I run the threads, they block all input until they're done (this defeats the purpose of threading), and I can't seem to get the screen to repaint the images when they finish loading - it seems to repaint randomly, after loading 3-4 images.

I'm using UiApplication.invokeLater(thread); to run the threads. This works in that it puts all the text and other elements on the screen without waiting for the images to load, but once it starts the threads, you can't scroll or click anything until it's done.

Can anyone clue me in on what I'm missing to make my program respond to input while processing this in the background?

This is what my run method looks like inside the little worker threads:

code:
public void run() {
	try{
		HttpConnection httpConnection = (HttpConnection) Connector.open(this.url);
		imageStream = httpConnection.openInputStream();
	}
	catch (Exception e){
		System.out.println(e.toString());
	}
	if(imageStream == null) {
		System.out.println("Error: input stream is not initialized.");
	} else if (imageStream != null) {
		System.out.println("OK: input stream is initialized.");
		ByteVector myVector = new ByteVector();
		try {
			int temp;
			do {
				temp = imageStream.read();
				myVector.addElement((byte) temp);
			} while (temp != -1);
		} catch (Exception e) { System.out.println(e.toString()); }
		data = new byte[myVector.size() - 1];
		data = myVector.getArray();
		myVector = null;
		try {
			image = EncodedImage.createEncodedImage(data, 0, data.length);
			imagePlaceholder.setImage(image);
		} catch (IllegalArgumentException iae) {
			System.out.println("Image format not recognized.");
		}
	}
}
Edit: I changed my class to extend thread rather than implement runnable and it worked (?)

gnaw at your paw fucked around with this message at 04:41 on Aug 26, 2009

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
UiApplication.invokeLater queues things to run in the UI thread after the current event has finished processing. You will indeed need to create threads to run your tasks. In what way exactly are you using a thread pool?

Also, this is unrelated, but if you don't see the problem with the following, you need to study the basics again:
code:
data = new byte[myVector.size() - 1];
data = myVector.getArray();

gnaw at your paw
May 23, 2008
Considering my only Java background is one semester my senior year of college, it doesn't surprise me at all that I'd overlook something "basic" like that. However, those particular lines of code were very rushed. I wrote ALL of this today... so, I don't feel too bad. That evolved from me originally sizing the byte array using HTTPConnection.getLength() but that was not working on the curve 8900 (returning -1), so I ended up creating a vector to store the bytes, and then I only realized later that there is a ByteVector class.

I also just recently realized that invokeLater should only be used for UI elements (after my post).

But what I guess I don't understand is: the difference between extending Thread and implementing Runnable? I thought they were two ways of doing the same thing, except you don't extend thread unless you're adding extra functionality.

--

Also, to answer your question: I'm not directly using a thread pool, I'm using the concept of a thread pool to execute several threads sequentially. I don't really know what a thread pool is, I just thought that was what you called it. I'm loading a bunch of images in a row, and I want to load the first images first, rather than loading the images that the user might not even scroll to before the ones that are at the top of the screen. But here is the code, in case you're curious:
code:
public class ImageThreadManager extends Thread {
	static Vector threads = new Vector();

	public static void Enqueue(ImageLoader r) {
		threads.addElement(r);		
	}

	public void run() {
		for (int i = 0; i < threads.size(); i++)
		{
			ImageLoader myThread = (ImageLoader)threads.elementAt(i);
			myThread.start();
			try {
	            myThread.join();
	        } catch (InterruptedException ignore) {
	        }
		}
	}
}

gnaw at your paw fucked around with this message at 06:51 on Aug 26, 2009

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
An implementation of Runnable is just that — something which represents an arbitrary task to be executed. A Thread is actually, well, a thread, which just happens to implement the Runnable interface; its normal run() implementation is to execute the Runnable object you constructed it with (if you did so) and then return. There's nothing magic that causes things to happen asynchronously except when you call start() on a thread.

Given that you don't see any blocking at all when you switch to a Thread subclass, my guess would be that the Blackberry invokeLater API specifically checks for Thread objects and treats them differently from other Runnables. (The other possibility, that you're calling start() on the thread and not telling me, should still cause blocking). If you really care, try overriding start() to print a backtrace to verify that.

gnaw at your paw posted:

I don't really know what a thread pool is

Basically, a thread pool is any mechanism that maintains a "pool" of threads to do arbitrary tasks, generally for the competing purposes of (1) limiting the total number of threads you create and (2) avoiding the cost of creating a new thread for every task. The full Java 1.5 API has a ThreadPoolExecutor class that gives you the general idea.

There is never a good reason to create a bunch of Thread objects, only to run them sequentially like that; you'd be better off creating a bunch of Runnable objects and calling their run() methods in sequence. Also, you're not really being thread-safe at all.

snoot
Jun 8, 2006

danger lurks everywhere
I have a web service that calls a third party Java API that requires an absolute path to a configuration file for it to function.

How do I include the config file in the web service 'war', then find the absolute path to that file?

I'm using Netbeans as an IDE and GlassFish to run the web service.

I guess this is fairly straight forward? I usually work in C#, and don't know where to look to figure out how to do this kind of thing in Java. Any pointers would be greatly appreciated.

Volguus
Mar 3, 2009

snoot posted:

I have a web service that calls a third party Java API that requires an absolute path to a configuration file for it to function.

How do I include the config file in the web service 'war', then find the absolute path to that file?

I'm using Netbeans as an IDE and GlassFish to run the web service.

I guess this is fairly straight forward? I usually work in C#, and don't know where to look to figure out how to do this kind of thing in Java. Any pointers would be greatly appreciated.

Short answer: you don't.

Long answer:
Depending on your web application server, the war file may or may not be unzipped while being deployed.

The safest way to do this is as follows:
InputStream in=getClass().getResourceAsStream("path to your file");
create a new file in the tmp directory (System.getProperty("java.io.tmpdir")).
Write into that file the contents of the "in" stream.
pass the full path to that file to the library. let it do its thing, delete the file.

"path to your file" is relative to your classpath.
if the file is in WEB-INF/classes then asking for: /myproperties.file should work just fine.
if it's in a package... just prepend the package path to the filename (/com/mycompany/myapp/file.properties)

Hope this helps.


short edit: some libraries (spring for example) know to get a properties file in the classpath, this library my know that as well. For spring I specify the xml file path as: classpath:/application-context.xml where the file is located in the war file in WEB-INF/classes

Volguus fucked around with this message at 22:15 on Aug 27, 2009

snoot
Jun 8, 2006

danger lurks everywhere

rhag posted:

Short answer: you don't.

Thanks for the info, rhag. I thought I might have to go the 'write resource to temp dir' route, but wasn't sure that was the best approach.

The API I'm using is open source (file validation related thing, not all that well written), my best approach might be seeing if I can extend the 'read config' class to take in a stream and avoid the whole mess.

huge sesh
Jun 9, 2008

Crossposted from webdev thread:

OK, I can't figure out how to load a file in Java.

What I want: the Java client sends an HTTP request to the server with the URL pointing toward the file name. Django sends back a 302 redirect to an url which serves static media. Client then opens a stream to the file and downloads it. The point here is to have an url that allows the file to be accessible by name but store it internally by database primary key.

When I ask for the file (by name) in firefox, it gives me the file to download. When I ask for the file by name in telnet, it sends back 302 found and the numeric URL. When I do an HTTP request with telnet for the file (via the numeric url), I get this:
code:
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 29 Aug 2009 02:33:44 GMT
Content-Type: application/x-fceux-state
Connection: keep-alive
Last-Modified: Thu, 27 Aug 2009 21:06:34 GMT
ETag: "1620281-a00-47225f1448a80"
Accept-Ranges: bytes
Content-Length: 2560 <-- correct for the file

<binary data>

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>
Now, when I try to open the file using URL.openStream() in Java it only works if I cheat and give it the numeric URL outright (in which case it only reads the binary data, none of the html). When I give it the url by name, it only gives me the 400 bad request html, which is weird as it indicates that it is following the redirect but then interpreting the data differently (telnet never gave html back when i requested by name).

Max Facetime
Apr 18, 2009

That HTTP response looks a bit confused with that extra error document tacked on at the end. I'd make double sure that there are no subtle differences with the headers of the working and non-working requests. You can use Wireshark to listen in on the request Java is making. That should tell you which request headers you should tweak in Java to make it work.

huge sesh
Jun 9, 2008

Thanks, tkinnun--turns out that not only does the JRE (1.6-13, windows) not even bother to write the header checksum into the IP header, it also completely fucks up escaping the URL. When you call URL.openStream(), it writes to the console
network: Connecting <url> with cookie=etc...
with spaces escaped to %20, but the actual request it makes doesn't escape the spaces.

Adbot
ADBOT LOVES YOU

covener
Jan 10, 2004

You know, for kids!

huge sesh posted:

Thanks, tkinnun--turns out that not only does the JRE (1.6-13, windows) not even bother to write the header checksum into the IP header, it also completely fucks up escaping the URL. When you call URL.openStream(), it writes to the console
network: Connecting <url> with cookie=etc...
with spaces escaped to %20, but the actual request it makes doesn't escape the spaces.

applications like java don't calculate checksums for IP headers, the host network stack does. Wireshark shows you its invalid because your network card offloads it, which isn't until after wireshark sees it on the way out.

The failure to encode a space in a URI sounds surprising for java. Can you illustrate with a short program?

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