how are static method calls handled by the JVM? does it still allocate memory when a call is made? if yes, how does garbage collection treat this allocation after the method call?
Rather new to REST and Jersey, and I'm trying out some basic examples. I've got one particular question though, which I haven't really found an answer for yet (don't really know how to look for this): how would you go about storing/defining common services so that they are stateful and accessible to all/some resources?
For instance, a logger instance (Log4J or whatever). Do I have to manually initialize this and store it in the HttpSession? Is there a "best practice" way of doing this so that my logger is accessible to all/some resources?
Thanks a lot.
I have a colon-delimited text file containing grouped, related data. The People group contains people's names followed by their ages, separated by colons. How can I parse the text and group people according to their ages?
The structure is as follows:
Group.txt
Age:10:20:30:40:
Group:G1:10:G2:30:G3:20:G4:40:
People:Jack:10:Tom:30:Dick:20:Harry:10:Paul:10:Peter:20:
People:Mary:20:Lance:10:
And I want to display something like this:
G1 Jack Harry Paul Lance
G2 Dick Peter Marry
G3 Tom
G4
Before debugging the late-hour-out-of-bound-recursive-function: is there a command to get subdirs? giveMeSubDirs(downToPath)?
// WARNING: RECURSION out of bound
public HashSet<FileObject> getAllDirs(String path) {
HashSet<FileObject> checkedDirs = new HashSet<FileObject>();
HashSet<FileObject> allDirs = new HashSet<FileObject>();
String startingPath = path;
File fileThing = new File(path);
FileObject fileObject = new FileObject(fileThing);
for (FileObject dir : getDirsInDir(path)) {
// SUBDIR
while ( !checkedDirs.contains(dir)
&& !(getDirsInDir(dir.getFile().getParent()).size() == 0)) {
// DO NOT CHECK TOP DIRS if any bottom dir UNCHECKED!
while ( uncheckedDirsOnLevel(path, checkedDirs).size() > 0) {
while (getDirsInDir(path).size() == 0
|| (numberOfCheckedDirsOnLevel(path, checkedDirs)==getDirsInDir(path).size())) {
allDirs.add(new FileObject(new File(path)));
checkedDirs.add(new FileObject(new File(path)));
if(traverseDownOneLevel(path) == startingPath )
return allDirs;
//get nearer to the root
path = traverseDownOneLevel(path);
}
path = giveAnUncheckedDir(path, checkedDirs);
if ( path == "NoUnchecked.") {
checkedDirs.add(new FileObject( (new File(path)).getParentFile() ));
break;
}
}
}
}
return allDirs;
}
I'm using JODConverter to convert .xls and .ppt to .pdf format. For this i have code something like
try{
//do something
System.out.println("connecting to open office");
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
System.out.println("connection object created");
connection.connect();
System.out.println("connection to open office successful");
//do something
if(!successful)
throw new FileNotFoundException();
}catch(Exception e){
System.out.println("hello here");
System.out.println("Caught Exception while converting to PDF ");
LOGGER.error("Error in converting media" + e.getMessage());
throw new MediaConversionFailedException();
}finally{
decode_pdf.closePdfFile();
System.out.println("coming in finally");
//do something here
}
My Output :
connecting to open office
connection object created
coming in finally
P.S. return type of method is void
How is it possible ? Even if there is some problem in connection.connect(), it s'd come in catch block. confused
board image
the above is a board layout done by using gridbaglayout.
i would like insets of 5 pixels around the whole board but not between each label.
i scaned the api and havent come up with something that lets me do this.
does this mean i have to nest my board gui inside another gridbaglayout with the insets desired?
thank you.
Hello!
I'm referring to this Nimbus reference.
I tried to set global Font to be slightly larger:
UIManager.put("defaultFont", new Font(Font.SANS_SERIF, 0, 16));
...works only for the menu but nothing else (buttons, labels).
I tried to change labels and buttons fonts with
UIManager.put("Button.font", new Font(Font.SANS_SERIF, 0, 16));
UIManager.put("Label.font", new Font(Font.SANS_SERIF, 0, 16));
but the font remains.
The only thing that worked for me was deriving a font:
someButton.setFont(someButton.getFont().deriveFont(16f));
But this is not an option, since this must be done for each
element manually.
Note, that deriving a font for UIManager doesn't work either:
UIManager.put("Label.font",
UIManager.getFont("Label.font").deriveFont(16f));
I tested everything under Linux and Windows: same behavior.
I just can't understand how an API can be so messy. If a method is called
setFont(..) then I expect it to set the font. If this method fails to
set the font in any thinkable circumstances, then it should be deprecated.
EDIT:
The problem not only applies to Nimbus, but also to the default LAF.
Hi,
I use Eclipse. When I have an application like this:
write 20 times 'Hello World\n' to stdout
write 'ERROR\n' to stderr
write 5 times 'Hello World\n' to stdout
The output looks many times like this:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
Hello World
Hello World
Hello World
ERROR
Is there a way to synchronize these two output streams? Of course without waiting a few milliseconds after the block of 20 times Hello World and waiting a few milliseconds after printing ERROR.
I am aware that you can initialize an array during instantiation as follows:
String[] names = new String[] {"Ryan", "Julie", "Bob"};
Is there a way to do the same thing with an ArrayList? Or must I add the contents individually with array.add()?
Thanks,
Jonathan
I am go through a socket program. In that printStackTrace is caught by the catch block.
Actully what it is?
catch(IOException ioe)
{
ioe.printStackTrace();
}
I am unaware of it. For what they are used?
I am learning GWT for web development and came across a piece of code I can't really understand.
helloBtn.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("Hello!");
}
});
If someone could explain to me what it is doing that would be great.
Thanks, John
Hi,
I am creating some multi-threaded code, and I have created a JobDispatcher class that creates threads. I want this object to handle any unhandled exceptions in the worker threads, and so I am using
Thread.setUncaughtExceptionHandler(this);
Now, I would like to test this functionality - how can I generate an unhandled exception in the run() method of my worker object?
Thanks,
Martin
I have a List that is guaranteed to contain just one type object. This is created by some underlying code in a library that I cannot update. I want to create a List<ObjectType> based on the incoming List object so that my calling code is talking to List<ObjectType>.
What's the best way to convert the List (or any other object collection) to a List<ObjectType>.
I'm curious why the String.indexOf is returning a 0 (instead of -1) when asking for the index of an empty string within a string.
The Javadocs only say this method returns the index in this String of the specified string, -1 if the string isn't found.
System.out.println("FOO".indexOf("")); // outputs 0 wtf!!!
System.out.println("FOO".indexOf("bar")); // outputs -1 as expected
System.out.println("FOO".indexOf("F")); // outputs 0 as expected
System.out.println("".indexOf("")); // outputs 0 as expected, I think
I am trying to get the ip of a socket connection in string form.
I am using a framework, which returns the SocketAddress of the recieved message. How can i transform it to InetSocketAddress or InetAddress?
I want to make an HTTP request and then get the response as sketched here:
URLConnection c = new URL("http://foo.com").openConnection();
c.setDoOutput(true);
/* write an http request here using a new OutputStreamWriter(c.getOutputStream) */
BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream));
reader.readLine();
But my question is, if the request I send takes a long time before a response is received, what happens in the call reader.readLine() above? Will this process stay running/runnable on the CPU or will it get taken off the CPU and be notified to wake up and run again when there is IO to be read?
If it stays on the CPU, what can be done to make it get off and be notified later?
Assign the following 25 scores to a one dimensional int array called "temp"
34,24,78,65,45,100,90,97,56,89,78,98,74,90,98,24,45,76,89,54,12,20,22,55,66
Move the scores to a 2 dimensional int array called "scores" row wise
-- meaning the first 5 scores go into row 0 etc
i have the following class:
public class NewGameContract {
public boolean HomeNewGame = false;
public boolean AwayNewGame = false;
public boolean GameContract(){
if (HomeNewGame && AwayNewGame){
return true;
} else {
return false;
}
}
}
when i try to use it like so:
if (networkConnection){
connect4GameModel.newGameContract.HomeNewGame = true;
boolean status = connect4GameModel.newGameContract.GameContract();
switch (status){
case true:
break;
case false:
break;
}
return;
}
i am getting the error: incompatible types found: boolean required: int on the following switch (status) code.
what am i doing wrong please?
public class PriorityQueue<T> {
private PriorityNode<T> head, tail;
private int numItems;
public PriorityQueue(){
numItems = 0;
head=null;
tail=null;
}
public void add(int priority, T value){
PriorityNode<T> newNode = new PriorityNode<T>(priority,value);
if(numItems == 0){
head = newNode;
tail = newNode;
}
else{
head.setNext(newNode);
head = newNode;
}
}
}
Where PriorityNode is defined as:
public class PriorityNode<T> implements Comparable<T> {
private T value;
private PriorityNode<T> next;
private int priority;
public PriorityNode(int priority,T newValue){
value = newValue;
next = null;
priority = 0;
}
public PriorityNode(T newValue){
value = newValue;
next = null;
priority = 0;
}
public void setPriority(int priority){
this.priority = priority;
}
public int getPriority(){
return this.priority;
}
public T getValue(){
return value;
}
public PriorityNode<T> getNext(){
return next;
}
public void setNext(PriorityNode<T> nextNode){
this.next = nextNode;
}
public void setValue(T newValue){
value = newValue;
}
public int compareTo(int pri) {
// TODO Auto-generated method stub
if(this.priority<pri){
return -1;
}
else if(this.priority == pri){
return 0;
}
else{
return 1;
}
}
}
I'm having a lot of difficulty using the Comparator here and implementing a priority queue - please point me in the right direction.
When I create complex type hierarchies (several levels, several types per level), I like to use the final keyword on methods implementing some interface declaration. An example:
interface Garble {
int zork();
}
interface Gnarf extends Garble {
/**
* This is the same as calling {@link #zblah(0)}
*/
int zblah();
int zblah(int defaultZblah);
}
And then
abstract class AbstractGarble implements Garble {
@Override
public final int zork() { ... }
}
abstract class AbstractGnarf extends AbstractGarble implements Gnarf {
// Here I absolutely want to fix the default behaviour of zblah
// No Gnarf shouldn't be allowed to set 1 as the default, for instance
@Override
public final int zblah() {
return zblah(0);
}
// This method is not implemented here, but in a subclass
@Override
public abstract int zblah(int defaultZblah);
}
I do this for several reasons:
It helps me develop the type hierarchy. When I add a class to the hierarchy, it is very clear, what methods I have to implement, and what methods I may not override (in case I forgot the details about the hierarchy)
I think overriding concrete stuff is bad according to design principles and patterns, such as the template method pattern. I don't want other developers or my users do it.
So the final keyword works perfectly for me. My question is:
Why is it used so rarely in the wild? Can you show me some examples / reasons where final (in a similar case to mine) would be very bad?
Hello friends, I was wanting to add multiple connections in the code below to be able to download files faster. Could someone help me? Thanks in advance.
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it.
file = new RandomAccessFile("C:\\"+getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1) {
break;
}
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
}
}
}
}
I just realized that the method Element.getElementsByTagName("someTagName") returns a nodelist of all elements in the document that have a given tagname. What if I just want to get all child elements by tag name?
For example...
<person>
<name>Bob</name>
<car>
<name>Toyota Corolla</name>
</car>
</person>