public void getSavedLocations() { // System.out.println("inside getSavedLocations"); //CONSOLE * * * * * * * * * * * * * loc.clear(); // clear locations. helps refresh the list when reprinting all the locations BufferedWriter f = null; // just in case file has not been created yet BufferedReader br = null; try { // attempt to open the locations file if it doesn't exist, create it f = new BufferedWriter( new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist br = new BufferedReader(new FileReader("savedLocations.txt")); String line; // each line is one index of the list loc.add("Saved Locations"); // loop and read a line from the file as long as we don't get null while ((line = br.readLine()) != null) // add the read word to the wordList loc.add(line); } catch (IOException e) { e.printStackTrace(); } finally { try { // attempt the close the file br.close(); // close bufferedwriter } catch (IOException ex) { ex.printStackTrace(); } } }
/** * Removes receiver and sender feedback from RTCP packets. * * @param inPacket the <tt>RTCPCompoundPacket</tt> to filter. * @return the filtered <tt>RawPacket</tt>. */ public RawPacket gateway(RTCPCompoundPacket inPacket) { if (inPacket == null || inPacket.packets == null || inPacket.packets.length == 0) { logger.info("Ignoring empty RTCP packet."); return null; } ArrayList<RTCPPacket> outPackets = new ArrayList<RTCPPacket>(inPacket.packets.length); for (RTCPPacket p : inPacket.packets) { switch (p.type) { case RTCPPacket.RR: case RTCPPacket.SR: case RTCPPacket.SDES: // We generate our own RR/SR/SDES packets. We only want // to forward NACKs/PLIs/etc. break; case RTCPFBPacket.PSFB: RTCPFBPacket psfb = (RTCPFBPacket) p; switch (psfb.fmt) { case RTCPREMBPacket.FMT: // We generate its own REMB packets. break; default: // We let through everything else, like NACK // packets. outPackets.add(psfb); break; } break; default: // We let through everything else, like BYE and APP // packets. outPackets.add(p); break; } } if (outPackets.size() == 0) { return null; } // We have feedback messages to send. Pack them in a compound // RR and send them. TODO Use RFC5506 Reduced-Size RTCP, if the // receiver supports it. Collection<RTCPRRPacket> rrPackets = makeRTCPRRPackets(System.currentTimeMillis()); if (rrPackets != null && rrPackets.size() != 0) { outPackets.addAll(0, rrPackets); } else { logger.warn("We might be sending invalid RTCPs."); } RTCPPacket[] pkts = outPackets.toArray(new RTCPPacket[outPackets.size()]); RTCPCompoundPacket outPacket = new RTCPCompoundPacket(pkts); return generator.apply(outPacket); }
@Test public void fromIterable() { ArrayList<String> items = new ArrayList<>(); items.add("one"); items.add("two"); items.add("three"); assertEquals((Long) 3L, Observable.fromIterable(items).count().toBlocking().single()); assertEquals("two", Observable.fromIterable(items).skip(1).take(1).toBlocking().single()); assertEquals("three", Observable.fromIterable(items).takeLast(1).toBlocking().single()); }
private List<QName> toPids(Collection<QName> processTypes, long version) { ArrayList<QName> result = new ArrayList<QName>(); for (QName pqName : processTypes) { result.add(toPid(pqName, version)); } return result; }
private ComponentItemImpl loadComponent(ComponentItemConfig config) throws ComponentCreationException { final ComponentItemImpl component = ComponentItemImpl.newInstance(this, config); try { component.setBehavior( componentRegistry.loadBehavior(config.getType(), component.getContext())); componentList.addItem( component, new Runnable() { @Override public void run() { component.addEventListener(BaseEvent.class, componentListener); if (counterSupport instanceof AggregatedCounterSupport) ((AggregatedCounterSupport) counterSupport).addChild(component); } }); } catch (ComponentCreationException e) { log.error("Unable to load component: " + component, e); badComponents.add(config); component.release(); throw e; } return component; }
/** * Load a deployment unit record stored in the db into memory. * * @param dudao */ protected List<ProcessConfImpl> load(DeploymentUnitDAO dudao) { __log.debug("Loading deployment unit record from db: " + dudao.getName()); File dudir = findDeployDir(dudao); if (dudir == null || !dudir.exists()) throw new ContextException( "Deployed directory " + (dudir == null ? "(unknown)" : dudir) + " no longer there!"); DeploymentUnitDir dud = new DeploymentUnitDir(dudir); // set the name with the one from database dud.setName(dudao.getName()); dud.scan(); ArrayList<ProcessConfImpl> loaded = new ArrayList<ProcessConfImpl>(); _rw.writeLock().lock(); try { _deploymentUnits.put(dud.getName(), dud); long version = 0; for (ProcessConfDAO p : dudao.getProcesses()) { TDeployment.Process pinfo = dud.getProcessDeployInfo(p.getType()); if (pinfo == null) { __log.warn("Cannot load " + p.getPID() + "; cannot find descriptor."); continue; } Map<QName, Node> props = calcInitialProperties(dud.getProperties(), pinfo); // TODO: update the props based on the values in the DB. ProcessConfImpl pconf = new ProcessConfImpl( p.getPID(), p.getType(), p.getVersion(), dud, pinfo, dudao.getDeployDate(), props, p.getState(), eprContext, _configDir, generateProcessEventsAll); version = p.getVersion(); _processes.put(pconf.getProcessId(), pconf); loaded.add(pconf); } // All processes and the DU have the same version dud.setVersion(version); } finally { _rw.writeLock().unlock(); } return loaded; }
private static void readCaptchaFile(String fileName) { try { BufferedReader reader = new BufferedReader(new FileReader(new File(fileName))); String line; while ((line = reader.readLine()) != null) captchaList.add(line); reader.close(); } catch (Exception exception) { throw new RuntimeException(exception); } }
void turnOnFadeLog() throws IOException { Global.log("Connecting to fade log..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.fadeLogPort() + "..."); try { fadeLog = new ClientByteStream(ip, Global.fadeLogPort(), 12); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { String s = null; byte[] data = null; try { data = fadeLog.read(); if (data == null) return; s = fadeLog.readLine(); } catch (IOException ex) { System.err.println("Error reading from fade log: " + ex); Global.onException(); stop(); return; } if (s == null) return; ByteBuffer bb = ByteBuffer.wrap(data); float x = bb.getFloat(); float y = bb.getFloat(); Color color = Global.IntToColor(bb.getInt()); // if fade color is same as ship color, play power-up sound if (color.equals(getPlayerShip().fill)) Sounds.powerUp.play(); fadeLog(s, x, y, color); } })); }
void turnOnBulletReceiver() throws IOException { Global.log("Turning on bullet receiver..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + (Global.bulletPort()) + "..."); try { bulletStream = new ClientByteStream(ip, Global.bulletPort(), Bullet.bufferSize()); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return true; } public float FPS() { return Global.ReceiveFPS * 20; } public void run() { byte[] data = null; try { data = bulletStream.read(); } catch (IOException ex) { System.err.println("Bullet receiver error: " + ex); Global.onException(); stop(); return; } if (data == null) return; Bullet toSpawn = Bullet.fromBytes(data); Ship find = cShip.get(toSpawn.getFill()); if (find == null) { for (Ship s : turrets) { if (s.fill.equals(toSpawn.getFill())) { find = s; break; } } } if (find == null) return; find.getBulletSet().add(toSpawn); } })); }
/*public int numTickGroups() { return ticks.size(); }*/ public String[][] threadInfo() { ArrayList<String[]> V = new ArrayList(); for (Iterator<CMLibrary> e = CMLib.libraries(); e.hasNext(); ) { CMLibrary lib = e.next(); SupportThread thread = lib.getSupportThread(); if (thread != null) { String[] S = new String[3]; S[0] = thread.getName(); S[1] = CMLib.english().returnTime(thread.milliTotal, thread.tickTotal); S[2] = thread.status; V.add(S); } } return V.toArray(new String[V.size()][]); }
private void createConnections() { for (ConnectionConfig connectionConfig : getConfig().getConnectionList()) { try { Connection connection = new ConnectionImpl(connectionConfig); connection .getOutputTerminal() .addEventListener(TerminalConnectionEvent.class, connectionListener); connectionList.addItem(connection); } catch (Exception e) { badConnections.add(connectionConfig); log.error( "Unable to create connection between terminals " + connectionConfig.getInputTerminalId() + " and " + connectionConfig.getOutputTerminalId(), e); } } }
void turnOnTurretReceiver() throws IOException { Global.log("Turning on turret receiver..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.turretPort() + "..."); try { turretStream = new ClientByteStream(ip, Global.turretPort(), Ship.bufferSize()); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; String name = null; try { data = turretStream.read(); name = turretStream.readLine(); } catch (IOException ex) { System.err.println("Cannot read info from turret stream"); Global.onException(); stop(); return; } if (data == null) return; Ship s = new Ship(name, Global.transparent); s.setDesign(new Design.Turret(s)); s.fromBytes(data, false); addShip(s); } })); }
/* * public synchronized ArrayList<Request> getWorkloadsList() { * ArrayList<Request> workloads = new ArrayList<Request>(); * * LOG.debug("Reading " + parentZnode + * Constants.DEFAULT_ZOOKEEPER_ZNODE_WORKLOADS); * * try { List<String> children = getChildren(parentZnode + * Constants.DEFAULT_ZOOKEEPER_ZNODE_WORKLOADS, null); * * if (!children.isEmpty()) { for (String child : children) { Request * request = new Request(); String workloadZnode = parentZnode + * Constants.DEFAULT_ZOOKEEPER_ZNODE_WORKLOADS + "/" + child; Stat stat = * zkc.exists(workloadZnode, false); if (stat != null) { byte[] bytes = * zkc.getData(workloadZnode, false, stat); try { * deserializer.deserialize(request, bytes); workloads.add(request); } catch * (TException e) { e.printStackTrace(); } } } } } catch (Exception e) { * e.printStackTrace(); } * * return workloads; } */ public synchronized ArrayList<String> getClientsList() { ArrayList<String> clients = new ArrayList<String>(); LOG.debug("Reading " + parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_CLIENTS); try { List<String> children = getChildren(parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_CLIENTS, null); if (!children.isEmpty()) { for (String child : children) { clients.add(child); } } } catch (Exception e) { e.printStackTrace(); } return clients; }
private synchronized void getZkRunning() throws Exception { LOG.debug("Reading " + parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING); List<String> children = getChildren( parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING, new RunningWatcher()); if (!children.isEmpty()) { for (String child : children) { // If stop-wms.sh is executed and WMS_MANAGES_ZK then zookeeper // is stopped abruptly. // Second scenario is when ZooKeeper fails for some reason // regardless of whether WMS // manages it. When either happens the WmsServer running znodes // still exist in ZooKeeper // and we see them at next startup. When they eventually timeout // we get node deleted events for a server that no longer // exists. So, only recognize // WmsServer running znodes that have timestamps after last // WmsMaster startup. Scanner scn = new Scanner(child); scn.useDelimiter(":"); String hostName = scn.next(); String instance = scn.next(); int infoPort = Integer.parseInt(scn.next()); long serverStartTimestamp = Long.parseLong(scn.next()); scn.close(); if (serverStartTimestamp < startupTimestamp) continue; if (!runningServers.contains(child)) { LOG.debug("Watching running [" + child + "]"); zkc.exists( parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING + "/" + child, new RunningWatcher()); runningServers.add(child); } } metrics.setTotalRunning(runningServers.size()); } else { metrics.setTotalRunning(0); } }
@Test public void testOfTypeWithPolymorphism() { ArrayList<Integer> l1 = new ArrayList<>(); l1.add(1); LinkedList<Integer> l2 = new LinkedList<>(); l2.add(2); @SuppressWarnings("rawtypes") Observable<List> observable = Observable.<Object>just(l1, l2, "123").ofType(List.class); Subscriber<Object> observer = TestHelper.mockSubscriber(); observable.subscribe(observer); verify(observer, times(1)).onNext(l1); verify(observer, times(1)).onNext(l2); verify(observer, never()).onNext("123"); verify(observer, never()).onError(org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onComplete(); }
private void getServersFile() throws Exception { InputStream is = this.getClass().getResourceAsStream("/servers"); if (is == null) throw new IOException("Cannot find servers file"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); configuredServers.clear(); String line; while ((line = br.readLine()) != null) { configuredServers.add(line); } Collections.sort(configuredServers); if (configuredServers.size() < 1) throw new IOException("No entries found in servers file"); int lnum = 1; for (int i = 0; i < configuredServers.size(); i++) { LOG.debug("servers file line " + lnum + " [" + configuredServers.get(i) + "]"); lnum++; } }
void turnOnServerTime() throws IOException { Global.log("Turning on server time..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.serverTimePort() + "..."); try { serverTime = new ClientByteStream(ip, Global.serverTimePort(), 2); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; try { data = serverTime.read(); } catch (IOException ex) { System.err.println("Error reading from server time: " + ex); Global.onException(); stop(); return; } if (data == null) return; ByteBuffer bb = ByteBuffer.wrap(data); short time = bb.getShort(); Game.activeGame().getHud().setTime(time); } })); }
void turnOnChatLog() throws IOException { Global.log("Connecting to chat log..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.chatLogPort() + "..."); try { chatLog = new ClientByteStream(ip, Global.chatLogPort(), 1); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { String s = null; try { s = chatLog.readLine(); } catch (IOException ex) { System.err.println("Error reading from chat log: " + ex); Global.onException(); stop(); return; } if (s == null) return; log(s); } })); }
String[] getPluginDirectories() { ArrayList<String> directories = new ArrayList<String>(); PackageManager pm = this.mAppContext.getPackageManager(); List<ResolveInfo> plugins = pm.queryIntentServices( new Intent(PLUGIN_ACTION), PackageManager.GET_SERVICES | PackageManager.GET_META_DATA); synchronized (mPackageInfoCache) { // clear the list of existing packageInfo objects mPackageInfoCache.clear(); for (ResolveInfo info : plugins) { // retrieve the plugin's service information ServiceInfo serviceInfo = info.serviceInfo; if (serviceInfo == null) { Log.w(LOGTAG, "Ignore bad plugin"); continue; } Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName); // retrieve information from the plugin's manifest PackageInfo pkgInfo; try { pkgInfo = pm.getPackageInfo( serviceInfo.packageName, PackageManager.GET_PERMISSIONS | PackageManager.GET_SIGNATURES); } catch (Exception e) { Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName); continue; } if (pkgInfo == null) { Log.w( LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Could not load package information."); continue; } /* * find the location of the plugin's shared library. The default * is to assume the app is either a user installed app or an * updated system app. In both of these cases the library is * stored in the app's data directory. */ String directory = pkgInfo.applicationInfo.dataDir + "/lib"; final int appFlags = pkgInfo.applicationInfo.flags; final int updatedSystemFlags = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; // preloaded system app with no user updates if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) { directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName; } // check if the plugin has the required permissions String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { Log.w( LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission."); continue; } boolean permissionOk = false; for (String permit : permissions) { if (PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (!permissionOk) { Log.w( LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission (2)."); continue; } // check to ensure the plugin is properly signed Signature signatures[] = pkgInfo.signatures; if (signatures == null) { Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Not signed."); continue; } // determine the type of plugin from the manifest if (serviceInfo.metaData == null) { Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no type defined"); continue; } String pluginType = serviceInfo.metaData.getString(PLUGIN_TYPE); if (!TYPE_NATIVE.equals(pluginType)) { Log.e(LOGTAG, "Unrecognized plugin type: " + pluginType); continue; } try { Class<?> cls = getPluginClass(serviceInfo.packageName, serviceInfo.name); // TODO implement any requirements of the plugin class here! boolean classFound = true; if (!classFound) { Log.e( LOGTAG, "The plugin's class' " + serviceInfo.name + "' does not extend the appropriate class."); continue; } } catch (NameNotFoundException e) { Log.e(LOGTAG, "Can't find plugin: " + serviceInfo.packageName); continue; } catch (ClassNotFoundException e) { Log.e(LOGTAG, "Can't find plugin's class: " + serviceInfo.name); continue; } // if all checks have passed then make the plugin available mPackageInfoCache.add(pkgInfo); directories.add(directory); } } return directories.toArray(new String[directories.size()]); }
public static void main(String[] args) throws Throwable { final int itrs = Integer.getInteger("iterations", 100000); // final int itrs = Integer.getInteger("iterations", 12); final int size = Integer.getInteger("size", 2048); final int subsize = Integer.getInteger("subsize", 128); final int maxchar = Integer.getInteger("maxchar", 128); final String regex = System.getProperty("filter"); final Pattern filter = (regex == null) ? null : Pattern.compile(regex); final boolean useSecurityManager = Boolean.getBoolean("SecurityManager"); if (useSecurityManager) System.setSecurityManager(new PermissiveSecurityManger()); final Random rnd = new Random(); String[] csns = new String[] { "Big5", "Johab", "EUC_CN", "EUC_KR", "MS932", "MS936", "MS949", "MS950", "GBK", "Big5_HKSCS", "Big5_HKSCS_2001", "Big5_Solaris", "MS950_HKSCS", "MS950_HKSCS_XP", "IBM1364", "IBM1381", "IBM1383", "IBM930", "IBM933", "IBM935", "IBM937", "IBM939", "IBM942", "IBM943", "IBM948", "IBM949", "IBM950", "IBM970", }; ArrayList<long[]> sum = new ArrayList<>(); for (final String csn : csns) { final Charset cs = Charset.forName(csn); List<Integer> cps = new ArrayList<>(0x4000); int off = 0; int cp = 0; int n = 0; CharsetEncoder enc = cs.newEncoder(); while (cp < 0x10000 && n < cps.size()) { if (enc.canEncode((char) cp)) { cps.add(cp); n++; } cp++; } Collections.shuffle(cps); char[] ca = new char[cps.size()]; for (int i = 0; i < cps.size(); i++) ca[i] = (char) (int) cps.get(i); System.out.printf("%n--------%s---------%n", csn); for (int sz = 8; sz <= 2048; sz *= 2) { System.out.printf(" [len=%d]%n", sz); final char[] chars = Arrays.copyOf(ca, sz); final String str = new String(chars); final byte[] bs = str.getBytes(cs); Job[] jobs = { new Job("String decode: csn") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) new String(bs, csn); } }, new Job("String decode: cs") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) new String(bs, cs); } }, new Job("String encode: csn") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) str.getBytes(csn); } }, new Job("String encode: cs") { public void work() throws Throwable { for (int i = 0; i < itrs; i++) str.getBytes(cs); } }, }; sum.add(time(jobs)); } } }
public void deinit(Appendable out, boolean force) throws Exception { Settings settings = new Settings(platform.getConfigFile()); if (!force) { Justif justify = new Justif(80, 40); StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); try { String list = listFiles(platform.getGlobal()); if (list != null) { f.format("In global default environment:%n"); f.format(list); } list = listFiles(platform.getLocal()); if (list != null) { f.format("In local default environment:%n"); f.format(list); } if (settings.containsKey(JPM_CACHE_GLOBAL)) { list = listFiles(IO.getFile(settings.get(JPM_CACHE_GLOBAL))); if (list != null) { f.format("In global configured environment:%n"); f.format(list); } } if (settings.containsKey(JPM_CACHE_LOCAL)) { list = listFiles(IO.getFile(settings.get(JPM_CACHE_LOCAL))); if (list != null) { f.format("In local configured environment:%n"); f.format(list); } } list = listSupportFiles(); if (list != null) { f.format("jpm support files:%n"); f.format(list); } f.format("%n%n"); f.format( "All files listed above will be deleted if deinit is run with the force flag set" + " (\"jpm deinit -f\" or \"jpm deinit --force\"%n%n"); f.flush(); justify.wrap(sb); out.append(sb.toString()); } finally { f.close(); } } else { // i.e. if(force) int count = 0; File[] caches = {platform.getGlobal(), platform.getLocal(), null, null}; if (settings.containsKey(JPM_CACHE_LOCAL)) { caches[2] = IO.getFile(settings.get(JPM_CACHE_LOCAL)); } if (settings.containsKey(JPM_CACHE_GLOBAL)) { caches[3] = IO.getFile(settings.get(JPM_CACHE_GLOBAL)); } ArrayList<File> toDelete = new ArrayList<File>(); for (File cache : caches) { if (cache == null || !cache.exists()) { continue; } listFiles(cache, toDelete); if (toDelete.size() > count) { count = toDelete.size(); if (!cache.canWrite()) { reporter.error(PERMISSION_ERROR + " (" + cache + ")"); return; } toDelete.add(cache); } } listSupportFiles(toDelete); for (File f : toDelete) { if (f.exists() && !f.canWrite()) { reporter.error(PERMISSION_ERROR + " (" + f + ")"); } } if (reporter.getErrors().size() > 0) { return; } for (File f : toDelete) { if (f.exists()) { IO.deleteWithException(f); } } } }
void turnOnPowerReceiver() throws IOException { Global.log("Turning on power receiver..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + (Global.powerPort()) + "..."); try { powerStream = new ClientByteStream(ip, Global.powerPort(), Power.bufferSize()); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; try { data = powerStream.read(); } catch (IOException ex) { Global.onException(); stop(); return; } if (data == null) return; addPower(Power.fromBytes(data)); } })); Global.log("Turning on power remover..."); while (true) { if (isDisposed()) throw new IOException("Client game disposed"); Global.log("Connecting to port " + Global.powerRemoverPort() + "..."); try { powerRemover = new ClientByteStream(ip, Global.powerRemoverPort(), 2); break; } catch (IOException ex) { } } Global.log("Connected!"); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return false; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; try { data = powerRemover.read(); } catch (IOException ex) { System.err.println("Cannot read info from power remover"); Global.onException(); stop(); return; } if (data == null) return; ByteBuffer bb = ByteBuffer.wrap(data); short id = bb.getShort(); for (Power power : powers) { if (power.ID == id) { removePower(power); break; } } } })); }
/** Deploys a process. */ public Collection<QName> deploy( final File deploymentUnitDirectory, boolean activate, String duName, boolean autoincrementVersion) { __log.info(__msgs.msgDeployStarting(deploymentUnitDirectory)); final Date deployDate = new Date(); // Create the DU and compile/scan it before acquiring lock. final DeploymentUnitDir du = new DeploymentUnitDir(deploymentUnitDirectory); if (duName != null) { // Override the package name if given from the parameter du.setName(duName); } long version; if (autoincrementVersion || du.getStaticVersion() == -1) { // Process and DU use a monotonically increased single version number by default. try { version = getCurrentVersion(); } finally { // we need to reset the current version thread local value. _currentVersion.set(null); } } else { version = du.getStaticVersion(); } du.setVersion(version); try { du.compile(); } catch (CompilationException ce) { String errmsg = __msgs.msgDeployFailCompileErrors(ce); __log.error(errmsg, ce); throw new ContextException(errmsg, ce); } du.scan(); final DeployDocument dd = du.getDeploymentDescriptor(); final ArrayList<ProcessConfImpl> processes = new ArrayList<ProcessConfImpl>(); Collection<QName> deployed; _rw.writeLock().lock(); try { if (_deploymentUnits.containsKey(du.getName())) { String errmsg = __msgs.msgDeployFailDuplicateDU(du.getName()); __log.error(errmsg); throw new ContextException(errmsg); } retirePreviousPackageVersions(du); for (TDeployment.Process processDD : dd.getDeploy().getProcessArray()) { QName pid = toPid(processDD.getName(), version); if (_processes.containsKey(pid)) { String errmsg = __msgs.msgDeployFailDuplicatePID(processDD.getName(), du.getName()); __log.error(errmsg); throw new ContextException(errmsg); } QName type = processDD.getType() != null ? processDD.getType() : processDD.getName(); CBPInfo cbpInfo = du.getCBPInfo(type); if (cbpInfo == null) { String errmsg = __msgs.msgDeployFailedProcessNotFound(processDD.getName(), du.getName()); __log.error(errmsg); throw new ContextException(errmsg); } ProcessConfImpl pconf = new ProcessConfImpl( pid, processDD.getName(), version, du, processDD, deployDate, calcInitialProperties(du.getProperties(), processDD), calcInitialState(processDD), eprContext, _configDir, generateProcessEventsAll); processes.add(pconf); } _deploymentUnits.put(du.getName(), du); for (ProcessConfImpl process : processes) { __log.info(__msgs.msgProcessDeployed(du.getDeployDir(), process.getProcessId())); _processes.put(process.getProcessId(), process); } } finally { _rw.writeLock().unlock(); } // Do the deployment in the DB. We need this so that we remember deployments across system // shutdowns. // We don't fail if there is a DB error, simply print some errors. deployed = exec( new Callable<Collection<QName>>() { public Collection<QName> call(ConfStoreConnection conn) { // Check that this deployment unit is not deployed. DeploymentUnitDAO dudao = conn.getDeploymentUnit(du.getName()); if (dudao != null) { String errmsg = "Database out of synch for DU " + du.getName(); __log.warn(errmsg); dudao.delete(); } dudao = conn.createDeploymentUnit(du.getName()); try { dudao.setDeploymentUnitDir(deploymentUnitDirectory.getCanonicalPath()); } catch (IOException e1) { String errmsg = "Error getting canonical path for " + du.getName() + "; deployment unit will not be available after restart!"; __log.error(errmsg); } ArrayList<QName> deployed = new ArrayList<QName>(); // Going trough each process declared in the dd for (ProcessConfImpl pc : processes) { try { ProcessConfDAO newDao = dudao.createProcess(pc.getProcessId(), pc.getType(), pc.getVersion()); newDao.setState(pc.getState()); for (Map.Entry<QName, Node> prop : pc.getProcessProperties().entrySet()) { newDao.setProperty(prop.getKey(), DOMUtils.domToString(prop.getValue())); } deployed.add(pc.getProcessId()); } catch (Throwable e) { String errmsg = "Error persisting deployment record for " + pc.getProcessId() + "; process will not be available after restart!"; __log.error(errmsg, e); } } return deployed; } }); _rw.readLock().lock(); boolean readLockHeld = true; try { for (ProcessConfImpl process : processes) { fireEvent( new ProcessStoreEvent( ProcessStoreEvent.Type.DEPLOYED, process.getProcessId(), process.getDeploymentUnit().getName())); fireStateChange( process.getProcessId(), process.getState(), process.getDeploymentUnit().getName()); } } catch (Exception e) { // need to unlock as undeploy operation will need a writeLock _rw.readLock().unlock(); readLockHeld = false; // A problem at that point means that engine deployment failed, we don't want the store to // keep the du __log.warn("Deployment failed within the engine, store undeploying process.", e); undeploy(deploymentUnitDirectory); if (e instanceof ContextException) throw (ContextException) e; else throw new ContextException("Deployment failed within the engine. " + e.getMessage(), e); } finally { if (readLockHeld) _rw.readLock().unlock(); } return deployed; }
void createShips() { Global.log("Creating ships..."); int n = numPlayers(); for (int i = 0; i < n; ++i) { Global.log("Creating ship for Player " + (i + 1) + " [" + playerNames[i] + "]..."); final int I = i; if (i == playerID) { final PlayerShip ship = new PlayerShip(name, nextColor(), this, new Controls()); ship.getControls().enabled = false; timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return true; } public float FPS() { return Global.SendFPS; } public void run() { try { sendMessage(ship.getControlBytes()); } catch (IOException ex) { System.err.println( "An exception occured via the ship of Player " + (I + 1) + " [" + playerNames[I] + "]: " + ex.toString()); Global.onException(); stop(); } } })); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return true; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; try { data = playerByteStreams[I].read(); } catch (IOException ex) { System.err.println("Error reading ship from server: " + ex); Global.onException(); stop(); return; } if (data == null) return; ship.fromBytes(data); } })); addShip(ship); } else { final Ship ship = new Ship(playerNames[i], nextColor()); timers.add( new FixedTimer( new FixedTask() { public boolean fixedRate() { return true; } public float FPS() { return Global.ReceiveFPS; } public void run() { byte[] data = null; try { data = playerByteStreams[I].read(); } catch (IOException ex) { System.err.println("Error reading ship from server: " + ex); Global.onException(); stop(); return; } if (data == null) return; ship.fromBytes(data); } })); addShip(ship); } Global.log("Done!"); } Global.log("Done creating ships!"); }