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
Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
CBA: if you want to store that number as a Long you can do

code:
long n = 600100200300l;
Note that Javac doesn't give a drat about precision in double literals. I think in your example the number can still be represented precisely with the given precision, but I don't believe you'd get a warning if it was going to truncate.

Adbot
ADBOT LOVES YOU

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Is there any way to make a Java program run itself in the background on Linux?

Like say I have upfile.jar, and running upfile.jar bigfile.avi will upload bigfile.avi to my FTP server. Is there any way for the program -- not any extra terminal commands, but the jar itself -- to detach from the terminal and run as a background process/daemon?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
With the bash shell you can end any command with an '&' to launch something as a background process.

code:
java -jar upfile.jar bigfile.avi &
Does that work?

lupoprovik
Sep 22, 2007

Internet Janitor posted:

With the bash shell you can end any command with an '&' to launch something as a background process.

code:
java -jar upfile.jar bigfile.avi &
Does that work?

Tack a 'nohup' onto the front of that so it wont kill the process when you log out.

Colonel Taint
Mar 14, 2004



^^^^
You may need to do
nohup java -jar upfile.jar bigfile.avi > /dev/null 2> /dev/null < /dev/null &
if it still hangs

Not sure if the terms are completely correct, but does anyone know the scope of the final-ism of a variable?

What I want to do is to make sure an object doesn't re-assign itself after it's created.

code:
//Somewhere
	someFunction(Someclass a)
	{
		a.bar()
	}

SomeClass
{
	...
	bar()
	{
		this = new SomeClass();
		..
	}
}

//Somewhere else
	final SomeClass foo = new SomeClass(..);
	
	someFunction(foo);
}
So even though the a in the someFunction function isn't final, will it retain the finality from foo and fail?

Colonel Taint fucked around with this message at 02:39 on Apr 29, 2010

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
SintaxError: I think you're rather confused. When a reference is 'final' it simply means that reference cannot be altered once it has been assigned, either at declaration or in a constructor. Arguments to a method cannot be 'final', and it wouldn't really mean anything in that context- references would be passed by value anyway. The keyword 'this' evaluates to a reference to the current object- it isn't a variable you can assign to a different reference.

What do you expect would happen if an object "re-assigned itself"? None of that makes any sense.

Colonel Taint
Mar 14, 2004


Ah, my bad. That's what I get for coming from a C++ background, where it's perfectly valid (though perhaps not always the best idea) to change what this points to.

Edit: that's apparently no longer true.

Java references confuse me :downs:

Colonel Taint fucked around with this message at 03:08 on Apr 29, 2010

1337JiveTurkey
Feb 17, 2005

Arguments to a method can be declared final in the implementation although it's not allowed in an abstract method. This simply indicates that the method will not change the values passed in even if pass by value semantics are enforced on all method calls normally. This is required if the values are to be accessible from within a local class defined inside the method. Otherwise it's merely a helpful indicator for the compiler when optimizing code and a way to ensure that the value isn't changed inadvertently.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Internet Janitor posted:

With the bash shell you can end any command with an '&' to launch something as a background process.
code:
java -jar upfile.jar bigfile.avi &
Does that work?
Yep. Now I've got a great ghetto method to make a jar run itself detached :v:
java -jar upfile.jar
code:
try {
	@SuppressWarnings("unused")
	Process proc = Runtime.getRuntime().exec("java -jar upfile.jar actuallyrun &");
} catch (IOException e) {
	e.printStackTrace();
}
If it has no args it does that, if it receives actuallyrun it executes.

edit: ignore the fact that this doesn't take a file as an argument, it's from the testing code just for the detaching part

Malloc Voidstar fucked around with this message at 07:02 on Apr 29, 2010

Max Facetime
Apr 18, 2009

Is there a way to escape Expression Language results in a JSP file by default?

I have ${item.value} in my JSP file, which generates the following code with Tomcat 6.0:

code:
out.write((java.lang.String) 
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate
("${item.value}", java.lang.String.class, 
(PageContext)_jspx_page_context, null, false));
I would like that to be something like:
code:
out.write(somepackage.SomeClass.escape((java.lang.String) 
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate
("${item.value}", java.lang.String.class, 
(PageContext)_jspx_page_context, null, false)));

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
You mean HTML/XML escaped, right?
code:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- Elsewhere... -->
<c:out value="${item.value}"/>
Who knows why the security wizards at Sun didn't make this the behavior of the more concise syntax.

Max Facetime
Apr 18, 2009

Yes. I could use c:out or roll my own, but I'd rather use

${item.value} for escaped text and

<c:out value="${item.value}" escapeXml="false"/> for unescaped text.

I've looked at replacing the Jasper compiler in Tomcat with a modified version, but I'd like to find an easier way.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
There isn't.

private message
Aug 22, 2004
[img]https://forumimages.somethingawful.com/images/newbie.gif[/img]
Hey I was wondering if anyone has the java source code for DFS (depth-first search) maze generation. Here is the algorithm written as psuedocode. I need to generate a maze within JFrame composed of cells.

create a CellStack (LIFO) to hold a list of cell locations
set TotalCells = number of cells in grid
choose a cell at random and call it CurrentCell
set VisitedCells = 1

while VisitedCells < TotalCells

find all neighbors of CurrentCell with all walls intact
if one or more found
choose one at random
knock down the wall between it and CurrentCell
push CurrentCell location on the CellStack
make the new cell CurrentCell
add 1 to VisitedCells else
pop the most recent cell entry off the CellStack
make it CurrentCell endIf

endWhile

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Private Message: Are you having difficulty with the Swing stuff, or maze generation itself?

For the UI, it should be as simple as extending a JFrame, calling getContentPane() to get the base component and calling getGraphics() on that to get an AWT Graphics context you can use to draw whatever you want.

Alternately, you could set the content pane's layout manager to a GridLayout of appropriate dimensions, to which you could add JPanels (or JButtons, or whatever) representing each tile in the maze.

As for implementing the algorithm, uh... you have pseudocode- why don't you take a crack at implementing it and get back to us if you run into any specific trouble? I don't mind giving advice, but I'm not going to do your homework for you.

Mill Town
Apr 17, 2006

private message posted:

Hey I was wondering if anyone has the java source code for DFS (depth-first search) maze generation.

Yeah wait a minute, you want us to just give you the source code, aka, the answer for your homework? Doesn't work like that, bub.

8ender
Sep 24, 2003

clown is watching you sleep
When I used to work in PL/SQL it had the ability for me to compared a string to a comma separated list of other strings like this:

code:

if x in ('One','Two','Three') then

-- Do stuff

end if;

In Java I'm doing something like this:

code:

if (x.equals('One')||x.equals('Two')||x.equals('Three')) {

// Do stuff

}

I'm missing the elegance of the PL/SQL method and the syntax gets really heavy when I'm comparing a lot of things. Is there some easy one liner method that I'm missing?

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
Sure, if you don't mind possible performance implications for some definition of "a lot of things":
code:
if(Arrays.asList("one","two","three").contains(x))

epswing
Nov 4, 2003

Soiled Meat
Teehee

code:
if (new ArrayList<String>() {{ add("one"); add("two"); add("three"); }}.contains(x))
Edited following Lysidas' excellent advice :)

code:
if (new HashSet<String>() {{ add("one"); add("two"); add("three"); }}.contains(x))

epswing fucked around with this message at 21:58 on May 4, 2010

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
As the number of things increases, you might consider using some kind of Set like a HashSet or a TreeSet. These data structures are perfect for membership testing.

Partyworm
Jul 8, 2004

Tired of partying
Does anyone have any experience with Java certification exams? Are they worth going for or just a waste of time next to practical ability?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

epswing posted:

code:
if (new HashSet<String>() {{ add("one"); add("two"); add("three"); }}.contains(x))

This is completely pointless. The only reason to do hashtable lookup instead of a linear scan is that it's O(1), but building the hashtable in the first place is O(N), and it's a fairly heavy O(N) at that. At the very least you should build the hashtable in a static field.

It is also quite possibly faster to call String.equals three times than it is to do a hash lookup.

epswing
Nov 4, 2003

Soiled Meat
If you didn't notice the "Teehee," this was a comedy 'contains' option.




vvv Edit: No problemo, and actually, thanks for the asymptotic analyzing, it's worse than I thought.

epswing fucked around with this message at 22:02 on May 4, 2010

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

epswing posted:

If you didn't notice the "Teehee," this was a comedy 'contains' option.

Ah, no, I didn't, nevermind.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

Partyworm posted:

Does anyone have any experience with Java certification exams? Are they worth going for or just a waste of time next to practical ability?

Never did them, probably a waste of money and time unless work is paying for it (and time to study for it)

epswing
Nov 4, 2003

Soiled Meat
If you've never done them, why do you think your opinion that they're a waste of money is worth anything?

I'm not intentionally trying to be a dick, but saying something is a waste of money with zero backup isn't helpful to anyone.

lamentable dustman
Apr 13, 2007

🏆🏆🏆

epswing posted:

If you've never done them, why do you think your opinion that they're a waste of money is worth anything?

I'm not intentionally trying to be a dick, but saying something is a waste of money with zero backup isn't helpful to anyone.

Everyone that I know who has taken them says they are a waste, there was a thread on reddit yesterday were everyone said they were a waste also


i guess they might be padding if you don't have a degree or something



e: also just accepted a new job, during my hunt never saw anything that said "NEED JAVA CERTIFICATION", they all said you need a degree and some experience.

lamentable dustman fucked around with this message at 16:27 on May 5, 2010

Fly
Nov 3, 2002

moral compass

Partyworm posted:

Does anyone have any experience with Java certification exams? Are they worth going for or just a waste of time next to practical ability?
I have interviewed many dozens of candidates and to this day I have not noticed any direct correlation between a candidate's aptitude and having Sun Java certification, but it slightly raises my expectations around what I think the candidate should be able to answer when I see that on a resum.

Many candidates with certifications seem to come from consulting or contracting backgrounds where the agency probably likes to be able to claim all of their contractors are certified.

zootm
Aug 8, 2006

We used to be better friends.

Fly posted:

Many candidates with certifications seem to come from consulting or contracting backgrounds where the agency probably likes to be able to claim all of their contractors are certified.
This is essentially it, yeah. I used to work for a bespoke company who wanted us to do the Java and .NET exams so that they could be listed on applications for work to clients. I'm not sure they're beneficial to the individual -- they tend to be heavy on API knowledge, which isn't necessarily all that useful, and I've found self-directed learning to be more effective. In short they're primarily a means of selling oneself to a client, not of self-improvement.

epswing
Nov 4, 2003

Soiled Meat
I have a textfile in my src folder, like jdbc.properties or whitelist.xml, and when I compile it ends up in my bin folder (or more specifically, my war/WEB-INF/classes folder since I'm in tomcat-land). How can I access whitelist.xml?

I thought I'd done this before in a previous life (job), but now I think that was packaging images for JButton icons into a jar, which isn't the same thing. I think I used some System.something call for that, but I can't find it now, and I'm not sure what to search for.

I can't reliably snatch whitelist.xml out of the filesystem, because when I start the tomcat server with tomcat/bin/startup.sh the current working directory is wherever I execute that command, obviously, so I can't get to it relatively, and trying to get to it absolutely is just dumb.

Edit: speling

vvv Edit 2: Gracias!

epswing fucked around with this message at 20:23 on May 5, 2010

lamentable dustman
Apr 13, 2007

🏆🏆🏆

epswing posted:

I have a textfile in my src folder, like jdbc.properties or whitelist.xml, and when I compile it ends up in my bin folder (or more specifically, my war/WEB-INF/classes folder since I'm in tomcat-land). How can I access whitelist.xml?

I thought I'd done this before in a previous life (job), but now I think that was packaging images for JButton icons into a jar, which isn't the same thing. I think I used some System.something call for that, but I can't find it now, and I'm not sure what to search for.

I can't reliably snatch whitelist.xml out of the filesystem, because when I start the tomcat server with tomcat/bin/startup.sh the current working directory is wherever I execute that command, obviously, so I can't get to it relatively, and trying to get to it absolutely is just dumb.

Edit: speling


getClass().getClassLoader().getResourceAsStream("whitelist.xml") should get the file as a stream from the classpath root

UraniumAnchor
May 21, 2006

Not a walrus.
code:
synchronized(a) {
 synchronized(b) {
  b.wait();
 }
}
Does the wait call release both locks or just the lock on b?

yatagan
Aug 31, 2009

by Ozma

UraniumAnchor posted:

code:
synchronized(a) {
 synchronized(b) {
  b.wait();
 }
}
Does the wait call release both locks or just the lock on b?

Just b.

Edit: because I like to second guess myself sometimes here's proof of concept (OK not strictly a proof) code:

code:
public class Test2 implements Runnable {
	static Object a = new Object();
	static Object b = new Object();
	String ID;

	public Test2(String ID) {
		this.ID = ID;
	}

	public void run() {
		synchronized(a) {
			 System.out.println(ID + "Got a's lock");
			 synchronized(b) {
				 System.out.println(ID + "Got b's lock");
				 try { b.wait();} catch (InterruptedException e) { }
			 }
			 System.out.println(ID + "b's lock released");
		}
		System.out.println(ID + "a's lock released");
	}


	public static void main(String[] args) {
		Thread t1 = new Thread(new Test2("T1"));
		Thread t2 = new Thread(new Test2("T2"));
		t1.start();
		t2.start();
		try { Thread.sleep(5000); } catch (InterruptedException e) { }
		synchronized(b) {
			b.notify();
		}

	}
}

yatagan fucked around with this message at 06:30 on May 6, 2010

Fly
Nov 3, 2002

moral compass

yatagan posted:

Just b.
The documentation also agrees:
http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait()

quote:

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

wigga please
Nov 1, 2006

by mons all madden
I'm a .NET guy, pretty new to Java, and iI have a Struts/EJB question. I'm trying to teach myself some stuff but I'm pretty disappointed in the tutorials I found so far.

I have two separate problems:the first, is just getting data from a simple query to display. I have a GetMessagesAction that exposes a "messages" property. I've tried to make this a ResultSet (although if resultset is anything like and ADO.NET DataSet I probably shouldn't use that), a HashMap, and just concatenating everything into a string (which is probably the worst but at least it displays anything).
How should I configure my JSP page to display this? <bean:write .../> cuts it for strings, but not for Collections or ResultSets (blank).
I tried <logic:iterate.../> but that just gets me a 500 error "No collection found". So I'm actually looking to find something comparable to the ASP.NET GridView or ListView controls.

Next, is a system that allows a user to submit a message once he has identified himself. The problem here is that I can get the username from a bean, but I wouldn't know how to pass it to the messaging bean. Load it into session? Get it from one of the form properties in the MessagesAction model?

geeves
Sep 16, 2004

wigga please posted:

I'm a .NET guy, pretty new to Java, and iI have a Struts/EJB question. I'm trying to teach myself some stuff but I'm pretty disappointed in the tutorials I found so far.

I have two separate problems:the first, is just getting data from a simple query to display. I have a GetMessagesAction that exposes a "messages" property. I've tried to make this a ResultSet (although if resultset is anything like and ADO.NET DataSet I probably shouldn't use that), a HashMap, and just concatenating everything into a string (which is probably the worst but at least it displays anything).
How should I configure my JSP page to display this? <bean:write .../> cuts it for strings, but not for Collections or ResultSets (blank).
I tried <logic:iterate.../> but that just gets me a 500 error "No collection found". So I'm actually looking to find something comparable to the ASP.NET GridView or ListView controls.

Next, is a system that allows a user to submit a message once he has identified himself. The problem here is that I can get the username from a bean, but I wouldn't know how to pass it to the messaging bean. Load it into session? Get it from one of the form properties in the MessagesAction model?


Any collection should do.. have you tried using <logic:present> to see if it's been loaded / available? Are you able to access the Collection with JSP instead of struts tags? Also, just a quick check - you are including the logic taglib, right? That last one has lead me to many headaches over time.

http://struts.apache.org/1.2.9/userGuide/struts-logic.html#iterate


As for the second, yes, at my old job we loaded everything into the session scope on success of the Action.

Colonel Taint
Mar 14, 2004


Alright, so I have a small server app that I'm writing, which works fairly well under a small load. However, after about a minute of light stress testing (new connection every 100ms or so, disconnect after ~45 seconds), this happens:




Although it still runs fine with the 200 threads (they're mostly in a wait state after running small, async jobs via a cachedThreadPool ExecutorService), I'd really rather have it remain at a somewhat steady thread count. I'm at somewhat of a loss as to how to deal with this. NetBeans's profiler isn't much help. tptp in Eclipse is a bit more useful, but isn't exactly shedding any light on the problem either, and in either case there's way too much going on after the fact for a debugger to be useful...

I've pretty much been trying to deal with this all day, so any help/advice would be useful.

Colonel Taint fucked around with this message at 17:11 on May 9, 2010

HondaCivet
Oct 16, 2005

And then it falls
And then I fall
And then I know


I have a quick/possibly dumb question about . . . well, for each loops I think, I'm not exactly sure what the problem is.

code:
for ( String s : names ) {
        	String actor = s;
        	if (!s.equals("Kevin Bacon")) {
        		System.out.println("");
         //blah blah blah
So I'm making a 6 Degrees of Kevin Bacon program for class. I'm trying to iterate through an ArrayList of String actor names with a for each loop. My problem is that the only spot inside the for each loop that recognizes the "s" String is that third line there with the if condition. No matter what the hell else I'm doing inside the for each loop, it acts like s doesn't exist and asks me to create it again. What am I doing wrong and how do I fix it?

Psychorider
May 15, 2009

HondaCivet posted:

I have a quick/possibly dumb question about . . . well, for each loops I think, I'm not exactly sure what the problem is.

code:
for ( String s : names ) {
        	String actor = s;
        	if (!s.equals("Kevin Bacon")) {
        		System.out.println("");
         //blah blah blah
So I'm making a 6 Degrees of Kevin Bacon program for class. I'm trying to iterate through an ArrayList of String actor names with a for each loop. My problem is that the only spot inside the for each loop that recognizes the "s" String is that third line there with the if condition. No matter what the hell else I'm doing inside the for each loop, it acts like s doesn't exist and asks me to create it again. What am I doing wrong and how do I fix it?

You should post the rest of the function so we can see why it doesn't work. The only thing I can think of is that you may close too many brackets and you end up outside the loop.

Adbot
ADBOT LOVES YOU

crazyfish
Sep 19, 2002

SintaxError posted:

Alright, so I have a small server app that I'm writing, which works fairly well under a small load. However, after about a minute of light stress testing (new connection every 100ms or so, disconnect after ~45 seconds), this happens:




Although it still runs fun with the 200 threads (they're mostly in a wait state after running small, async jobs via a cachedThreadPool ExecutorService), I'd really rather have it remain at a somewhat steady thread count. I'm at somewhat of a loss as to how to deal with this. NetBeans's profiler isn't much help. tptp in Eclipse is a bit more useful, but isn't exactly shedding any light on the problem either, and in either case there's way too much going on after the fact for a debugger to be useful...

I've pretty much been trying to deal with this all day, so any help/advice would be useful.

Does your thread pool really need to be unbounded? You could try fat provisioning your threads by using a fixed thread pool, but that's not as efficient as the cached one for obvious reasons.

It's really unfortunate that the cached thread pool doesn't allow you to specify an upper bound on the number of threads it creates, though if your multithreading skills are strong you could probably implement a thread pool that does what you want without a massive amount of work.

Also if the asynchronous tasks you're executing have a true async model, you might want to look at using a callbacks instead of threads to carry context.

crazyfish fucked around with this message at 16:58 on May 9, 2010

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