public static void runCowboy(RobotController rc, int assignment) throws GameActionException { if (assignment == 0) assignment = rc.readBroadcast(rc.getRobot().getID()); int squad = Channels.assignmentDecoding(assignment)[0]; int role = Channels.assignmentDecoding(assignment)[1]; if (rc.readBroadcast(squad) == 0) { System.out.println( "My time has elapsed. I must die in battle with honor for my squad " + squad + "!"); kamikaze(rc); } // checkIfBackupNeeded(rc); switch (role) { case 0: COWBOY.runDefender(rc, squad); break; case 1: COWBOY.runAttacker(rc, squad); break; case 2: COWBOY.runScout(rc, squad); break; } rc.yield(); }
public Main(Options options) throws MalformedURLException { Fibers fibers = new Fibers(); Channels channels = new Channels(); Fiber core = fibers.core(); new Connector( channels.added(), channels.removed(), core, new VirtualMachineFactory( new AgentHolder(), new MainClassOrJarFile(), new GroovyScriptMonitorFactories(options.monitorScriptsSource.toURI().toURL()), channels.samples(), fibers.sampler())) .start(); new VirtualMachineLogger(core, channels.added(), channels.removed()); channels.samples().subscribe(fibers.emitter(), new CollectdEmitter()); core.scheduleWithFixedDelay( new Scanner(channels.added(), channels.removed()), 0, options.virtualMachineScanInterval, TimeUnit.SECONDS); }
static void runDefender(RobotController rc, int squad) throws GameActionException { Team team = rc.getTeam(); Team enemy = team.opponent(); int squadInfo = rc.readBroadcast(squad); MapLocation target = Conversion.intToMapLocation(squadInfo); MapLocation curr = rc.getLocation(); int status = rc.readBroadcast(squad + 1); int PASTRstatus = Channels.NTPASTRDecoding(status)[1]; int NTstatus = Channels.NTPASTRDecoding(status)[0]; Robot[] allies = rc.senseNearbyGameObjects(Robot.class, rc.getType().attackRadiusMaxSquared * 2, team); // Create a PASTR/NT if not already there // System.out.println(allies.length + " " + rc.readBroadcast(Channels.numAlliesNeededChannel)); if (allies.length >= rc.readBroadcast(Channels.numAlliesNeededChannel) && curr.distanceSquaredTo(target) < distanceThreshold && rc.isActive()) { if (PASTRstatus == 0) { rc.construct(RobotType.PASTR); rc.broadcast(squad + 1, Channels.NTPASTREncoding(NTstatus, 1)); System.out.println("Constructing a PASTR..."); } else if (NTstatus == 0) { rc.construct(RobotType.NOISETOWER); rc.broadcast(squad + 1, Channels.NTPASTREncoding(1, PASTRstatus)); System.out.println("Constructing a NT..."); } } // Then go to right place if (curr.distanceSquaredTo(target) > 8) Move.moveTo(rc, target); // Then attack! Robot[] enemyRobots = rc.senseNearbyGameObjects(Robot.class, rc.getType().sensorRadiusSquared * 2, enemy); MapLocation eloc = Attack.nearestEnemyLoc(rc, enemyRobots, rc.getLocation()); if (eloc != null) { if (rc.isActive()) Move.moveToward(rc, eloc); if (rc.isActive() && rc.canAttackSquare(eloc)) rc.attackSquare(eloc); } // If there is a pastr and noisetower, don't block them! if (PASTRstatus == 1 && NTstatus == 1) { if (enemyRobots.length == 0 && rc.senseCowsAtLocation(rc.getLocation()) > 30) { Move.tryToSneak(rc); } } }
static void runScout(RobotController rc, int squad) throws GameActionException { int squadInfo = rc.readBroadcast(squad); MapLocation target = Conversion.intToMapLocation(Channels.scoutDecoding(squadInfo)[1]); MapLocation curr = rc.getLocation(); if (curr.distanceSquaredTo(target) > 50) Move.moveTo(rc, target); else { int start = Channels.scoutDecoding(squadInfo)[0]; rc.broadcast( Channels.scoutChannel, Channels.scoutEncoding((Clock.getRoundNum() - start), target, 1)); } }
public static String postPage( URLConnection connection, String query, String cookie, HashMap<String, String> hdr) { URL url = connection.getURL(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setDefaultUseCaches(false); // connection.setAllowUserInteraction(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("User-Agent", defAgentString); connection.setRequestProperty("Content-Length", "" + query.length()); try { String c1 = ChannelCookie.getCookie(url.toString()); if (!empty(c1)) { if (!cookieContains(c1, cookie)) cookie = append(cookie, "; ", c1); } if (!empty(cookie)) connection.setRequestProperty("Cookie", cookie); if (hdr != null && hdr.size() != 0) { for (String key : hdr.keySet()) connection.setRequestProperty(key, hdr.get(key)); } connection.setConnectTimeout(10000); connection.connect(); // open up the output stream of the connection if (!empty(query)) { DataOutputStream output = new DataOutputStream(connection.getOutputStream()); output.writeBytes(query); output.flush(); output.close(); } BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder page = new StringBuilder(); String str; while ((str = in.readLine()) != null) { // page.append("\n"); page.append(str.trim()); page.append("\n"); } in.close(); Channels.restoreProxyDNS(); return page.toString(); } catch (Exception e) { Channels.debug("post error " + e); Channels.restoreProxyDNS(); return ""; } }
// TODO: fix. Returning Object[] is not the right design public Object[] getWaveServerRaw( final String s, final String c, final String n, final String l, final double t1, final double t2) { String lc = ""; if (l != null && !l.equals("--")) { lc = "$" + l; } final String code = s + "$" + c + "$" + n + lc; if (!winston.checkConnect() || !winston.useDatabase(code)) { return null; } List<byte[]> bufs = null; try { bufs = data.getTraceBufBytes(code, t1, t2, 0); } catch (final UtilException e) { } if (bufs == null || bufs.size() == 0) { return null; } try { final int sid = channels.getChannelID(code); final TraceBuf tb0 = new TraceBuf(bufs.get(0)); final TraceBuf tbN = new TraceBuf(bufs.get(bufs.size() - 1)); int total = 0; for (final byte[] buf : bufs) { total += buf.length; } String lr = ""; if (l != null) { lr = " " + l; } final String hdr = sid + " " + s + " " + c + " " + n + lr + " F " + tb0.dataType() + " " + tb0.getStartTime() + " " + tbN.getEndTime() + " " + total; return new Object[] {hdr, new Integer(total), bufs}; } catch (final Exception e) { LOGGER.error("Could not get raw wave.", e.getLocalizedMessage()); } return null; }
public static String parseASX(String url, int type) { if (type == ChannelUtil.ASXTYPE_NONE) return url; if (type == ChannelUtil.ASXTYPE_AUTO && !isASX(url)) return url; String page; try { page = ChannelUtil.fetchPage(new URL(url).openConnection()); } catch (Exception e) { Channels.debug("asx fetch failed " + e); return url; } Channels.debug("page " + page); int first = page.indexOf("href="); if (first == -1) return url; int last = page.indexOf('\"', first + 6); if (last == -1) return url; return page.substring(first + 6, last); }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception { if (!(me.getMessage() instanceof HttpRequest)) { ctx.sendUpstream(me); return; } HttpRequest request = (HttpRequest) me.getMessage(); Object response; // Look up resource String path = request.getUri(); String host = request.getHeader("host"); log.debug("Received request for path:" + path); boolean showHtml = false; if (path.endsWith("?html")) { showHtml = true; path = path.replace("?html", ""); } for (String service : resources.keySet()) { log.debug("Available Service: " + service); } Model model = resources.get(path); if (model != null) { if (request.getMethod() == HttpMethod.GET) { if (showHtml) { String html = HtmlCreator.createModelPage(model, new URI(path), host); response = ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8"))); log.debug("Returned html page for resource: " + path); } else { response = new SelfDescription(model, new URI(request.getUri())); log.debug("Resource found: " + path); } } else { response = new DefaultHttpResponse( request.getProtocolVersion(), HttpResponseStatus.METHOD_NOT_ALLOWED); log.debug("Method not allowed: " + request.getMethod()); } } else { response = HttpResponseFactory.createHttpResponse( request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND); log.debug("Resource not found: " + path); } // Send response ChannelFuture future = Channels.write(ctx.getChannel(), response); future.addListener(ChannelFutureListener.CLOSE); }
public int getChannelID(final String s, final String c, final String n, final String l) { String loc = ""; if (l != null && !l.equals("--")) { loc = "$" + l; } final String trueCode = s + "$" + c + "$" + n + loc; final int id = channels.getChannelID(trueCode); return id; }
private void writeReset(final InetSocketAddress remoteEndpoint, final int messageID) { try { CoapMessage resetMessage = CoapMessage.createEmptyReset(messageID); ChannelFuture future = Channels.future(ctx.getChannel()); Channels.write(this.getChannelHandlerContext(), future, resetMessage, remoteEndpoint); future.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info("RST for message ID {} succesfully sent to {}.", messageID, remoteEndpoint); } }); } catch (IllegalArgumentException e) { log.error("This should never happen.", e); } }
public static void RemoveFromFavFile(String name, String url) { File f = Channels.workFavFile(); try { String str = FileUtils.readFileToString(f); Channels.debug("removing from fav file " + name); int pos = str.indexOf(url); if (pos > -1) { FileOutputStream out = new FileOutputStream(f, false); pos = str.lastIndexOf(FAV_BAR, pos); // head out.write(str.substring(0, pos).getBytes()); pos = str.indexOf(FAV_BAR, pos + 30); // tail if (pos > -1) out.write(str.substring(pos).getBytes()); out.flush(); out.close(); } } catch (Exception e) { } }
public static boolean streamType(String url, String type) { try { URI u = new URI(url); return u.getScheme().startsWith(type); } catch (Exception e) { Channels.debug("execp stream type " + e); return false; } }
private void writeEmptyAcknowledgement( final InetSocketAddress remoteAddress, final int messageID) { try { CoapMessage emptyAcknowledgement = CoapMessage.createEmptyAcknowledgement(messageID); ChannelFuture future = Channels.future(ctx.getChannel()); Channels.write(ctx, future, emptyAcknowledgement, remoteAddress); future.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info( "Empty ACK for message ID {} succesfully sent to {}.", messageID, remoteAddress); } }); } catch (IllegalArgumentException e) { log.error("This should never happen.", e); } }
public static void addToFavFile(String data, String name) { File f = Channels.workFavFile(); try { boolean newFile = !f.exists(); Channels.debug("adding to fav file " + name); FileOutputStream out = new FileOutputStream(f, true); if (newFile) { String msg = "## Auto generated favorite file,Edit with care\n\n\n"; out.write(FAV_BAR.getBytes(), 0, FAV_BAR.length()); out.write(msg.getBytes(), 0, msg.length()); } String n = "## Name: " + name + "\r\n\n"; out.write(FAV_BAR.getBytes(), 0, FAV_BAR.length()); out.write(n.getBytes(), 0, n.length()); out.write(data.getBytes(), 0, data.length()); out.flush(); out.close(); } catch (Exception e) { } }
public static void cacheFile(File f, String type) { File cache = new File(Channels.cacheFile()); long ttd = System.currentTimeMillis() + (7 * 24 * 60 * 60); // now + 1week String data = "\n\r" + f.getAbsolutePath() + "," + String.valueOf(ttd) + "," + type + "\n\r"; try { FileOutputStream out = new FileOutputStream(cache, true); out.write(data.getBytes(), 0, data.length()); out.flush(); out.close(); } catch (Exception e) { } }
private static ProcessBuilder buildPid(String fName, String url) { int rtmpMet = Channels.rtmpMethod(); if (rtmpMet == Channels.RTMP_MAGIC_TOKEN) { url = url.replace("!!!pms_ch_dash_y!!!", " -y "); url = url.replace("!!!pms_ch_dash_w!!!", " -W "); return null; } ArrayList<String> args = new ArrayList<String>(); args.add(Channels.cfg().getRtmpPath()); int pos = url.indexOf('?'); if (pos == -1) return null; String[] data = url.substring(pos + 1).split("&"); for (int i = 0; i < data.length; i++) { String[] kv = data[i].split("="); args.add(kv[0]); if (kv.length > 1) args.add("\"" + ChannelUtil.unescape(kv[1]) + "\""); } args.add("-o"); args.add("\"" + fName + "\""); return new ProcessBuilder(args); }
public static String execute(ProcessBuilder pb, boolean verbose) { try { Channels.debug("about to execute " + pb.command()); pb.redirectErrorStream(true); Process pid = pb.start(); InputStream is = pid.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); if (verbose) Channels.debug("execute read line " + line); } pid.waitFor(); return sb.toString(); } catch (Exception e) { Channels.debug("executing external script failed " + e); } return null; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { ChannelBuffer buf; PaxosMessage msg; buf = (ChannelBuffer) e.getMessage(); // Read in the message string. msg = new PaxosMessage(); msg.unSerialize(buf.array()); // Send the message upstream to the server handler. Channels.fireMessageReceived(ctx, msg); }
@Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) { PaxosMessage msg; ChannelBuffer sendBuf; byte[] data; msg = (PaxosMessage) e.getMessage(); // The original message. // Serialize the message. data = msg.serialize(); sendBuf = ChannelBuffers.buffer(data.length); sendBuf.writeBytes(data); // Write the actual msg. // Send the message upstream. Channels.write(ctx, e.getFuture(), sendBuf); }
@Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); if (sslFactory != null) { pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine())); } pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunking", new ChunkedWriteHandler()); pipeline.addLast("shuffle", PullServer); return pipeline; // TODO factor security manager into pipeline // TODO factor out encode/decode to permit binary shuffle // TODO factor out decode of index to permit alt. models }
public static int[] getNameIndex(String[] prop) { try { String x = ChannelUtil.getPropertyValue(prop, "name_index"); if (!empty(x)) { String[] idx = x.split("\\+"); int[] res = new int[idx.length]; for (int i = 0; i < idx.length; i++) { int j = new Integer(idx[i]).intValue(); if (j > 0) res[i] = j; } return res; } } catch (Exception e) { Channels.debug("excep " + e); } return null; }
public static String backTrack(DLNAResource start, int stop) { if (start == null) return null; if (Channels.save()) // compensate for save start = start.getParent(); if (stop == 0) return start.getName(); int i = 0; DLNAResource curr = start; while (i < stop) { curr = curr.getParent(); i++; if (curr instanceof Channel) { curr = null; break; } } if (curr != null) return curr.getName(); return null; }
@Test public void testPrimitiveChannelClose() throws Exception { assumeThat(mailboxSize, not(equalTo(0))); final IntChannel ch = Channels.newIntChannel(mailboxSize, policy); Fiber fib = new Fiber( "fiber", fjPool, new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { for (int i = 1; i <= 5; i++) { int m = ch.receiveInt(); assertThat(m, is(i)); } try { int m = ch.receiveInt(); fail("m = " + m); } catch (QueueChannel.EOFException e) { } assertTrue(ch.isClosed()); } }) .start(); Thread.sleep(50); ch.send(1); ch.send(2); ch.send(3); ch.send(4); ch.send(5); ch.close(); ch.send(6); ch.send(7); fib.join(); }
public String getWaveServerMenuItem( final String s, final String c, final String n, final String l, final double embargo, final double span) { String loc = ""; if (l != null && !l.equals("--")) { loc = "$" + l; } final String trueCode = s + "$" + c + "$" + n + loc; final int id = channels.getChannelID(trueCode); if (id == -1) { return null; } else { return getWaveServerMenuItem(id, embargo, span); } }
private <In, Out> Channel listen(int port, NetworkEndpointFactory<In, Out> endpointFactory) { ServerBootstrap bootstrap = new ServerBootstrap(channelFactory); bootstrap.setPipelineFactory( () -> Channels.pipeline( new ObjectEncoder(), new ObjectDecoder(ClassResolvers.softCachingResolver(getClass().getClassLoader())), new LoggingHandler(NettyNetworkServer.class, logLevel), new NettyNetworkEndpointAdapter<>(endpointFactory.createEndpoint()), new AddToChannelGroupHandler(allChannels))); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); Channel channel = bootstrap.bind(new InetSocketAddress(port)); allChannels.add(channel); return channel; }
public static String fetchPage( URLConnection connection, ChannelAuth auth, String cookie, HashMap<String, String> hdr) { try { // URLConnection connection=url.openConnection(); URL url = connection.getURL(); connection.setConnectTimeout(10000); connection.setRequestProperty("User-Agent", defAgentString); if (auth != null) { Channels.debug("auth " + auth.method + " authstr " + auth.authStr); if (auth.method == ChannelLogin.STD) connection.setRequestProperty("Authorization", auth.authStr); else if (auth.method == ChannelLogin.COOKIE) cookie = append(cookie, "; ", auth.authStr); else if (auth.method == ChannelLogin.APIKEY) { url = new URL(url.toString() + auth.authStr); connection = url.openConnection(); } } Channels.debug("fpage cookie " + cookie); String c1 = ChannelCookie.getCookie(url.toString()); if (!empty(c1)) { if (!cookieContains(c1, cookie)) { cookie = append(cookie, "; ", c1); } } Channels.debug("fpage2 cookie " + cookie + " " + url); if (!empty(cookie)) connection.setRequestProperty("Cookie", cookie); if (hdr != null && hdr.size() != 0) { for (String key : hdr.keySet()) connection.setRequestProperty(key, hdr.get(key)); } // connection.setRequestProperty("Content-Length", "0"); connection.setDoInput(true); connection.setDoOutput(true); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder page = new StringBuilder(); String str; while ((str = in.readLine()) != null) { // page.append("\n"); page.append(str.trim()); page.append("\n"); } in.close(); Channels.restoreProxyDNS(); return page.toString(); } catch (Exception e) { Channels.debug("fetch exception " + e.toString()); Channels.restoreProxyDNS(); return ""; } }
/** * Creates a new NetarkivetMessage. * * @param to the initial receiver of the message * @param replyTo the initial sender of the message * @throws ArgumentNotValid if to==replyTo, the replyTo parameter is a topic instead of a queue, * or there is a null parameter. */ protected NetarkivetMessage(ChannelID to, ChannelID replyTo) { ArgumentNotValid.checkNotNull(to, "to"); ArgumentNotValid.checkNotNull(replyTo, "replyTo"); if (to.getName().equals(replyTo.getName())) { throw new ArgumentNotValid("to and replyTo should not be equal."); } // Have not implemented replying to a topic because there is no use // for it in our current architecture if (Channels.isTopic(replyTo.getName())) { throw new ArgumentNotValid( "Reply channel must be queue but " + replyTo.toString() + " is a Topic"); } this.to = to; this.replyTo = replyTo; this.id = null; this.replyOfId = null; }
static void checkIfBackupNeeded(RobotController rc) throws GameActionException { int soldierSenseRad = (int) RobotType.SOLDIER.sensorRadiusSquared; Robot[] allies = rc.senseNearbyGameObjects(Robot.class, soldierSenseRad, rc.getTeam()); Robot[] enemies = rc.senseNearbyGameObjects(Robot.class, soldierSenseRad, rc.getTeam().opponent()); // System.out.println(allies.length + " " + enemies.length); boolean outnumbered = false; if (enemies.length == 0) outnumbered = false; else if ((double) allies.length / enemies.length <= 1.5) outnumbered = true; if (outnumbered && rc.readBroadcast(Channels.backupChannel) == 0) { int squad = rc.readBroadcast(rc.getRobot().getID()); rc.broadcast( Channels.backupChannel, Channels.backupEncoding(rc.getLocation(), squad, enemies.length)); System.out.println("COWBOY sending help call"); } }
private <K, V, T extends RedisAsyncConnection<K, V>> T connect( CommandHandler<K, V> handler, T connection) { try { ConnectionWatchdog watchdog = new ConnectionWatchdog(bootstrap, channels, timer); ChannelPipeline pipeline = Channels.pipeline(watchdog, handler, connection); Channel channel = bootstrap.getFactory().newChannel(pipeline); ChannelFuture future = channel.connect((SocketAddress) bootstrap.getOption("remoteAddress")); future.await(); if (!future.isSuccess()) { throw future.getCause(); } watchdog.setReconnect(true); return connection; } catch (Throwable e) { throw new RedisException("Unable to connect", e); } }
@Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("openChannels", transport.serverOpenChannels); HttpRequestDecoder requestDecoder = new HttpRequestDecoder( (int) transport.maxInitialLineLength.bytes(), (int) transport.maxHeaderSize.bytes(), (int) transport.maxChunkSize.bytes()); if (transport.maxCumulationBufferCapacity != null) { if (transport.maxCumulationBufferCapacity.bytes() > Integer.MAX_VALUE) { requestDecoder.setMaxCumulationBufferCapacity(Integer.MAX_VALUE); } else { requestDecoder.setMaxCumulationBufferCapacity( (int) transport.maxCumulationBufferCapacity.bytes()); } } if (transport.maxCompositeBufferComponents != -1) { requestDecoder.setMaxCumulationBufferComponents(transport.maxCompositeBufferComponents); } pipeline.addLast("decoder", requestDecoder); pipeline.addLast("decoder_compress", new ESHttpContentDecompressor(transport.compression)); HttpChunkAggregator httpChunkAggregator = new HttpChunkAggregator((int) transport.maxContentLength.bytes()); if (transport.maxCompositeBufferComponents != -1) { httpChunkAggregator.setMaxCumulationBufferComponents( transport.maxCompositeBufferComponents); } pipeline.addLast("aggregator", httpChunkAggregator); pipeline.addLast("encoder", new ESHttpResponseEncoder()); if (transport.compression) { pipeline.addLast("encoder_compress", new HttpContentCompressor(transport.compressionLevel)); } if (transport.pipelining) { pipeline.addLast("pipelining", new HttpPipeliningHandler(transport.pipeliningMaxEvents)); } pipeline.addLast("handler", requestHandler); return pipeline; }