java – How to convert a string to a long one?

I have an object called operation, it is of type String and it stores a value "01"
This value, I want to set it to an object called nuOperacion which is of type Long and must register it in the database, I have the following elements

query.setNuOperation (Long.parseLong (data.getOperation ());

But he sends me the following error:
Java.lang.NumberFormatException: null
And should only one be registered in the database, but I have to collect a "01" in my object
How can I do it?

java – weblogic and spring 403 Forbidden error page

I'm using Google Translator right now.
I'm using Weblogic and SpringMVC.
By the way, I configured the 403Error page in web.xml, but the default forbidden page is executed for something outside the WEB-INF folder.

After searching on Google, I need to configure the weblogic.xml file. But I do not know how to define the file. I'm using a windows server. I would like to know how to fix it.

I would be grateful if you could define and, if so, how to configure it.

java – Design reason to use when you want to apply common features to specific methods?

I'm trying to find a design template to use (if there is one) in a situation where I would do some features on multiple classes. Here is a (simplified) overview of the problem I am facing:

I have Java code to CREATE, UPDATE, DELETE Student objects, Professor objects and Staff objects. And whenever such an object is created, deleted or updated, I want to extract information about the object concerned (such as its name, age, identifier) ​​and inform an external service. So, something like:

StudentDAO class {
public Student createStudent (Student studentToCreate) {
jdbcTemplate.update (INSERT_SQL, .....);
// ===> extract some information from the student
// inform the external service that a student has been created ....
public Student deleteStudent (Student studentToDelete) {
jdbcTemplate.update (DELETE_SQL, .....);
// ===> extract some information from the student
// inform the external service that a student has been deleted ....
// same for the update

ProfessortDAO class {
public professor createProfessor (ProfessorToCreate) {
jdbcTemplate.update (INSERT_SQL, .....);
// ===> extract some information from the teacher
// inform the external service that a teacher has been created ....
public Student deleteProfessor (Professor professorToDelete) {
jdbcTemplate.update (DELETE_SQL, .....);
// ===> extract some information from the teacher
// inform the external service that a teacher has been deleted ...
// same for the update

// repeat for the staff

The example is a bit artificial, but assume that students, faculty, and staff share no hierarchy in inheritance. Is there a way to get this feature without copying and pasting the logic of extracting information and sending it to all CAD classes for the CREATE, DELETE, UPDATE methods?

java – How to distinguish between a wall and the ground in the event of collision with the ground?

I'm programming a collision detection and response system for my voxel game, and after several rewrites, I've come up with a pretty stable and reliable solution. The problem I am currently facing is that I have to distinguish between the fact that the player falls to the ground or walks on a wall. For the moment, I only have the code if the velocity is negative, then corrects upwards, but it forces the player to hang the walls when he walks against a falling one.

My first solution was to calculate the direction from which the player comes by subtracting the previous position and the block with which he is currently colliding. I "search" then in this direction blocks at the feet of the players. If I do not find one, I guess the player walks against a wall and corrects instead horizontally. If I find blocks, I guess the player is stuck in the ground and corrects up.

This is the current crash code:

                checkCollision () {) private
if (! = null) {
if (this.collision) {
float length = (float) Math.sqrt (this.velocityX * this.velocityX + this.velocityY * this.velocityY + this.velocityZ * this.velocityZ);
if (length == 0.0) {
this.predictedX = this.posX;
this.predictedY = this.posY;
this.predictedZ = this.posZ;
} other {
float nVelocityX = this.velocityX / length;
float nVelocityY = this.velocityY / length;
float nVelocityZ = this.velocityZ / length;

float advancement = Math.min (1.0f, length);
float lengthLeft = Math.max (length - 1.0f, 0.0f);

a boolean collided;
this.boundingBox.setCenterXY (this.posX, this.posY, this.posZ);

while (advancement <= length) {
                        this.predictedX = this.posX + nVelocityX * advancement;
                        this.predictedY = this.posY + nVelocityY * advancement;
                        this.predictedZ = this.posZ + nVelocityZ * advancement;

                        // Update bb
                        this.boundingBox.setCenterXY(this.predictedX, this.predictedY, this.predictedZ);

                        // Loop through all blocks the bounding box could collide with from top to bottom
                        for (int y = (int) Math.floor(this.boundingBox.getMaxY()); y >= Math.floor (this.boundingBox.getMinY ()); y--) {
for (int x = (int) Math.floor (this.boundingBox.getMinX ()); x <this.boundingBox.getMaxX (); x ++) {
for (int z = (int) Math.floor (this.boundingBox.getMinZ ()); z < this.boundingBox.getMaxZ(); z++) {
                                    if (y >= 0 && y < IChunk.BLOCK_COUNT) {
                                        collided = false;
                                        IChunk chunk = >> ISection.BLOCK_TO_CHUNK, z >> ISection.BLOCK_TO_CHUNK, false);

Block block;
if (chunk! = null) {
block = BlockRegistry.getBlock (chunk.getBlock (x, y, z));
} other {
block = BlockRegistry.getBlock (1);

if (block.isSolid ()) {
RESULT.facing = null;
if (nVelocityY <0.0f) {
int minX = x;
int maxX = x;
int minZ = z;
int maxZ = z;

float distX = this.prevBoundingBox.getMinX () - x;
float distZ = this.prevBoundingBox.getMinZ () - z;

if (distX < 0.0f) {
                                                    minX -= (int) Math.floor(this.width);
                                                } else if (distX > 0.0f) {
minX ++;
maxX + = (int) Math.floor (this.width);

if (distZ < 0.0f) {
                                                    minZ -= (int) Math.floor(this.depth);
                                                } else if (distZ > 0.0f) {
minZ ++;
maxZ + = (int) Math.floor (this.depth);

int blockY = (int) Math.floor (this.prevBoundingBox.getMinY ());
for (int blockX = minX; blockX <= maxX; blockX ++) {
for (int blockZ = minZ; blockZ <= maxZ; blockZ++) {
                                                        if (blockX == x && blockZ == z) continue;
                                                        int blockId =, blockY, blockZ);

                                                        if (blockId != -1) {
                                                            block = BlockRegistry.getBlock(blockId);

                                                            if (block.isSolid()) {
                                                                RESULT.facing = Facing.TOP;
                                                                break correction;

                                            } else if (nVelocityY > 0.0f && y> Math.floor (this.posY) + this.height && (chunk! = Null &&! BlockRegistry.getBlock (chunk.getBlock (x, y - 1, z)) IsSolid ())) {
// the entity jumps against the ceiling, the downward correction takes precedence
RESULT.facing = Face.BOTTOM;

if (RESULT.facing == null) {
if (Math.abs (nVelocityX)> Math.abs (nVelocityZ)) {
// the speed on the x-axis is higher, the correction on the x-axis takes precedence

if (nVelocityX <0.0f)
RESULT.facing = Facing.EAST;
RESULT.facing = Facing.WEST;
} other {
// the speed on the z axis is greater, the correction on the z axis takes precedence

if (nVelocityZ < 0.0f)
                                                        RESULT.facing = Facing.SOUTH;
                                                        RESULT.facing = Facing.NORTH;

                                            System.out.println("Correction Facing: " +;

                                            OTHER.setPosition(x, y, z);
                                            OTHER.setSize(1.0f, block.getHeight(), 1.0f);
                                            collided = this.boundingBox.intersects(OTHER, RESULT);

                                        if (collided) {
                                            if (y == Math.floor(this.boundingBox.getMinY()) && RESULT.facing != Facing.TOP) {
                                                // there is only collision at the feet -> stepup
this.predictedY = Math.floor (this.predictedY) + block.getHeight ();
} other {
this.applyCorrection ();
break loop;

if (advancement> = length) {

lengthLeft = Math.max (lengthLeft - 1.0f, 0.0f);
advancement = length - lengthLeft;
} other {
this.predictedX = this.posX + this.velocityX;
this.predictedY = this.posY + this.velocityY;
this.predictedZ = this.posZ + this.velocityZ;

To prevent the player from ghosting through the walls during brisk walking, I divide the movement into units along the speed axis until all speed is processed. The first positive collision detection will cause a correction and will cancel any subsequent checks.

If a solid block is found, a static AABB is set on the block coordinates and a collision check is performed. According to previously defined conditions, a correction for an axis is calculated and stored in the RESULT variable. Intersection & Correction itself works as expected.

I do not know why, but the player may slip into the ground once during his landing after hitting a wall, as shown in this video:

Is there another way to detect if I'm walking against a wall or falling into the ground?

java – Get JSON composed of tables with Retrofit 2 and Android

I am trying to create an application in Android Studio and I want to use a recipe to cook, here is the answer of the API that I consume with Android Studio and Java:

"q": "chicken",
"from": 0,
"to": 10,
"params": {
"cure": [ ],
"Q": [ "pollo" ],
"App_id": [ "02" ],
"App_key": [ "n66b" ]
"more": true,
"account": 1000,
"recipe": {
"uri": "",
"label": "Chicken with herbs cream",
"image": "",
"source": "KiwiLimon",
"url": "",
"shareAs": "",
"yield": 42.0,

And continue with more 'recipe', what I want is to get only the number of hits that all the recipes must be able to display in my application, the problem is that I get the following error:

BEGIN_ARRAY expected but BEGIN_OBJECT at line 1 column 2 path $

I understand it's because it's waiting for a table and getting a JSON object, but I do not know how to parse it, I have my Recipe template class and the RecipeService service and I handle everything in MainActivity. I have seen in some answers that I should make an intermediate response, but I do not understand how I could implement it in my code, so I show the classes that handle all that.


public class Recipe {
private channel label;
private channel image;
private chain source;
private String shareAs;
private list dietLabels;
private list health tags;
private list warnings;
private list line of ingredients;
private list Ingredients;
double private calories;
double private totalWeight;
private list totalNutrients;
private list totalDaily;

public String getLabel () {
return label;


                public interface RecipeService {

String API_ROUTE = "/ search";
String API_KEY = "& app_key =" + Credentials.API_KEY;
String APP_ID = "& app_id =" + Credentials.APP_ID;
// String query = "";

Call <list > getRecipe (@Query ("q") String q);



    private void getRecipes () {
Retrofit Retrofit = new Retrofit.Builder ()
.baseUrl ("")
.addConverterFactory (GsonConverterFactory.create ())
.build ();

RecipeService recipeService = retrofit.create (RecipeService.class);
Call <list> call = recipeService.getRecipe ("chicken");

System.out.println ("GET RECIPES");
System.out.println ("HEADERS:" + call.request (). Headers ());

call.enqueue (new Callback <List> () {
public void onResponse (Call <List> call, answer <list> answer) {

System.out.println ("ANSWER CODE:" + response.code ());
for (recipe recipe: response.body ()) {

System.out.println ("ADDING:" + recipe.getLabel ());
recipes.add (recipe.getLabel ());
//System.out.printlnnrecipes.toArray (). ToString ());

public void onFailure (Call <List> call, Throwable t) {
System.out.println ("AN ARRIVAL FAULT");
System.out.println (t.getMessage ());

apt – installation error of Java on Debian 8

I followed the instructions on this site:

When I install jre and jdk, it is written:

Reading package lists ... Done
Build a dependency tree
Reading status information ... Done
default-jdk is already the most recent version.
0 upgraded, 0 newly installed, 0 to delete and 1 not upgraded.

I followed the instructions to the letter:

sudo apt-get install oracle-java8-install

After that says:

                Build a dependency tree
Reading status information ... Done
E: Can not locate the oracle-java8-installer package

And when I run
java -version
javac -version

It says:

bash: java: command not found

java – What would be the simplest way to generate random numbers, really random, without repetition?

I've been looking at solutions involving very complex lists or methods, but I wanted to know if there was a simple way to generate random, really random numbers in JAVA, because with only Math.random, this n & rsquo; Is not enough …

java – domain name API for multiple key objects

We implement an API and want to follow best practices for naming endpoints. However, during the design, we found a challenge. We have some objects where the key of the objects is a combination of three keys: key1, key2, key3.

We followed for other objects (for example, orders) the model:

    api / orders? fiter1 = value1 & filter2 = value2 # To retrieve the list of commands that have not been filled by the filters.
api / orders / {key} # To retrieve a specific order

But what if the key is actually a combination key in the database, for example, the combination of the day and the name of the person, for example?

Some developers follow this approach:

1 /

    api / order? day = 2017-05-20 & name = Bob # I do not like this approach because the end points are singular. 

2 /

    api / orders / {month} / {name} # Do not like because it's really naughty

I've seen a different approach, which I like very much:

    api / orders / {date: name} 

In this idea, the key is created by combining the two properties. Is this a good approach?

java – search the shortest path in the matrix for multiple objects

I've implemented the A * search algorithm that finds the shortest path from start to finish.

The implementation looks like this

Public class AStarShortestPathContext {

Private Vertex[][]    matrix;
private int lines, columns;
private int cost;
PriorityQueue private openList;
private set closedSet;

public AStarShortestPathContext (int rows, int columns, int cost) {
this.rows = rows;
this.columns = columns;
this.cost = cost;

openList = new PriorityQueue <> (Comparator.comparingInt (Vertex :: getF));
closedSet = new HashSet <> ();

public list find (Vertex startVertex, Vertex goalVertex, boolean[][]    blocked) {
refreshContext ();

Vertex start = new Vertex (startVertex);
Vertex goal = new Vertex (goalVertex);

CalculUtils.updateEuristic (matrix, goal);

openList.add (start);
while (! openList.isEmpty ()) {
Vertex current = openList.poll ();
closedSet.add (current);
if (current.equals (goal)) {
return path (current);
} other {
neighbors (current, blocked);

return Collections.emptyList ();

/** Temporary solution **/
public void refreshContext () {
// Do I really have to do every research?
this.matrix = new top[rows][];
for (int i = 0; i <lines; i ++) {
this.matrix[i] = new summit[columns];
for (int j = 0; j <columns; j ++) {
matrix[i][j]    = new vertex (i, j);

openList.clear ();
closedSet.clear ();

private empty neighbors (Vertex current, boolean[][]    blocked) {
int row = current.getRow ();
int column = current.getColumn ();

lower int = row + 1;
if (lower < rows && !blocked[lower][column]) {
            checkAdjacentVertex(current, lower, column);

        int left = column - 1;
        if (left >= 0 &&! Blocked[row][left]) {
checkAdjacentVertex (current, row, left);

int right = column + 1;
if (on the right < columns && !blocked[row][right]) {
            checkAdjacentVertex(current, row, right);

        int upper = row - 1;
        if (upper >= 0 &&! Blocked[upper][column]) {
checkAdjacentVertex (current, upper, column);

private void checkAdjacentVertex (Current Top, int row, int column) {
Adjacent vertex = matrix[row][column];
if (! closedSet.contains (adjacent)) {
int g = ComputationUtils.g (current, cost);
if (! openList.contains (adjacent)) {
updateVertex (adjacent, current, g, ComputationUtils.f (adjacent));
openList.add (adjacent);
} other {
if (g <adjacent.getG ()) {
updateVertex (adjacent, current, g, ComputationUtils.f (adjacent));

// like no default update operation, we need to delete and add a node
openList.remove (adjacent);
openList.add (adjacent);

// considering that I only need the last vertex, I may need to adjust it
private list path (topGoGoal) {
listing path = new ArrayList <> ();
path.add (reachedGoal);

Parent of the summit;
while ((parent = reachGoal.getParent ()) !! = null) {
path.add (0, parent);
reachGoal = parent;
way back;

updateVertex (Vertex v, parent Vertex, int g, int f) private void {
v.setParent (parent);
v.setG (g);
v.setF (f); // the order is important because F depends on G


It is supposed to work for multiple robots (threads) on the same table. For that I created competitor context class that looks like this

Public class AStarShortestPathConcurrentContext implements IObservable {
private AStarShortestPathContext searchContext;
private boolean[][]    blocked;
private list <IObserver> observers;

public AStarShortestPathConcurrentContext (int ranks, int columns, int cost) {
searchContext = new AStarShortestPathContext (rows, columns, cost);
blocked = DataUtils.generateEmptyBoolMatrix (rows, columns);
observers = new ArrayList <> ();

public Vertex next (Vertex startVertex, Vertex goalVertex, String Identifier) ​​{
listing path = searchContext.find (startVertex, goalVertex, blocked);
// the starting vertex is 0, the next vertex is 1
Next Summit = path.get (1);
updateBlockedTable (startVertex, next);

// basically tell Swing JTable to update values ​​in cells and force rendering
notifyObserver (ChangeStateEvent
.constructeur ()
.identifier (login)
.newState (NPCWalkState
.constructeur ()
.row (next.getRow ())
.column (next.getColumn ())
.to build())
.previousState (NPCWalkState
.constructeur ()
.row (startVertex.getRow ())
.column (startVertex.getColumn ())
.to build())
.to build());
then return;

private void updateBlockedTable (Vertex startVertex, Vertex next) {
int block_row = next.getRow ();
int block_column = next.getColumn ();

int release_row = startVertex.getRow ();
int release_column = startVertex.getColumn ();

blocked[blocked_row][blocked_column]    = true;
blocked[released_row][released_column]    = false;

public void addObserver (IObserver observer) {
observers.add (observer);

public Void notifyObserver (ChangeStateEvent data) {
.parallelStream ()
.forEach (observer -> observer.receiveNotification (data));

And this class is used in threads.

Public class WalkableNPCThread implements Runnable {
private speed;
private String objectId;
private AStarShortestPathConcurrentContext searchContext;
Vertex private startVertex;
private Vertex goalVertex;

public WalkableNPCThread (npc WalkableNPC, AStarShortestPathConcurrentContext searchContext) {
this.speed = npc.getSpeed ​​();
this.searchContext = searchContext;
this.objectId = npc.getIdentifier ();

public void configureWalk (int initialRow, int initialColumn, int goalRow, int goalColumn) {
startVertex = new Vertex (initialRow, initialColumn);
goalVertex = new Vertex (goalRow, goalColumn);

public void run () {
while (! startVertex.equals (goalVertex)) {
ThreadUtils.delaySeconds (speed);
Vertex nextStep = (startVertex, goalVertex, objectId);
startVertex = new Vertex (nextStep);

The array is the same for all threads, so I instantiate AStarShortestPathConcurrentContext once and pass it as a constructor parameter to each thread. It seems to work properly.

What bothers me, is this method

public Vertex next (Vertex startVertex, Vertex goalVertex, String Identifier) ​​{
listing path = searchContext.find (startVertex, goalVertex, blocked);
// the starting vertex is 0, the next vertex is 1
Next Summit = path.get (1);
updateBlockedTable (startVertex, next);

// basically tell Swing JTable to update values ​​in cells and force rendering
notifyObserver (ChangeStateEvent
.constructeur ()
.identifier (login)
.newState (NPCWalkState
.constructeur ()
.row (next.getRow ())
.column (next.getColumn ())
.to build())
.previousState (NPCWalkState
.constructeur ()
.row (startVertex.getRow ())
.column (startVertex.getColumn ())
.to build())
.to build());
then return;

I synchronize it to prevent updates from blocked field by other threads and also to prevent the update of the AStarShortestPathContext when searching (I update it for each thread before searching).

I'm not sure I need to block the whole method following. Is there a way to do that better?

I thought I was using lock for the whole method instead of synchronized but that would block the whole method.

selenium webdriver for java API: findElement produces different results

I use Selenium WebDriver for Java to explore this page:

In my code the method

WebElement.findElement (...)

produces different results, as follows:

1.) My source code:


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import at.home.digest.model.HomeToDeal;

public class ImmoweltBot {

public static final String URL = "";
public static final String queryURL = URL + "/ list / wien / wohnungen / mieten? sort = relevanz";

public static void main (String [] args) throws Exception {

System.setProperty ("", "C: \ Temp \ chromedriver.exe");

String URLPage = StringUtils.EMPTY;
int page = 1;
int totalNumberOfEntities = 6000;
int numberOfEntitiesFound = 0;

listing elemnts = new ArrayList <> ();

WebDriver webDriver = new ChromeDriver ();

while (numberOfEntitiesFound <totalNumberOfEntities) {

webDriver.get (queryURL + URLPage);

WebDriverWait wait = new WebDriverWait (webDriver, 5);
By searchResults = By.xpath ("// *[contains(@class, 'clear relative js-listitem')]");

JavascriptExecutor js = (JavascriptExecutor) webDriver;
webDriver.manage (). window (). maximize ();
js.executeScript ("window.scrollBy (0,1000)");

final int totalNumberOfKeyDowns = 190;
int keyDownTries = 0;
while ((++ keyDownTries <totalNumberOfKeyDowns)) {
elemnts = wait.until (ExpectedConditions.presenceOfAllElementsLocatedBy (searchResults));
webDriver.findElement (By.tagName ("body")). sendKeys (Keys.DOWN);


WebElement elem = webDriver.findElement (By.xpath ("// *[contains(@class, 'ellipsis margin_none')]"));
totalNumberOfEntities = Utils.parseNumber (elem.getText ()). intValue ();

for (int i = 0; i <elemnts.size (); i ++) {
WebElement divListItemClear = elemnts.get (i);
HomeToDeal homeToRent = new HomeToDeal ();
String exposeURL = divListItemClear.findElement (By.tagName ("a")). GetAttribute ("href");
homeToRent.setURL (exposURL);

WebElement listContentClear = divListItemClear.findElement (By.xpath ("// *[contains(@class, 'listcontent clear')]"));
WebElement h2Elem = listContentClear.findElement (By.tagName ("h2"));
String text = h2Elem.getText ();
homeToRent.setDescription (text);

System.out.println (homeToRent);

URLPage = "& cp =" + (++ page);
numberOfEntitiesFound + = elemnts.size ();


My problem is that the line

String exposeURL = divListItemClear.findElement (By.tagName ("a")). GetAttribute ("href");

works as expected and gives me the following URL of the element (for each new iteration of the cycle), but the lines

WebElement listContentClear = divListItemClear.findElement (By.xpath ("// *[contains(@class, 'listcontent clear')]"));
WebElement h2Elem = listContentClear.findElement (By.tagName ("h2"));
String text = h2Elem.getText ();

give me EACH TIME ONE AND THE SAME value of the h2- HTML element and it's always about the value of the first item found.

Ideas what am I doing wrong?

Thank you!