Why is Soot always saying That the class I want to load is a phantom class, even when it does not exist - soot

This soot class loads a class and prints the number of methods.
When I give the correct name of the class I want to load it says that the class is phantom. Also when the class does not exist it gives the same message. I do not know what I am doing wrong.
public class Loader {
public static void main(String args[]){
List<String> projectPaths;
String classPath;
String highLevelPackageName;
classPath = "C:\\Users\\Alastair\\workspace1\\Interview\\bin";
projectPaths = new ArrayList<String>();
projectPaths.add(classPath);
Options.v().set_allow_phantom_refs(true);
Options.v().set_whole_program(true);
Options.v().set_app(true);
Options.v().set_no_bodies_for_excluded(true);
Options.v().set_process_dir(projectPaths);
String previousClassPath = Scene.v().getSootClassPath();
previousClassPath += ";" + classPath;
Scene.v().setSootClassPath(previousClassPath);
SootClass sootClass = Scene.v().loadClassAndSupport("Diagonal.class");
sootClass.setApplicationClass();
System.out.println(sootClass.getMethodCount());
}
}
This is the class I am trying to load.
public class Diagonal {
public static void main(String args[]) {
diagonal();
lefttriangle();
righttriangle();
tree();
}
public static void diagonal() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == j) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
}
public static void lefttriangle() {
for(int i=0;i<6;i++){
for(int j=0;j<6;j++){
if(j<=i){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println("");
}
}
public static void righttriangle(){
for(int i=0;i<7;i++){
for(int j=7;j>0;j--){
if(i<j){
System.out.print(" ");
}else{
System.out.print("*");
}
}
System.out.println("");
}
}
public static void tree(){
for(int i=1;i<=7;i++){
for(int j=7;j>i;j--){
System.out.print(" ");
}
for(int j = 1; j < i*2; j++){
System.out.print("*");
}
System.out.println("");
}
}
}

Phantom classes are implicitly created models of classes that do not exist on Soot's classpath. To get rid of this problem, make sure that the class you are referencing is on Soot's classpath.

Related

Concurrent writing elements into the ConcurrentHashMap admits element

Concurrent writing elements into the ConcurrentHashMap admits element. Requirements: writing must be done in different threads. Is there way to use advantages of the ConcurrentHashMap and do writing without blocking and sleeping?
Is there good code for iterator that accessed from different treads. Or is there other good variant to keep ieratian looking on the effectively-final requirement?
public class Task3v2 {
public static void main(String[] args) {
System.out.println("ConcurrentHashMap : "+timeIt(new ConcurrentHashMap<Integer, String>()));
}
static Iterator<Integer> integerIterator;
static {createIterator();}
private static void createIterator() {
integerIterator=
Stream.iterate(0, i -> i + 1).limit(100).collect(Collectors.toList()).iterator();
}
public static double timer(Runnable block) {
long start = System.nanoTime();
try {
block.run();
} finally {
long end = System.nanoTime();
return(end - start);
}
}
public static double timeIt(Map<Integer, String> map){
return timer(
()->{
new Thread(()->{
fillMap(map);
System.out.println("invoked");
readMap(map);
}).start();
});
}
private static void fillMap(Map<Integer, String> map){
int[] index = new int[1];
String[] tmp = new String[1];
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i = 0; i< 100; i++){
index[0] = i;
tmp[0] = "Name"+i;
new Thread(()->{
int a = integerIterator.next();
System.out.println("a :"+a);
map.put(a,"Name"+a);
}
).start();
}
}
private static void readMap(Map<Integer, String> map){
int[] index2 = new int[1];
for(int i = 0; i< 100; i++){
index2[0]=i;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
System.out.println("map.get(index2[0]) :"+map.get(index2[0]));
}).start();
}
}
}
Finally the map must pass following tests:
public class Task3Test {
static ConcurrentHashMap<Integer, String> map;
#BeforeClass
public static void fillMap(){
map = new ConcurrentHashMap<>();
timeIt(map);
}
#Test
public void elementPresenceTest(){
//GIVEN
//map;
//WHEN
List<Integer> actualPresenceList = Stream.iterate(0, i -> i + 1).limit(100)
.filter(n->(map.entrySet().stream().map(Map.Entry::getKey)
.anyMatch(m->(n.equals(m))))).collect(Collectors.toList());
actualPresenceList.forEach(System.out::println);
System.out.println("size"+actualPresenceList.size());
//THEN
List<Integer>expectedPresenceList = Stream.iterate(0, i -> i + 1).limit(100).collect(Collectors.toList());
assertThat(actualPresenceList, Matchers.contains(expectedPresenceList));
}
#Test
public void elementAmountTest() {
assertThat(map.entrySet(), Matchers.hasSize(100));
}
}
Iterator is not acceptable for concurrency. Solution is:
static Queue integerQueue = Stream.iterate(0, i -> i + 1).limit(100).collect(Collectors.toCollection(LinkedBlockingQueue::new));
There is needed to keep sleeping for the readMap() method to provide time for the writing method. If there is needed to keep any data structure on adding new elements in concurrency environment, it should be used queue instead of map.

Spark|ML|Random Forest|Load trained model from .txt of RandomForestClassificationModel. toDebugString

Using Spark 1.6 and the ML library I am saving the results of a trained RandomForestClassificationModel using toDebugString():
val rfModel = model.stages(2).asInstanceOf[RandomForestClassificationModel]
val stringModel =rfModel.toDebugString
//save stringModel into a file in the driver in format .txt
So my idea is that in the future read the file .txt and load the trained randomForest, is it possible?
thanks!
That won't work. ToDebugString is merely a debug info to understand how it's got calculated.
If you want to keep this thing for later use, you can do the same we do, which is (although we are in pure java) simply serialise RandomForestModel object. There might be version incompatibilities with default java serialisation, so we use Hessian to do it. It worked through versions update - we started with spark 1.6.1 and it still works with spark 2.0.2.
If you're ok with not sticking to ml, juste use mllib's implementation: the RandomForestModel you get with mllib has a save function.
At least for Spark 2.1.0 you can do this with the following Java (sorry - no Scala) code. However, it may not be the smartest idea to rely on an undocumented format that may change without notice.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.US_ASCII;
/**
* RandomForest.
*/
public abstract class RandomForest {
private static final Logger LOG = LoggerFactory.getLogger(RandomForest.class);
protected final List<Node> trees = new ArrayList<>();
/**
* #param model model file (format is Spark's RandomForestClassificationModel toDebugString())
* #throws IOException
*/
public RandomForest(final URL model) throws IOException {
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(model.openStream(), US_ASCII))) {
Node node;
while ((node = load(reader)) != null) {
trees.add(node);
}
}
if (trees.isEmpty()) throw new IOException("Failed to read trees from " + model);
if (LOG.isDebugEnabled()) LOG.debug("Found " + trees.size() + " trees.");
}
private static Node load(final BufferedReader reader) throws IOException {
final Pattern ifPattern = Pattern.compile("If \\(feature (\\d+) (in|not in|<=|>) (.*)\\)");
final Pattern predictPattern = Pattern.compile("Predict: (\\d+\\.\\d+(E-\\d+)?)");
Node root = null;
final List<Node> stack = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
final String trimmed = line.trim();
//System.out.println(trimmed);
if (trimmed.startsWith("RandomForest")) {
// skip the "Tree 1" line
reader.readLine();
} else if (trimmed.startsWith("Tree")) {
break;
} else if (trimmed.startsWith("If")) {
// extract feature index
final Matcher m = ifPattern.matcher(trimmed);
m.matches();
final int featureIndex = Integer.parseInt(m.group(1));
final String operator = m.group(2);
final String operand = m.group(3);
final Predicate<Float> predicate;
if ("<=".equals(operator)) {
predicate = new LessOrEqual(Float.parseFloat(operand));
} else if (">".equals(operator)) {
predicate = new Greater(Float.parseFloat(operand));
} else if ("in".equals(operator)) {
predicate = new In(parseFloatArray(operand));
} else if ("not in".equals(operator)) {
predicate = new NotIn(parseFloatArray(operand));
} else {
predicate = null;
}
final Node node = new Node(featureIndex, predicate);
if (stack.isEmpty()) {
root = node;
} else {
insert(stack, node);
}
stack.add(node);
} else if (trimmed.startsWith("Predict")) {
final Matcher m = predictPattern.matcher(trimmed);
m.matches();
final Object node = Float.parseFloat(m.group(1));
insert(stack, node);
}
}
return root;
}
private static void insert(final List<Node> stack, final Object node) {
Node parent = stack.get(stack.size() - 1);
while (parent.getLeftChild() != null && parent.getRightChild() != null) {
stack.remove(stack.size() - 1);
parent = stack.get(stack.size() - 1);
}
if (parent.getLeftChild() == null) parent.setLeftChild(node);
else parent.setRightChild(node);
}
private static float[] parseFloatArray(final String set) {
final StringTokenizer st = new StringTokenizer(set, "{,}");
final float[] floats = new float[st.countTokens()];
for (int i=0; st.hasMoreTokens(); i++) {
floats[i] = Float.parseFloat(st.nextToken());
}
return floats;
}
public abstract float predict(final float[] features);
public String toDebugString() {
try {
final StringWriter sw = new StringWriter();
for (int i=0; i<trees.size(); i++) {
sw.write("Tree " + i + ":\n");
print(sw, "", trees.get(0));
}
return sw.toString();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static void print(final Writer w, final String indent, final Object object) throws IOException {
if (object instanceof Number) {
w.write(indent + "Predict: " + object + "\n");
} else if (object instanceof Node) {
final Node node = (Node) object;
// left node
w.write(indent + node + "\n");
print(w, indent + " ", node.getLeftChild());
w.write(indent + "Else\n");
print(w, indent + " ", node.getRightChild());
}
}
#Override
public String toString() {
return getClass().getSimpleName() + "{numTrees=" + trees.size() + "}";
}
/**
* Node.
*/
protected static class Node {
private final int featureIndex;
private final Predicate<Float> predicate;
private Object leftChild;
private Object rightChild;
public Node(final int featureIndex, final Predicate<Float> predicate) {
Objects.requireNonNull(predicate);
this.featureIndex = featureIndex;
this.predicate = predicate;
}
public void setLeftChild(final Object leftChild) {
this.leftChild = leftChild;
}
public void setRightChild(final Object rightChild) {
this.rightChild = rightChild;
}
public Object getLeftChild() {
return leftChild;
}
public Object getRightChild() {
return rightChild;
}
public Object eval(final float[] features) {
Object result = this;
do {
final Node node = (Node)result;
result = node.predicate.test(features[node.featureIndex]) ? node.leftChild : node.rightChild;
} while (result instanceof Node);
return result;
}
#Override
public String toString() {
return "If (feature " + featureIndex + " " + predicate + ")";
}
}
private static class LessOrEqual implements Predicate<Float> {
private final float value;
public LessOrEqual(final float value) {
this.value = value;
}
#Override
public boolean test(final Float f) {
return f <= value;
}
#Override
public String toString() {
return "<= " + value;
}
}
private static class Greater implements Predicate<Float> {
private final float value;
public Greater(final float value) {
this.value = value;
}
#Override
public boolean test(final Float f) {
return f > value;
}
#Override
public String toString() {
return "> " + value;
}
}
private static class In implements Predicate<Float> {
private final float[] array;
public In(final float[] array) {
this.array = array;
}
#Override
public boolean test(final Float f) {
for (int i=0; i<array.length; i++) {
if (array[i] == f) return true;
}
return false;
}
#Override
public String toString() {
return "in " + Arrays.toString(array);
}
}
private static class NotIn implements Predicate<Float> {
private final float[] array;
public NotIn(final float[] array) {
this.array = array;
}
#Override
public boolean test(final Float f) {
for (int i=0; i<array.length; i++) {
if (array[i] == f) return false;
}
return true;
}
#Override
public String toString() {
return "not in " + Arrays.toString(array);
}
}
}
To use the class for classification, use:
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* RandomForestClassifier.
*/
public class RandomForestClassifier extends RandomForest {
public RandomForestClassifier(final URL model) throws IOException {
super(model);
}
#Override
public float predict(final float[] features) {
final Map<Object, Integer> counts = new HashMap<>();
trees.stream().map(node -> node.eval(features))
.forEach(result -> {
Integer count = counts.get(result);
if (count == null) {
counts.put(result, 1);
} else {
counts.put(result, count + 1);
}
});
return (Float)counts.entrySet()
.stream()
.sorted((o1, o2) -> Integer.compare(o2.getValue(), o1.getValue()))
.map(Map.Entry::getKey)
.findFirst().get();
}
}
For regression:
import java.io.IOException;
import java.net.URL;
/**
* RandomForestRegressor.
*/
public class RandomForestRegressor extends RandomForest {
public RandomForestRegressor(final URL model) throws IOException {
super(model);
}
#Override
public float predict(final float[] features) {
return (float)trees
.stream()
.mapToDouble(node -> ((Number)node.eval(features)).doubleValue())
.average()
.getAsDouble();
}
}

OrientDB all paths between two nodes

#OrientDB 2.1.12 :
I want to find ALL possible PATHS of ANY length between two nodes considering navigation by OUT edges only.
I am using shortestPath() but it returns only one path. I searched a lot and I couldn’t find a native class which does this in OrientDB. I am already using non-native class. However, it is not efficient enough. Here some of the shortespath code:
s = " select expand( shortestpath(" + first_vertex.getId() + ", " + second_vertex.getId() + ", "+ direction +"))";
for (Vertex v : (Iterable<Vertex>) g.command(new OCommandSQL(s)).execute()){
. . .
. . .
}
Is there any native solution in OrientDB as it is the case in Neo4j?
You can use this code
import java.util.ArrayList;
import java.util.List;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class AllPaths {
private boolean stop=false;
private Vertex vertexFrom=null;
private List<Vertex> vertexPreviousStep=new ArrayList<Vertex>();
private List<Vertex> vertexCurrently=new ArrayList<Vertex>();
private List<List<Vertex>> paths=new ArrayList<List<Vertex>>();
private OrientGraph g;
public AllPaths(OrientGraph g) {
this.g=g;
}
protected List<List<Vertex>> getPaths(String ridFrom, String ridTo) {
if(!check(ridFrom,ridTo))
return paths;
vertexPreviousStep.add(vertexFrom);
List<Vertex> p=new ArrayList<Vertex>();
p.add(vertexFrom);
paths.add(p);
int step=1;
do{
stop=false;
for(Vertex v: vertexPreviousStep){
List<Vertex> toAdd=new ArrayList<Vertex>();
Iterable<Vertex> nodes = (Iterable<Vertex>) v.getVertices(Direction.OUT);
for(Vertex v1:nodes){
toAdd.add(v1);
if(!v1.getId().toString().equals(ridTo))
vertexCurrently.add(v1);
}
if(toAdd.size()!=0)
setPaths(v,toAdd,step);
}
change();
step++;
}while(stop==true);
return cleanPaths(ridTo);
}
private boolean check(String ridFrom,String ridTo) {
boolean findFrom=false,findTo=false;
for(Vertex v:g.getVertices()){
if(v.getId().toString().equals(ridFrom)){
findFrom=true;
vertexFrom=v;
}
else if(v.getId().toString().equals(ridTo))
findTo=true;
}
if(findFrom==false || findTo==false)
return false;
return true;
}
public void change(){
vertexPreviousStep.clear();
for(Vertex v:vertexCurrently)
vertexPreviousStep.add(v);
vertexCurrently.clear();
}
private void setPaths(Vertex previousVertex,List<Vertex> toAdd,int step) {
for(int i=0;i<paths.size();i++){
List<Vertex> list=paths.get(i);
Vertex last=list.get(list.size()-1);
if(last.getId().toString().equals(previousVertex.getId().toString()) && list.size()==step){
int j=0;
for(Vertex v1:toAdd){
boolean vertexFound=false;
for(Vertex v2:list){
if(v2.getId().toString().equals(v1.getId().toString()))
vertexFound=true;
}
if(vertexFound==false){
List<Vertex> listVertex=new ArrayList<Vertex>();
for(Vertex p:list)
listVertex.add(p);
listVertex.add(v1);
if(j==0){
stop=true;
paths.set(i,listVertex);
j++;
}
else
paths.add(listVertex);
}
}
}
}
}
public List<List<Vertex>> cleanPaths(String ridTo){
for(int i=0;i<paths.size();i++){
List<Vertex> list=paths.get(i);
if(!list.get(list.size()-1).getId().toString().equals(ridTo)){
paths.remove(i);
i--;
}
}
return paths;
}
public static void main(String[] args) {
OrientGraph g=new OrientGraph("remote:localhost/MyDb");
AllPaths paths=new AllPaths(g);
System.out.println(paths.getPaths("#9:0", "#9:8"));
}
}
UPDATE
import java.util.ArrayList;
import java.util.List;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class Main {
private boolean stop=false;
private List<Vertex> visitedNodesPreviousStep=new ArrayList<Vertex>();
private List<Vertex> visitedNodeCurrently=new ArrayList<Vertex>();
private List<List<Vertex>> path_vertex=new ArrayList<List<Vertex>>();
private List<List<Edge>> path_edges=new ArrayList<List<Edge>>();
private OrientGraph g;
int step=0;
public Main(OrientGraph g) {
this.g=g;
}
protected List<List<Object>> getDistance(String starting_rid, String ending_rid,int depth) {
Vertex starting_node=g.getVertex(starting_rid);
Vertex ending_node=g.getVertex(ending_rid);
visitedNodesPreviousStep.add(starting_node);
List<Vertex> p1=new ArrayList<Vertex>();
p1.add(starting_node);
path_vertex.add(p1);
step=1;
boolean found_node_to_be_added=false;
do{
stop=false;
found_node_to_be_added=false;
for(Vertex v: visitedNodesPreviousStep){
List<Edge> edges_to_be_added=new ArrayList<Edge>();
List<Vertex> nodes_to_be_added=new ArrayList<Vertex>();
Iterable<Edge> it_edge = (Iterable<Edge>) v.getEdges(Direction.OUT);
for(Edge e1:it_edge){
Vertex v1=e1.getVertex(Direction.IN);
edges_to_be_added.add(e1);
nodes_to_be_added.add(v1);
String rid=v1.getId().toString();
if(!rid.equals(ending_rid)){ // checking the current #rid isn't the ending
visitedNodeCurrently.add(v1);
}
else{ // ending node found
setPathFoundList(v,ending_node,step,e1);
//stop=true;
}
}
if(nodes_to_be_added.size()!=0 && stop==false){
found_node_to_be_added=true;
setpath_vertex(v,nodes_to_be_added,edges_to_be_added);
}
}
if(found_node_to_be_added==false){
stop=true;
}
//System.out.println("step = " + step + " " +path_vertex);
change();
step++;
}while(stop==false && step<depth);
clean_vertex_path(ending_node);
return getShortestPathList();
}
public void change(){
visitedNodesPreviousStep.clear();
for(Vertex v:visitedNodeCurrently)
visitedNodesPreviousStep.add(v);
visitedNodeCurrently.clear();
}
private void setPathFoundList(Vertex node,Vertex ending_node,int step,Edge edge){
for(int i=0;i<path_vertex.size();i++){
List<Vertex> path=path_vertex.get(i);
Vertex last=path.get(path.size()-1);
if(last.getId().equals(node.getId()) && path.size()==step){
path.add(ending_node);
List<Edge> edgesPath=path_edges.get(i);
edgesPath.add(edge);
}
}
}
private void setpath_vertex(Vertex node,List<Vertex> nodes_to_be_added,List<Edge> edges_to_be_added) {
for(int i=0;i<path_vertex.size();i++){
List<Vertex> path=path_vertex.get(i);
Vertex last=path.get(path.size()-1);
if(last.getId().equals(node.getId())){
int j=0;
for(int h=0;h<nodes_to_be_added.size();h++){
boolean name_present=false;
for(Vertex p:path){
if(p.getId().equals(nodes_to_be_added.get(h).getId()))
name_present=true;
}
if(name_present==false){
List<Vertex> p2=new ArrayList<Vertex>();
for(Vertex p:path)
p2.add(p);
p2.add(nodes_to_be_added.get(h));
List<Edge> e2=new ArrayList<Edge>();
if(step==1){
e2.add(edges_to_be_added.get(h));
}
else{
List<Edge> edgesPath=path_edges.get(i);
for(Edge p1:edgesPath)
e2.add(p1);
e2.add(edges_to_be_added.get(h));
}
if(j==0){
path_vertex.set(i, p2);
if(step==1){
path_edges.add(i, e2);
}
else{
path_edges.set(i, e2);
}
j++;
}
else{
path_vertex.add(p2);
path_edges.add(e2);
}
}
}
}
}
}
public void clean_vertex_path(Vertex ending_node_name){
for(int i=0;i<path_vertex.size();i++){
List<Vertex> path=path_vertex.get(i);
if(!path.get(path.size()-1).getId().equals(ending_node_name.getId())){
path_vertex.remove(i);
path_edges.remove(i);
i--;
}
}
}
public List<List<Object>> getShortestPathList(){
List<List<Object>> resultList=new ArrayList<List<Object>>();
if(path_vertex.size()==0)
return new ArrayList<List<Object>>();
else{
for(int i=0;i<path_vertex.size();i++){
List<Object> result=new ArrayList<Object>();
List<Vertex> path2= path_vertex.get(i);
List<Edge> edges2= path_edges.get(i);
for(int k=0;k<path2.size();k++){
result.add(path2.get(k));
if(k!=path2.size()-1)
result.add(edges2.get(k));
}
resultList.add(result);
}
}
return resultList;
}
public static void main(String[] args) {
String remote="remote:localhost/";
String DBname="ShortestPath";
String currentPath=remote+DBname;
OServerAdmin serverAdmin;
try {
serverAdmin = new OServerAdmin(currentPath).connect("root", "root");
if(serverAdmin.existsDatabase()){
OrientGraph g=new OrientGraph(currentPath);
Main shortest2 = new Main(g);
System.out.println("SHORTEST PATH " + shortest2.getDistance("#9:0","#9:8",5));
}
}
catch(Exception e){
}
}
}
Hope it helps.
# Lvca and # Alessandro
I used this code by "LucaS" OrientDB get Edges with shortestPath()
I find it efficient and useful. What you think about? It retrieves all paths between two nodes. How I can determine the search depth to be for example of depth 2,3, 4 etc.?
import java.util.ArrayList;
import java.util.List;
import com.orientechnologies.orient.client.remote.OServerAdmin;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
public class myClass {
private boolean stop=false;
private List<Vertex> visitedNodesPreviousStep=new ArrayList<Vertex>();
private List<Vertex> visitedNodeCurrently=new ArrayList<Vertex>();
private List<List<Vertex>> path_vertex=new ArrayList<List<Vertex>>();
private List<List<Edge>> path_edges=new ArrayList<List<Edge>>();
private OrientGraph g;
int step=0;
public myClass(OrientGraph g) {
this.g=g;
}
protected List<Object> getDistance(String starting_rid, String ending_rid) {
Vertex starting_node=g.getVertex(starting_rid);
Vertex ending_node=g.getVertex(ending_rid);
visitedNodesPreviousStep.add(starting_node);
List<Vertex> p1=new ArrayList<Vertex>();
p1.add(starting_node);
path_vertex.add(p1);
step=1;
boolean found_node_to_be_added=false;
do{
stop=false;
found_node_to_be_added=false;
for(Vertex v: visitedNodesPreviousStep){
List<Edge> edges_to_be_added=new ArrayList<Edge>();
List<Vertex> nodes_to_be_added=new ArrayList<Vertex>();
Iterable<Edge> it_edge = (Iterable<Edge>) v.getEdges(Direction.OUT);
for(Edge e1:it_edge){
Vertex v1=e1.getVertex(Direction.IN);
edges_to_be_added.add(e1);
nodes_to_be_added.add(v1);
String rid=v1.getId().toString();
if(!rid.equals(ending_rid)){ // checking the current #rid isn't the ending
visitedNodeCurrently.add(v1);
}
else{ // ending node found
setPathFoundList(v,ending_node,step,e1);
stop=true;
}
}
if(nodes_to_be_added.size()!=0 && stop==false){
found_node_to_be_added=true;
setpath_vertex(v,nodes_to_be_added,edges_to_be_added);
}
}
if(found_node_to_be_added==false){
stop=true;
}
System.out.println("step = " + step + " " +path_vertex);
change();
step++;
}while(stop==false);
clean_vertex_path(ending_node);
return getShortestPathList();
}
public void change(){
visitedNodesPreviousStep.clear();
for(Vertex v:visitedNodeCurrently)
visitedNodesPreviousStep.add(v);
visitedNodeCurrently.clear();
}
private void setPathFoundList(Vertex node,Vertex ending_node,int step,Edge edge){
for(int i=0;i<path_vertex.size();i++){
List<Vertex> path=path_vertex.get(i);
Vertex last=path.get(path.size()-1);
if(last.getId().equals(node.getId()) && path.size()==step){
path.add(ending_node);
List<Edge> edgesPath=path_edges.get(i);
edgesPath.add(edge);
}
}
}
private void setpath_vertex(Vertex node,List<Vertex> nodes_to_be_added,List<Edge> edges_to_be_added) {
for(int i=0;i<path_vertex.size();i++){
List<Vertex> path=path_vertex.get(i);
Vertex last=path.get(path.size()-1);
if(last.getId().equals(node.getId())){
int j=0;
for(int h=0;h<nodes_to_be_added.size();h++){
boolean name_present=false;
for(Vertex p:path){
if(p.getId().equals(nodes_to_be_added.get(h).getId()))
name_present=true;
}
if(name_present==false){
List<Vertex> p2=new ArrayList<Vertex>();
for(Vertex p:path)
p2.add(p);
p2.add(nodes_to_be_added.get(h));
List<Edge> e2=new ArrayList<Edge>();
if(step==1){
e2.add(edges_to_be_added.get(h));
}
else{
List<Edge> edgesPath=path_edges.get(i);
for(Edge p1:edgesPath)
e2.add(p1);
e2.add(edges_to_be_added.get(h));
}
if(j==0){
path_vertex.set(i, p2);
if(step==1){
path_edges.add(i, e2);
}
else{
path_edges.set(i, e2);
}
j++;
}
else{
path_vertex.add(p2);
path_edges.add(e2);
}
}
}
}
}
}
public void clean_vertex_path(Vertex ending_node_name){
for(int i=0;i<path_vertex.size();i++){
List<Vertex> path=path_vertex.get(i);
if(!path.get(path.size()-1).getId().equals(ending_node_name.getId())){
path_vertex.remove(i);
path_edges.remove(i);
i--;
}
}
}
public List<Object> getShortestPathList(){
List<Object> result=new ArrayList<Object>();
if(path_vertex.size()==0)
return new ArrayList<Object>();
else{
List<Vertex> path=path_vertex.get(0);
int min_size= path.size();
for(int i=0;i<path_vertex.size();i++){
if(path_vertex.get(i).size()<=min_size){
List<Vertex> path2= path_vertex.get(i);
List<Edge> edges2= path_edges.get(i);
for(int k=0;k<path2.size();k++){
result.add(path2.get(k));
if(k!=path2.size()-1)
result.add(edges2.get(k));
}
}
}
}
return result;
}
public static void main(String[] args) {
String remote="remote:localhost/";
String DBname="Stack36794694";
String currentPath=remote+DBname;
OServerAdmin serverAdmin;
try {
serverAdmin = new OServerAdmin(currentPath).connect("root", "root");
if(serverAdmin.existsDatabase()){
OrientGraph g=new OrientGraph(currentPath);
myClass shortest2 = new myClass(g);
System.out.println("SHORTEST PATH " + shortest2.getDistance("#9:0","#9:5"));
}
}
catch(Exception e){
}
}
}

Sending an object to host from a client

I cant seem to find the problem on the code but it the server is not displaying anything. It displays the catch. Client seems find and it sets the players name and score and sends it but I cant seem to find the issue on this one why server is not displaying the name and score.
Here is my Client:
public class Client
{
private static final int BUFSIZE = 64;
public static void main(String[] args) throws IOException
{
try
{
int scores;
Scanner in = new Scanner(System.in);
Socket clntSock = new Socket("127.0.0.1", 6000);
System.out.println("What is the filename?");
String input = in.nextLine();
Scanner fileInput = new Scanner(new File(input));
ObjectOutputStream out = new
ObjectOutputStream(clntSock.getOutputStream());
Player playerObject = new Player();
playerObject.setName(fileInput.nextLine());
System.out.println(""+playerObject.getName());
for (int i = 0; i < 5; i++)
{
scores = Integer.parseInt(fileInput.nextLine());
playerObject.setScore(scores);
System.out.println(""+playerObject.getScores().get(i));
}
out.writeObject(playerObject);
in.close();
fileInput.close();
out.close();
clntSock.close();
}
catch ( UnknownHostException ex )
{
System.out.println( "Unknown host" );
}
}
}
and my Host:
public class Host
{
private static final int BUFSIZE = 64;
public static void main(String[] args) throws IOException
{
// Step 1: Create a ServerSocket.
ServerSocket servSock = new ServerSocket(6000);
PrintStream fileOut = new PrintStream("Datafromclient.txt");
try
{
// Step 2: Wait for a connection..
Socket clntSock = servSock.accept();
// Step 3: Get input and output streams.
System.out.println("Step 3: Get object input stream.,");
ObjectInputStream objectIn = new
ObjectInputStream(clntSock.getInputStream());
Player playerObjct = (Player)objectIn.readObject();
System.out.println("The name of Player: "+playerObjct.getName());
for(int i=0; i <5; i++)
{
System.out.println("Scores:"+playerObjct.getScores().get(i));
}
objectIn.close();
clntSock.close();
// Step 5: Close connection
objectIn.close();
clntSock.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
}
}
My player class:
public class Player
private String name;
private int playerId;
private int bestScore;
private static int numberOfPlayers = 0;
private ArrayList<Integer> scores = new ArrayList<Integer>();
/* -------------- CONSTRUCTOR --------------------------------------
*/
public Player()
{
numberOfPlayers++;
playerId = numberOfPlayers;
}
public Player(String name)
{
this.name = name;
}
//Create set method for setName
public void setName(String name)
{
this.name = name;
}
//Create set method for setScores
public void setScore(int score)
{
scores.add(score);
}
//Create get method for getPlayerId
public int getPlayerId()
{
return this.playerId;
}
//Create get method for getName
public String getName()
{
return this.name;
}
//Create get method for getScores
public ArrayList<Integer> getScores()
{
return scores;
}
//Create get method for getBestScore
public int getBestScore()
{
calculateBestScore();
return bestScore;
}
//Method to expose the value of numberOfPlayers
public static int getNumberOfPlayers()
{
return numberOfPlayers;
}
//Create get method for calcualteAverage
public double calculateAverage()
{
Integer sum = 0;
if(!scores.isEmpty())
{
for(Integer score : scores)
{
sum += score;
}
return sum.doubleValue() / scores.size();
}
return sum;
}
public void calculateBestScore()
{
bestScore = Collections.max(scores);
}
}
I was missing
import java.io.Serializable;
public class Player implements Serializable
now its working.

Implementing busy wait with a pair of flags

I am trying to implement a busy waiting mechanism, using 2 flags. I get a deadlock, but just can't understand why... it looks to me as if it should work...
sorry for the long code, That's the shortest I succeeded to make it.
package pckg1;
public class MainClass {
public static void main(String[] args) {
Buffer b = new Buffer();
Producer prod = new Producer(b);
Consumer cons = new Consumer(b);
cons.start();
prod.start();
}
}
class Producer extends Thread {
private Buffer buffer;
public Producer(Buffer buffer1) {
buffer = buffer1;
}
public void run() {
for (int i = 0; i < 60; i++) {
while (!buffer.canUpdate)
;
buffer.updateX();
buffer.canUpdate = false;
buffer.canUse = true;
}
}
}
class Consumer extends Thread {
private Buffer buffer;
public Consumer(Buffer buffer1) {
buffer = buffer1;
}
public void run() {
for (int i = 0; i < 60; i++) {
while (!buffer.canUse)
;
buffer.consumeX();
buffer.canUse = false;
buffer.canUpdate = true;
}
}
}
class Buffer {
private int x;
public boolean canUpdate;
public boolean canUse;
public Buffer() {
x = 0;
canUpdate = true;
}
public void updateX() {
x++;
System.out.println("updated to " + x);
}
public void consumeX() {
System.out.println("used " + x);
}
}
I recommend that all the logic concerning Buffer should go into that class.
Also, accessing (and modifying) the flags must be protected, if 2 or more have access to it. That's why I put synchronised to the 2 methods.
class Buffer {
private int x;
private boolean canUpdate;
private boolean canUse;
public Buffer() {
x = 0;
canUpdate = true;
}
public synchronised void updateX() {
x++;
System.out.println("updated to " + x);
canUpdate = false;
canUse = true;
}
public synchronised void consumeX() {
System.out.println("used " + x);
canUpdate = true;
canUse = false;
}
public synchronised boolean canUse() {
return canUse;
}
public synchronised boolean canUpdate() {
return canUpdate;
}
}
Also, remove the canUpdate and canUse writes from the Producer and Consumer classes, and replace the reads (in the conditons) with the methods.
Also, it would be useful to introduce some Thread.sleep(100) in the waiting loops.

Resources