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?
Some swing code I write in my computer behave different on my colleague's computer, and in my PC, and in my notebook.
I wonder, is there something I can do to my Swing applications behave the same in every computer?
I want to have sure a algorithm I've tested in my computer will work the same way in my clients computers.
E.g.
Problem to focus JTextField
Trying to tail / parse some log files. Entries start with a date then can span many lines.
This works, but does not ever see new entries to file.
File inputFile = new File("C:/test.txt");
InputStream is = new FileInputStream(inputFile);
InputStream bis = new BufferedInputStream(is);
//bis.skip(inputFile.length());
Scanner src = new Scanner(bis);
src.useDelimiter("\n2010-05-01 ");
while (true) {
while(src.hasNext()){
System.out.println("[ " + src.next() + " ]");
}
}
Doesn't seem like Scanner's next() or hasNext() detects new entries to file.
Any idea how else I can implement, basically, a tail -f with custom delimiter.
ok - using Kelly's advise i'm checking & refreshing the scanner, this works. Thank you !!
if anyone has improvement suggestions plz do!
File inputFile = new File("C:/test.txt");
InputStream is = new FileInputStream(inputFile);
InputStream bis = new BufferedInputStream(is);
//bis.skip(inputFile.length());
Scanner src = new Scanner(bis);
src.useDelimiter("\n2010-05-01 ");
while (true) {
while(src.hasNext()){
System.out.println("[ " + src.next() + " ]");
}
Thread.sleep(50);
if(bis.available() > 0){
src = new Scanner(bis);
src.useDelimiter("\n2010-05-01 ");
}
}
I am a building a console Sudoku Solver where the main objective is raw speed.
I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. So one WorkerThread is started for each cell right now. How can I re-use an existing thread that has completed its work?
The Thread Pool Pattern seems to be the solution, but I don't understand what to do to prevent the thread from dying once its job has been completed.
ps : I do not expect to gain much performance for this particular task, just want to experiment how multi-threading works before applying it to the more complex parts of the code.
Thanks
Is there a way to set DPI in swing ? For the whole application ? And if there is how do I set it to the value of system DPI ?
I guess there must be a way to do it as I mentioned this feature must have benn added to NetBeans in some of latest versions...
Thank you for reading
i am triying to write a web based proxy site on google app engine.Displaying the first page of entered url was fairly simple urlFetching api but i am unable to figure out how to proxify the links and requests origionating from this newly displayed page.
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
for my application I have to build a little customized time ticker which ticks over after whatever delay I tell it to and writes the new value in my textArea. The problem is that the ticker is running fully until the termination time and then printing all the values. How can I make the text area change while the code is running.
while(tick<terminationTime){
if ((System.currentTimeMillis()) > (msNow + delay)){
msNow = System.currentTimeMillis();
tick = tick + 1;
currentTime.setText(""+tick);
sourceTextArea.append(""+tick+" " + System.currentTimeMillis() +" \n");
}
currentTime and sourceTextArea are both text areas and both are getting updated after the while loop ends.
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?
I'm looking for a simple commons method or operator that allows me to repeat some String n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.
String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");
Related to:
repeat string javascript
Create NSString by repeating another string a given number of times
Edited
I try to avoid for loops when they are not completely necessary because:
They add to the number of lines of code even if they are tucked away in another function.
Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".
Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".
They are very often easy to get wrong. For loops that involving indexes tend to generate off by one bugs.
For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.
For loops increase the number of places a bug hunter has to look.
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'm using AES to encrypt/decrypt some files in GCM mode using BouncyCastle.
While I'm proving wrong key for decryption there is no exception.
How should I check that the key is incorrect?
my code is this:
SecretKeySpec incorrectKey = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] block = new byte[1048576];
int i;
cipher.init(Cipher.DECRYPT_MODE, incorrectKey, ivSpec);
BufferedInputStream fis=new BufferedInputStream(new ProgressMonitorInputStream(null,"Decrypting ...",new FileInputStream("file.enc")));
BufferedOutputStream ro=new BufferedOutputStream(new FileOutputStream("file_org"));
CipherOutputStream dcOut = new CipherOutputStream(ro, cipher);
while ((i = fis.read(block)) != -1) {
dcOut.write(block, 0, i);
}
dcOut.close();
fis.close();
thanks
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>.
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.
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.
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?
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
}
}
public class Owner extends Master {
public void printSomething () {
System.out.println ("This printed from Owner");
}
public int returnSomeCals ()
{
return 5+5;
}
}
Without messing with methods of subclass...is it possible to execute printForAllMethodsInSubClass() before the method of a subclass gets executed?
Okay, what I have so far is:
You enter the game, and write "spin" to the console.
Program will enter the while loop.
In the while loop, if entered int is -1, return to the back (Set console input back to "", and let the user select what game he would like to play).
Problem:
Instead of going back, and selecting "spin" again, the program exits?
Why is it happening? How can I fix this?
private static Scanner console = new Scanner(System.in);
private static Spin spin = new Spin();
private static String inputS = "";
private static int inputI = 0;
private static String[] gamesArray = new String[] {"spin", "tof"};
private static boolean spinWheel = false;
private static boolean tof = false;
public static void main (String[] args) {
if (inputS.equals("")) {
System.out.println("Welcome to the system!");
System.out.print("Please select a game: ");
inputS = console.nextLine();
}
while (inputS.equals("spin")) {
System.out.println("Welcome to the spin game! Please write 1 to spin. and -1 to exit back");
inputI = console.nextInt();
switch (inputI) {
case 1:
break;
case -1:
inputI = 0;
inputS = "";
break;
}
}
}
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?
I want to buy Microsoft SQL Server 2008 Web Edition in order to remotely install it on the server.
The question is: Can I buy a licence in USA and pay in US dollars? OR do I have to buy it in my country (Portugal)? Since the servers are in Germany, should I buy the licence in Germany?
(And if anyone know a good reseller I would apreciate)
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 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?