/** * This starts the layout thread, it does not run before this. Note this is a background check it * doesn't stop when done it just sleeps until it gets more work. */ public void start() { if (controller != null && !runner.isAlive() && !pauseState) { active = true; runner.start(); } }
/** @param args the command line arguments */ public static void main(String[] args) throws Exception { try { conf = new JsonFile("config.json").read(); address = conf.getJson().get("bind_IP").toString(); port = Integer.parseInt(conf.getJson().get("port").toString()); collection = new CollectThread(conf); collection.start(); s = new ServerSocket(port, 50, InetAddress.getByName(address)); System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("listening on: " + address + ":" + port + "\n"); } catch (Exception e) { System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("error: " + e); } while (true) { try { sock = s.accept(); System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("connection from " + sock.getInetAddress() + ":"); System.out.print(sock.getPort() + "\n"); server = new ConsoleThread(conf, sock); server.start(); } catch (Exception e) { System.out.print("(" + new GregorianCalendar().getTime() + ") -> "); System.out.print("error: " + e); continue; } } }
/** * Subscribe - Private Interface * * <p>Patch provided by petereddy on GitHub * * @param String channel name. * @param Callback function callback. * @param String timetoken. */ private void _subscribe(String channel, Callback callback, String timetoken) { while (true) { try { // Build URL List<String> url = java.util.Arrays.asList("subscribe", this.SUBSCRIBE_KEY, channel, "0", timetoken); // Wait for Message JSONArray response = _request(url); JSONArray messages = response.optJSONArray(0); // Update TimeToken if (response.optString(1).length() > 0) timetoken = response.optString(1); // Run user Callback and Reconnect if user permits. If // there's a timeout then messages.length() == 0. for (int i = 0; messages.length() > i; i++) { JSONObject message = messages.optJSONObject(i); if (!callback.execute(message) || cancel) return; } } catch (Exception e) { try { Thread.sleep(1000); } catch (InterruptedException ie) { return; } } } }
/** This stops the layout if it's running, if it's not running it does nothing... */ public void stop() { if (runner.isAlive()) { try { active = false; if (idleing) { runner.interrupt(); } System.out.println( "Thread " + Thread.currentThread().getName() + " Ordering thread layout thread to stop."); runner.join(); initThread(); } catch (InterruptedException ex) { System.err.println("Layout Thread failed to stop"); Logger.getLogger(WeightedElasticLayout.class.getName()).log(Level.SEVERE, null, ex); } } }
/** This initializes the runner thread. */ private void initThread() { if (runner == null || !runner.isAlive()) { runner = new Thread(this, "WeightedElasticLayoutThread"); stable = false; idleing = false; active = false; } else { System.err.println("WeightedElasticLayoutThread Error: Trying to Re-initialize thread"); } }
/** Main threading method. Runs layout or sleeps. */ public void run() { System.out.println(Thread.currentThread().getName() + " layout starting up"); while (active) { if (stable) { // graph is stable, sleep and try again later. // System.out.println(Thread.currentThread().getName() + " done, sleeping."); try { idleing = true; Thread.sleep(THREAD_SLEEP_TIME); } catch (InterruptedException ex) { // just stop sleeping early... // System.out.println( Thread.currentThread().getName() + " waking up."); } idleing = false; } else { // System.out.println(Thread.currentThread().getName() + " doing layout..."); doLayout(); } } System.out.println(Thread.currentThread().getName() + "layout stopping."); }
/** Creates a thread and runs a test case */ public void runTest() { // anonymous inner class for thread target Thread myThread = new Thread( this.myGroup, new Runnable() { public void run() { while (!RunLoadTest.isOutOfTime()) { doTest(); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(e.getMessage()); } } System.out.println("Test " + myGroup + " Stopped! ==> " + reqCount + " Runs."); } }); myThread.start(); }
// MTProto public MTProto(int dc_id, MTProtoListener callback, int reuseFlag) { this.reuseFlag = reuseFlag; cb = callback; for (int i = 0; i < dcStates.size(); i++) if (dcStates.get(i).getInt("id") == dc_id) { dcState = dcStates.get(i); // Common.hexStringToByteArray("23D03699CE2AB29BA2273084D95DA126EC3A1D55BE4C317615CE66609D5562BDC0EFDE5AE1F9185001C35781F622B31DF5294685559340DE7D5CC8D7F6F86AE049107D8E498EB2AC3D6FA735DF90648EEC34A6B7BE3A5075A455F5696DB39280BF68C1637E1580E1EBA3F0C12EF2C03B8E9B5ECCFD3E4885BF636863388E3EC9E9EF60C722FF9B45CD93FA5E8D0D277B45A6A9370860582A159187F2F352D418D195D8E9310B5559E170F51CB2056F6CB6DB586E9349192A1B7EAA50887C115A14F996F5A855E90E47635A81EA3048615F4FD91347D73335E5503179857D0D29132483271B28E6591172C3D94686BD96E91FDB7AD9591A526218B3DDFC7A2A09") setAuthKey(dcState.getBytes("auth_key")); bind = dcState.getBool("bind"); seqno = dcState.getInt("seqno"); session = dcState.getLong("session"); server_salt = dcState.getLong("server_salt"); Common.logError("session: " + session + " seqno: " + seqno); connected = false; Thread netThread = new Thread(transport = new TransportTCP(this, true)); netThread.setPriority(Thread.MIN_PRIORITY); netThread.start(); return; } Common.logError("dc not found: " + dc_id); }
/** * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each * test results are documented and displayed in standard out with the following information: * * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The * start time of the last test run STOP - The stop time of the last test run THREAD - The thread * id handling this test case RESULT - The result of the test. Either the number of bytes returned * or an error message. */ private void doTest() { String result = ""; this.reqCount++; // Connect and run test steps Date startTime = new Date(); try { ClientResource client = new ClientResource(this.myURL); // place order JSONObject json = new JSONObject(); json.put("payment", "quarter"); json.put("action", "place-order"); client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON); // Get Gumball Count Representation result_string = client.get(); JSONObject json_count = new JSONObject(result_string.getText()); result = Integer.toString((int) json_count.get("count")); } catch (Exception e) { result = e.toString(); } finally { Date stopTime = new Date(); // Print Report of Result: System.out.println( "======================================\n" + "URL => " + this.myURL + "\n" + "REQ CNT => " + this.reqCount + "\n" + "START => " + startTime + "\n" + "STOP => " + stopTime + "\n" + "THREAD => " + Thread.currentThread().getName() + "\n" + "RESULT => " + result + "\n"); } }
/** * Returns true if the layout is running, false if it's stopped or paused or ... * * @return true if running false otherwise. */ public boolean isRunning() { return runner.isAlive(); }
/** * Helper for events. Signals the graph it needs to restart calculating forces as the model has * changed. Mark graph as 'dirty' If layout thread is sleeping, wake it up. */ private void markLayoutDirty() { stable = false; if (idleing) { runner.interrupt(); } }
/** * Layout core logic. * * <p>This iterates over all the nodes and determines their velocities based on a force directed * layout approach, performs collision detection/avoidance and then ultimately their new positions * as they move. */ private void doLayout() { double maxVelocity = 100; double numOfIterations = 0; double step = 100; double skip = step; int counter = 1; boolean dividerChanged = false; // active = true; while (maxVelocity > 1 && active && (numOfIterations < MAX_NUM_OF_ITERATIONS)) { counter++; maxVelocity = 0; numOfIterations++; Iterator<Node> outer = controller.getNodeIterator(); startTime = System.currentTimeMillis(); double systemMovement = 0; double kineticEnergy = 0; /* Iterate over all nodes and calculate velocity */ while (outer.hasNext()) { Node current = outer.next(); current.resetVelocity(); current.resetAcceleration(); /* * If current node is not pinned or selected, * perform force directed layout calculations here. */ if (!((current == controller.getGraphSelected()) || current.isPinned())) { calculateNodeAttractiveForce(current); calculateNodeRepulsiveForces(current); // applyNodeFriction(current); // if (IS_COOLING) { // calculateNodeCooling(current, numOfIterations); // } // calculate velocities current.setVX(current.getVX() + current.accelx * TIMESTEP * DAMPING); current.setVY(current.getVY() + current.accely * TIMESTEP * DAMPING); double speedSquared = current.getVX() * current.getVX() + current.getVY() * current.getVY(); kineticEnergy += 0.5 * current.weight * speedSquared; // cap the velocity if (current.getVX() >= 0) { current.setVX(Math.min(current.getVX(), MAX_DIST_PER_MOVE)); } else { current.setVX(Math.max(current.getVX(), -MAX_DIST_PER_MOVE)); } if (current.getVY() >= 0) { current.setVY(Math.min(current.getVY(), MAX_DIST_PER_MOVE)); } else { current.setVY(Math.max(current.getVY(), -MAX_DIST_PER_MOVE)); } // System.out.println("vy "+ current.getVY() + ", vx " + current.getVX()); } } /* Iterate over all nodes move them after all the velocities are set */ outer = controller.getNodeIterator(); while (outer.hasNext()) { Node current = outer.next(); int xStart = current.getX(); int yStart = current.getY(); /* update node position */ int xEnd = current.getX() + (int) current.getVX(); int yEnd = current.getY() + (int) current.getVY(); int dX = Math.abs(xStart - xEnd); int dY = Math.abs(yStart - yEnd); // systemMovement += dX; // systemMovement += dY; // if(dX + dY > 6) { controller.moveNode(current, xEnd, yEnd); // } // controller.moveNode(current, Math.min(current.getX() + (int) // current.getVX(),MAX_DIST_PER_MOVE), Math.min(current.getY() + (int) current.getVY(), // MAX_DIST_PER_MOVE)); /* compute maxVelocity for layout iteration */ maxVelocity = Math.max( maxVelocity, Math.sqrt(Math.pow(current.getVX(), 2) + Math.pow(current.getVY(), 2))); } if (kineticEnergy < ENERGY_THRESHOLD) { numOfIterations = MAX_NUM_OF_ITERATIONS; } /* Make animation slower */ try { Thread.sleep(sleepInterval); } catch (InterruptedException ex) { } /* Calculate how long the iteration took */ stopTime = System.currentTimeMillis(); long duration = stopTime - startTime; if ((duration > MAX_ITERATION_TIME) && (sleepInterval > 5)) { sleepInterval -= 5; } else if (duration < MIN_ITERATION_TIME) { sleepInterval += 5; } if (numOfIterations > skip) { skip += step; System.out.print('.'); } } /* We've reached a stable layout, hold on for now */ stable = true; // System.out.println("ran in " + numOfIterations + " iterations."); }