miercuri, 1 februarie 2012

Java Enums. The “non obvious” way to cast to an int and vice versa

Enums are usually stored as ints in most programming languages. Those languages usually allow the programmer to freely convert between the enum and the underlying integer value, but Java doesn’t want you to do that. I want to do this:

private enum Command = { stop, start} // stop = 0, start = 1

Command myCommand = start;

int value = (int)myCommand; // won’t compile

Command aCommand = (Command)1; // also won’t compile

There’s no shortage of Java programmers who will tell you that trying to perform the above is “bad” practice. Their reasoning goes something like if you trying to convert an enum to an int they you are using the enum wrong. Sure if you are using the enum in something like a switch statement then there’s no need to convert it to an int. However, as soon as you are trying saving that enum to a file, or send it over a network connection, or set it as a field in a sql statement, it’s not going to work. The problem is that the file doesn’t have any idea (nor does it care) about Java enums. TCP/UDP doesn’t understand Java enums either. It’ll handle byte streams just fine, but to convert your enum to a byte stream first you have to convert it to an int. Lastly, I have yet to see a database that accepts a Java enum as a field. They basically all accept ints though.

Which leads us back to our problem. We want to convert our enum to and/or from an int. I’ve seen many elaborate (read: hacked) ways of doing it. I’ve done it myself. It turns out there’s a fairly easy (but non-obvious) way to do it:

Command myCommand = start;

int value = myCommand.ordinal(); // works as expected; although the java docs complain about this usage

Command aCommand = Command.values()[1]; // also works

There’s a Java programmer out there somewhere right now trying to convert his ints to an enum.

source: http://www.chippeddagger.com/2010/04/17/java-enums-the-non-obvious-way-to-cast-to-an-int-and-visa-versa/

luni, 21 februarie 2011

Unbound classpath container: 'JRE System Library jdk 1.6' in project

Problem solved:

Right click on the project -> Properties -> Java Build Path -> Add Library -> JRE System Library -> Workspace default JRE -> Finish.

luni, 15 noiembrie 2010

restart id column

select max(EAT_ID)+1 from EPTOS.ENTITYASSIGNEDTHREADS;

alter table EPTOS.ENTITYASSIGNEDTHREADS alter column EAT_ID restart with 429163;

vineri, 22 ianuarie 2010

In order to access a different computer and if it doesn't work from TotalCmd or Remote Desktop, you have to follow these steps:

A
1. Go into My Computer
2. In Tools - > click Map network drive
3. In the dialog box appeared insert:
path to computer: \\fileserver\kit2
4. Click Connect using different user name and enter user and pass

B
Next time you want to log on to the computer, if the connection cannot be establish
1. In My Computer - right click -> Disconnect
2. use the same steps (A 1-4)

miercuri, 13 ianuarie 2010

My Wiki 1

Update DB

When I update project from CVS:
1. Check changelog.txt in order to see if DB schema has been updated.
2. If DB schema has been updated see which is the last update made.
3. In DbVis, go to the respective DB, into databasedescription table and see schemarevision field. Sort field descending.
4. In projects, search for the update doc and copy content of the doc
5. In DBvis, paste it into SQL Commander and click button Execute as SQL script.

Steps 4 and 5 repeat as long as necessary until the DB will be updated.

miercuri, 2 decembrie 2009

Stack Overflow

The first time I saw something about Stack Overflow was while I was investigating a way to find HTML elements in xpath, in order to use them with Selenium. Couple days ago I finally created my account there and started using it. So far my impression has been very positive.

Stack Overflow is basically just a question-answer site for software developers. But because of its active user mass good questions are replied rapidly and bad ones are moderated. Users receive more privileges the more they are writing good questions and answers.

What is a good question or answer then? That is up to other users who can vote, edit or close your entry.

miercuri, 1 aprilie 2009

JAVA - joc: ghiceste un numar !

Jocul Ghiceste numarul

Se genereaza un numar aleator intre 0 - 10 (inclusiv) care se posteaza intr-un cookie. Utilizatorul introduce numele sau si incepe jocul. Primeste raspunsuri in legatura cu raspunsul sau: numarul este mai mare sau mai mic decat cel introdus. La final se afiseaza numarul de incercari facute pentru a ghici numarul.

Codul primei pagini: startGuessGame.jsp

html


<%@page import="javax.servlet.http.Cookie" %>



Introduceti numele dumneavoastra:








html

Codul paginii a doua: guessGame.jsp

html


<%@page import="javax.servlet.http.Cookie" %>



Bine ai venit, <%if(request.getAttribute("playerName") != null){
out.print(request.getAttribute("playerName")); } %> !



Introduceti in textfield un numar intre 0 - 10!







<%
if(request.getAttribute("eroare") != null){
out.print(request.getAttribute("eroare"));
}
if(request.getAttribute("mesaj") != null){
out.print(request.getAttribute("mesaj"));
}
%>


html

Codul servletului GuessGame.java

package teste;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;

/**
* Servlet implementation class GuessGame
*/
public class GuessGame extends HttpServlet {
private static final long serialVersionUID = 1L;

private static int searchCookie(HttpServletRequest request, String cookieName){
int value = 0;
Cookie[] cookieArray = request.getCookies();
if(cookieArray != null){
for(int i = 0; i < cookieArray.length; i++){
String name = cookieArray[i].getName();
if(name.equals(cookieName)){
//ia valoarea cookie-ului si o pune intr-un String, apoi o transf in int:
String valCookie = cookieArray[i].getValue();
value = Integer.parseInt(valCookie);
}
}
}
return value;
}

/**
* @see HttpServlet#HttpServlet()
*/
public GuessGame() {
super();
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doRequest(request, response);
}

protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int guessingNumber = 0;
int number = 0;
int numarIncercari = 0;

String mesaj = "";
String eroare = "";
String aux = "";

String playerName = request.getParameter("playerName");
log("playerName: " + playerName);

Random randomNumber = new Random();
if(playerName != null){
guessingNumber = randomNumber.nextInt(11);
} else {
guessingNumber = searchCookie(request,"guessNumber");
}

Cookie trialNumber = new Cookie("trialNumber", "trialNumber");
Cookie guessNumber = new Cookie("guessNumber", "guessNumber");

String initGuessCookie = Integer.toString(numarIncercari);
trialNumber.setValue(initGuessCookie);

String initNumberCookie = Integer.toString(guessingNumber);
guessNumber.setValue(initNumberCookie);

try{
String nr = request.getParameter("number");
number = Integer.parseInt(nr);
if(number numarIncercari++;
log("< incercari: " + numarIncercari);
} else if(number>guessingNumber){
numarIncercari++;
log("> incercari: " + numarIncercari);
} else {
numarIncercari++;
log("= incercari: " + numarIncercari);
}
} catch (NumberFormatException nfe) {
eroare = "Eroare! Introduceti un numar valid!";
} finally {
int value = 0;
if(number value = searchCookie(request,"trialNumber");
value++;
aux = Integer.toString(value);
trialNumber.setValue(aux);
mesaj = "Numarul este mai mic! Mai incearca! Incercari: "+ trialNumber.getValue();
log("Numarul de incercari este: "+ trialNumber.getValue());

} else if (number>guessingNumber){
value = searchCookie(request,"trialNumber");
value++;
aux = Integer.toString(value);
trialNumber.setValue(aux);
mesaj = "Numarul este mai mare! Mai incearca! Incercari: "+ trialNumber.getValue();
log("Numarul de incercari este: "+ trialNumber.getValue());

} else if(number == guessingNumber){
value = searchCookie(request,"trialNumber");
value++;
aux = Integer.toString(value);
trialNumber.setValue(aux);
mesaj = "Ati ghicit numarul! Incercari: "+ trialNumber.getValue();
log("Numarul de incercari este: "+ trialNumber.getValue());
trialNumber.setValue("0");
}
request.setAttribute("mesaj", mesaj);
request.setAttribute("eroare", eroare);
request.setAttribute("playerName", playerName);
response.addCookie(trialNumber);
response.addCookie(guessNumber);

RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/teste/guessGame.jsp" );
dispatcher.forward( request, response );
}
}
}