public void saveBuku(Buku newBuku) { try { Transaction TxBuku = sess.beginTransaction(); sess.save(newBuku); TxBuku.commit(); } catch (Exception e) { e.printStackTrace(); } }
@Override public String execute() throws Exception { try { Map session = ActionContext.getContext().getSession(); setUser((User) session.get("user")); Date date = new Date(); System.out.println("Time\t\t" + getDeltime() + "\t\t"); setProduct((Product) getMyDao().getDbsession().get(Product.class, getProductid())); getProduct().setUser(getUser()); getProduct().setName(getPname()); getProduct().setDelivaryTime(getDeltime()); getProduct().setDescription(getDesc()); getProduct().setQty(getQty()); getProduct().setVat(getVat()); getProduct().setPrice(getPrice()); getProduct().setPostage(getPostage()); getProduct().setUnitsSold(getSold()); getProduct().setStatus(userEnum.Active.getUserType()); getProduct().setDate(date); getMyDao().getDbsession().update(getProduct()); if (getImag() != null) { byte[] bimg = new byte[(int) getImag().length()]; byte[] bimg2 = new byte[(int) getImg2().length()]; byte[] bimg3 = new byte[(int) getImg3().length()]; FileInputStream flogo = new FileInputStream(getImag()); FileInputStream fim1 = new FileInputStream(getImg2()); FileInputStream fim2 = new FileInputStream(getImg3()); flogo.read(bimg); fim1.read(bimg2); fim2.read(bimg3); setPimg(new Productimage(getProductid(), getProduct())); getPimg().setImagefile(bimg); getPimg().setImg2(bimg2); getPimg().setImg3(bimg3); getMyDao().getDbsession().saveOrUpdate(getPimg()); } else { } Criteria pro = getMyDao().getDbsession().createCriteria(Product.class); pro.add(Restrictions.eq("user", getUser())); pro.setMaxResults(50); setProdlist((List<Product>) pro.list()); addActionMessage("Product \t" + getPname() + "\tSuccessfully Updated"); return "success"; } catch (Exception e) { addActionError("error" + e.getMessage()); e.printStackTrace(); return "error"; } }
public void updateBuku(Posts newBuku) { try { Transaction TxBuku = sess.beginTransaction(); sess.update(newBuku); TxBuku.commit(); } catch (Exception e) { e.printStackTrace(); } }
public MaskFormatter Mascara(String Mascara) { MaskFormatter F_Mascara = new MaskFormatter(); try { F_Mascara.setMask(Mascara); // Atribui a mascara F_Mascara.setPlaceholderCharacter(' '); // Caracter para preencimento } catch (Exception excecao) { excecao.printStackTrace(); } return F_Mascara; }
public List<Buku> getListBuku() { List<Buku> LstBuku = null; try { Transaction TxBuku = sess.beginTransaction(); Query q = sess.createQuery("from Buku"); LstBuku = q.list(); } catch (Exception e) { e.printStackTrace(); } return LstBuku; }
// Method that allows the user to create a new game in the database public void CreateGame( ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) { try { // Defining variables from typed values in the CreateScreen panel String gamename = frame.getCreate().getTfGameName().getText(); int mapSize = frame.getCreate().getTfMapSize(); String controls = frame.getCreate().getTfControls().getText(); // Checks whether the typed in values are legitimate // Strings controls and gamename can't be empty and the map size can't be 0 if (!controls.equals("") && mapSize != 0 && !gamename.equals("")) { // Creates objects of/instansialize Game and Gamer classes Game game = new Game(); Gamer gamer = new Gamer(); // Sets controls equal to the typed controls gamer.setControls(controls); // Sets id equal to the logged in user (the current user) gamer.setId(currentUser.getId()); // Sets the above defined id as the host of the game game.setHost(gamer); // Sets the gamename and mapsize equal to the typed values game.setName(gamename); game.setMapSize(mapSize); // All of the above setters are used to @post the variables into the database // String json = new Gson().toJson(game); String message = parser.createParser(server.post(json, "games/")); // Checks if the received list of games contains the newly created game // If so a confirmation will be shown to the user if (message.equals(game.getName())) { JOptionPane.showMessageDialog( frame, "Game was created!\nIt's called " + game.getName(), "Success!", JOptionPane.INFORMATION_MESSAGE); } } // Prints a stacktrace when catching an unforeseen error } catch (Exception e) { e.printStackTrace(); } }
// Method that shows the top 5 scores in the ScoreScreen panel public void ShowHighscore(ScreenFrame frame, ServerConnection server, Parsers parser) { // try { // Initiates highscore class Highscore highscores = new Highscore(); // Instantiates highscore object..? highscores = parser.scoreParser(server.get("scores/"), highscores); // Sets the labels in ScoreScreen panel equal to the obtained scores from servers frame .getHighscore() .getLblFirst() .setText("#1: " + String.valueOf(highscores.getFirstPlace() + " points")); frame .getHighscore() .getLblSecond() .setText("#2: " + String.valueOf(highscores.getSecondPlace() + " points")); frame .getHighscore() .getLblThird() .setText("#3: " + String.valueOf(highscores.getThirdPlace() + " points")); frame .getHighscore() .getLblFourth() .setText("#4: " + String.valueOf(highscores.getFourthPlace() + " points")); frame .getHighscore() .getLblFifth() .setText("#5: " + String.valueOf(highscores.getFifthPlace() + " points")); // } catch (Exception e) { e.printStackTrace(); } }
// Boolean method that allows the user to deleting a game with a known Game Id public boolean DeleteGame(ScreenFrame frame, ServerConnection server, Parsers parser) { // Try/catch for error handling through exceptions try { // Gets variable gameId from DeleteScreen panel // Defines which game that has to be deleted long gameId = frame.getDelete().getTfGameId(); // String message = parser.messageParser(server.delete("games/" + gameId)); // If the server returns "Game was deleted" the statement returns true // which executes the lines at Controller class (l. 157-160) if (message.equals("Game was deleted")) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; }
// Method that makes it possible for the user to log in public User Login(ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) { // Sets variables username and password equal to the typed values in the LoginScreen panel String username = frame.getLoginScreen().getTfUsername().getText(); String password = frame.getLoginScreen().getTfPassword().getText(); // Try/catch for error handling through exceptions try { // If-statement for checking the typed values. // If the typed values aren't equal to "" (empty textfields) the method will be executed if (!username.equals("") & !password.equals("")) { User user = new User(); // Sets the username and password for the logged in user equal to the typed values user.setUsername(username); user.setPassword(password); // Sends String json = new Gson().toJson(user); // Sends String message = parser.loginParser((server.post(json, "login/")), user); // Checks whether the received message is equal to the wanted one if (message.equals("Login successful")) { currentUser = user; // Uses the userParser method to get .. parser.userParser(server.get("users/" + currentUser.getId() + "/"), currentUser); // Leads the user to the usermenu frame.show(frame.USERSCREEN); // Returns the value/variable/object currentUser to define who's logged in return currentUser; // If the server can't fit the typed values // Responds following received message with a JOptionPane that will warn the user } else if (message.equals("Wrong username or password")) { JOptionPane.showMessageDialog( frame, "Wrong username or password. Please try again", "Error", JOptionPane.ERROR_MESSAGE); // If the error is elsewhere than in the typed values // Responds following received message with a JOptionPane that will warn the user } else if (message.equals("Error in JSON")) { JOptionPane.showMessageDialog(frame, "Error", "Error", JOptionPane.ERROR_MESSAGE); } } // Prints a stacktrace when catching an unforeseen error } catch (Exception e) { e.printStackTrace(); } return null; }
// Method that allows the user to join a game and at the same time starting, determining who's the // winner public void JoinGame( ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) { // Try/catch for error handling through exceptions try { // Defines the variables gameId for the game and controls for the joining user // GamId is set as type long because the server apparently sends back long type variables long gameId = frame.getJoin().getTfGameId(); String controls = frame.getJoin().getTfControls().getText(); // Checks whether the opponent typed controls are legitimate if (!controls.equals("")) { // Instansierer/create new objects of game and gamer class Game game = new Game(); Gamer gamer = new Gamer(); // Sets the gamer id equal to the current users id gamer.setId(currentUser.getId()); // Sets the typed in controls equal to gamer controls gamer.setControls(controls); // Sets the gameId equal to the typed gameId game.setGameId(gameId); // Sets the gamer to being the opponent game.setOpponent(gamer); String json = new Gson().toJson(game); String message = parser.messageParser(server.put("games/join/", json)); // Checks whether the PUT-request succeeded if (message.equals("Game was joined")) { // Game joined = parser.joinParser(server.put("games/start/", json)); joined = parser.joinParser(server.get("game/" + joined.getGameId() + "/")); // If the SnakeMasterId is equal to the opponent (current user) // the panel shows a message confirming that the opponent won if (joined.getSnakeMasterId() == currentUser.getId()) { JOptionPane.showMessageDialog( frame, "You joined the game and won!", "WINNER!", JOptionPane.INFORMATION_MESSAGE); // If the SnakeMasterId isn't equal to the current users // the panel shows a message confirming that the host won } else if (joined.getSnakeMasterId() != currentUser.getId()) { JOptionPane.showMessageDialog( frame, "You joined the game and lost!\nBuhuu..", "LOSER", JOptionPane.INFORMATION_MESSAGE); } // If the PUT-request message equals "Game closed" // the panel shows error message to the user } else if (message.equals("Game closed")) { JOptionPane.showMessageDialog( frame, "The Game is closed. Check your Game Id again", "NOPE", JOptionPane.ERROR_MESSAGE); } } } catch (Exception e) { e.printStackTrace(); } }
/** * routing using A* algorithm with fibonacci heap basically same as routingAStar function * * @param startNode * @param endNode * @param startTime * @param pathNodeList return path * @return */ public static double routingAStarFibonacci( long startNode, long endNode, int startTime, int dayIndex, ArrayList<Long> pathNodeList) { System.out.println("start finding the path..."); int debug = 0; double totalCost = -1; try { // test store transversal nodes // HashSet<Long> transversalSet = new HashSet<Long>(); if (!OSMData.nodeHashMap.containsKey(startNode) || !OSMData.nodeHashMap.containsKey(endNode)) { System.err.println("cannot find start or end node!"); return -1; } if (startNode == endNode) { System.out.println("start node is the same as end node."); return 0; } HashSet<Long> closedSet = new HashSet<Long>(); HashMap<Long, FibonacciHeapNode<NodeInfoHelper>> nodeHelperCache = new HashMap<Long, FibonacciHeapNode<NodeInfoHelper>>(); FibonacciHeap<NodeInfoHelper> openSet = initialStartSet(startNode, endNode, nodeHelperCache); HashSet<Long> endSet = initialEndSet(endNode); NodeInfoHelper current = null; FibonacciHeapNode<NodeInfoHelper> fCurrent = null; while (!openSet.isEmpty()) { // remove current from openset fCurrent = openSet.min(); openSet.removeMin(); current = fCurrent.getData(); // if(!transversalSet.contains(current.getNodeId())) // transversalSet.add(current.getNodeId()); long nodeId = current.getNodeId(); // add current to closedset closedSet.add(nodeId); if (endSet.contains(nodeId)) { // find the destination current = current.getEndNodeHelper(endNode); totalCost = current.getCost(); break; } // for time dependent routing int timeIndex = startTime + (int) (current.getCost() / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL); if (timeIndex > OSMRouteParam.TIME_RANGE - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights timeIndex = OSMRouteParam.TIME_RANGE - 1; LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(nodeId); if (adjNodeList == null) continue; // this node cannot go anywhere double arriveTime = current.getCost(); // for each neighbor in neighbor_nodes(current) for (ToNodeInfo toNode : adjNodeList) { debug++; long toNodeId = toNode.getNodeId(); int travelTime; if (toNode.isFix()) // fix time travelTime = toNode.getTravelTime(); else // fetch from time array travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex); // tentative_g_score := g_score[current] + dist_between(current,neighbor) double costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND; // tentative_f_score := tentative_g_score + heuristic_cost_estimate(neighbor, goal) double heuristicTime = estimateHeuristic(toNodeId, endNode); double totalCostTime = costTime + heuristicTime; // if neighbor in closedset and tentative_f_score >= f_score[neighbor] if (closedSet.contains(toNodeId) && nodeHelperCache.get(toNodeId).getData().getTotalCost() <= totalCostTime) { continue; } NodeInfoHelper node = null; FibonacciHeapNode<NodeInfoHelper> fNode = null; // if neighbor not in openset or tentative_f_score < f_score[neighbor] if (!nodeHelperCache.containsKey(toNodeId)) { // neighbor not in openset // create new one node = new NodeInfoHelper(toNodeId); node.setCost(costTime); node.setHeuristic(heuristicTime); node.setParentId(nodeId); fNode = new FibonacciHeapNode<NodeInfoHelper>(node); openSet.insert(fNode, node.getTotalCost()); nodeHelperCache.put(node.getNodeId(), fNode); } else if (nodeHelperCache.get(toNodeId).getData().getTotalCost() > totalCostTime) { // neighbor in openset fNode = nodeHelperCache.get(toNodeId); node = fNode.getData(); // update information node.setCost(costTime); node.setHeuristic(heuristicTime); node.setParentId(nodeId); if (closedSet.contains(toNodeId)) { // neighbor in closeset closedSet.remove(toNodeId); // remove neighbor form colseset openSet.insert(fNode, node.getTotalCost()); } else { // neighbor in openset, decreaseKey openSet.decreaseKey(fNode, node.getTotalCost()); } } } } if (totalCost != -1) { long traceNodeId = current.getNodeId(); pathNodeList.add(traceNodeId); // add end node traceNodeId = current.getParentId(); while (traceNodeId != 0) { pathNodeList.add(traceNodeId); // add node fCurrent = nodeHelperCache.get(traceNodeId); current = fCurrent.getData(); traceNodeId = current.getParentId(); } Collections.reverse(pathNodeList); // reverse the path list System.out.println("find the path successful!"); } else { System.out.println("can not find the path!"); } // OSMOutput.generateTransversalNodeKML(transversalSet, nodeHashMap); } catch (Exception e) { e.printStackTrace(); System.err.println( "tdsp: debug code " + debug + ", start node " + startNode + ", end node " + endNode); } return totalCost; }
// TODO : if start or end is already in the highway, will occur the problem, need to fix public static double routingHierarchy( long startNode, long endNode, int startTime, int dayIndex, ArrayList<Long> pathNodeList) { // System.out.println("start finding the path..."); int debug = 0; try { if (!OSMData.nodeHashMap.containsKey(startNode) || !OSMData.nodeHashMap.containsKey(endNode)) { System.err.println("cannot find start or end node!"); return -1; } if (startNode == endNode) { System.out.println("start node is the same as end node."); return 0; } NodeInfo start = OSMData.nodeHashMap.get(startNode); NodeInfo end = OSMData.nodeHashMap.get(endNode); double minDistance = Geometry.calculateDistance(start.getLocation(), end.getLocation()); if (minDistance < 5) { // use normal A* algorithm to calculate small distance return routingAStar( start.getNodeId(), end.getNodeId(), OSMRouteParam.START_TIME, OSMRouteParam.DAY_INDEX, pathNodeList); } SearchingSharing sharingData = new SearchingSharing(); HashMap<Long, NodeInfoHelper> nodeForwardCache = new HashMap<Long, NodeInfoHelper>(); HashMap<Long, NodeInfoHelper> nodeReverseCache = new HashMap<Long, NodeInfoHelper>(); ForwardSearching forwardSearching = new ForwardSearching( startNode, endNode, startTime, dayIndex, sharingData, nodeForwardCache); ReverseSearching reverseSearching = new ReverseSearching(endNode, startNode, sharingData, nodeReverseCache); // two thread run simultaneously Thread forwardThread = new Thread(forwardSearching); Thread reverseThread = new Thread(reverseSearching); // search forward forwardThread.start(); // let forward searching for a while // Thread.sleep(100); // search reverse reverseThread.start(); // waiting for thread finish forwardThread.join(); reverseThread.join(); // get the searching intersects ArrayList<Long> intersectList = sharingData.getIntersectList(); // pick the least cost one according to time-dependent double minCost = Double.MAX_VALUE; ArrayList<Long> minCostPath = new ArrayList<Long>(); for (long intersect : intersectList) { NodeInfoHelper current = nodeForwardCache.get(intersect); // cost from source to intersect double cost = current.getCost(); current = nodeReverseCache.get(intersect); // update the reverse cost as forward cost current.setCost(cost); ArrayList<Long> reversePath = new ArrayList<Long>(); double totalCost = Double.MAX_VALUE; // recalculate from intersect to destination while (true) { long nodeId = current.getNodeId(); int timeIndex = startTime + (int) (current.getCost() / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL); if (timeIndex > OSMRouteParam.TIME_RANGE - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights timeIndex = OSMRouteParam.TIME_RANGE - 1; long nextNodeId = current.getParentId(); double arriveTime = current.getCost(); // arrive end if (nextNodeId == 0) { totalCost = arriveTime; break; } // add node reversePath.add(nextNodeId); // calculate cost according adjlist LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(nodeId); double costTime = 0; for (ToNodeInfo toNode : adjNodeList) { if (toNode.getNodeId() == nextNodeId) { int travelTime; // forward searching is time dependent if (toNode.isFix()) // fix time travelTime = toNode.getTravelTime(); else // fetch from time array travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex); costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND; break; } } current = nodeReverseCache.get(nextNodeId); if (costTime == 0) System.err.println("cost time cannot be zero!"); else current.setCost(costTime); } // process the left nodes to real destination long lastNode = reversePath.get(reversePath.size() - 1); if (lastNode != endNode) { NodeInfo last = OSMData.nodeHashMap.get(lastNode); NodeInfo dest = OSMData.nodeHashMap.get(endNode); EdgeInfo onEdge = last.getEdgeFromNodes(dest); current = nodeReverseCache.get(lastNode); int totalDistance = onEdge.getDistance(); int distance; long toNodeId; if (onEdge.getStartNode() == lastNode) { // from start to middle distance = onEdge.getStartDistance(endNode); toNodeId = onEdge.getEndNode(); } else { // from end to middle distance = onEdge.getEndDistance(endNode); toNodeId = onEdge.getStartNode(); } LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(lastNode); double costTime = 0; int timeIndex = startTime + (int) (totalCost / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL); if (timeIndex > OSMRouteParam.TIME_RANGE - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights timeIndex = OSMRouteParam.TIME_RANGE - 1; for (ToNodeInfo toNode : adjNodeList) { if (toNode.getNodeId() == toNodeId) { int travelTime; // forward searching is time dependent if (toNode.isFix()) // fix time travelTime = toNode.getTravelTime(); else // fetch from time array travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex); costTime = (double) travelTime / OSMParam.MILLI_PER_SECOND; break; } } if (costTime != 0) { costTime *= (double) distance / totalDistance; } totalCost += costTime; // add cost reversePath.add(endNode); // add dest } // if found less cost path, build forward path if (totalCost < minCost) { ArrayList<Long> forwardPath = new ArrayList<Long>(); minCost = totalCost; current = nodeForwardCache.get(intersect); long traceNodeId = current.getParentId(); while (traceNodeId != 0) { forwardPath.add(traceNodeId); // add node current = nodeForwardCache.get(traceNodeId); traceNodeId = current.getParentId(); } Collections.reverse(forwardPath); // reverse the path list // record min-cost path, combine forward path and reverse path minCostPath = new ArrayList<Long>(); minCostPath.addAll(forwardPath); minCostPath.add(intersect); minCostPath.addAll(reversePath); // output kml // OSMOutput.generatePathKML(nodeHashMap, pathNodeList, "path_" + intersect); // ArrayList<Long> intersectNode = new ArrayList<Long>(); // intersectNode.add(intersect); // OSMOutput.generatePathNodeKML(nodeHashMap, intersectNode, "intersect_" + intersect); } } pathNodeList.addAll(minCostPath); return minCost; } catch (Exception e) { e.printStackTrace(); System.err.println("routingHierarchy: debug code " + debug); } return 0; }