/** * Test whether a memory range is set to a given integer value * * @param start The address to start checking at * @param bytes The size of the region to check, in bytes * @param verbose If true, produce verbose output * @param value The value to which the memory should be set */ private static boolean isSet(Address start, int bytes, boolean verbose, int value) /* Inlining this loop into the uninterruptible code can * cause/encourage the GCP into moving a get_obj_tib into the * interruptible region where the tib is being installed via an * int_store */ throws NoInlinePragma { if (Assert.VERIFY_ASSERTIONS) assertAligned(bytes); for (int i = 0; i < bytes; i += BYTES_IN_INT) if (start.loadInt(Offset.fromInt(i)) != value) { if (verbose) { Log.prependThreadId(); Log.write("Memory range does not contain only value "); Log.writeln(value); Log.write("Non-zero range: "); Log.write(start); Log.write(" .. "); Log.writeln(start.add(bytes)); Log.write("First bad value at "); Log.writeln(start.add(i)); dumpMemory(start, 0, bytes); } return false; } return true; }
private void handleCookie(String set_cookie, boolean cookie2, RoRequest req, Response resp) throws ProtocolException { Cookie[] cookies; if (cookie2) cookies = Cookie2.parse(set_cookie, req); else cookies = Cookie.parse(set_cookie, req); if (Log.isEnabled(Log.COOKI)) { Log.write(Log.COOKI, "CookM: Received and parsed " + cookies.length + " cookies:"); for (int idx = 0; idx < cookies.length; idx++) Log.write(Log.COOKI, "CookM: Cookie " + idx + ": " + cookies[idx]); } Hashtable cookie_list = Util.getList(cookie_cntxt_list, req.getConnection().getContext()); synchronized (cookie_list) { for (int idx = 0; idx < cookies.length; idx++) { Cookie cookie = (Cookie) cookie_list.get(cookies[idx]); if (cookie != null && cookies[idx].hasExpired()) { Log.write(Log.COOKI, "CookM: cookie has expired and is " + "being removed: " + cookie); cookie_list.remove(cookie); // expired, so remove } else if (!cookies[idx].hasExpired()) // new or replaced { if (cookie_handler == null || cookie_handler.acceptCookie(cookies[idx], req, resp)) cookie_list.put(cookies[idx], cookies[idx]); } } } }
/** * Associates this stream with a request and the actual output stream. No other methods in this * class may be invoked until this method has been invoked by the HTTPConnection. * * @param req the request this stream is to be associated with * @param os the underlying output stream to write our data to, or null if we should write to a * ByteArrayOutputStream instead. * @param con_to connection timeout to use in sendRequest() */ void goAhead(Request req, OutputStream os, int con_to) { this.req = req; this.os = os; this.con_to = con_to; if (os == null) bos = new ByteArrayOutputStream(); Log.write(Log.CONN, "OutS: Stream ready for writing"); if (bos != null) Log.write(Log.CONN, "OutS: Buffering all data before sending " + "request"); }
/** * Returns user feedback. * * @param info information string * @param ok success/error flag * @throws IOException I/O exception */ private void info(final String info, final boolean ok) throws IOException { // write feedback to log file log.write(this, ok ? OK : ERROR_C + info, perf); // send {MSG}0 and (0|1) as (success|error) flag out.writeString(info); send(ok); }
/** Stops the shooter */ public static void stopShooter() { try { shooterConveyor.setX(0.0); } catch (CANTimeoutException ex) { System.out.println("CAN TIMEOUT EXCEPTION ON SHOOTER CONVEYOR"); Log.write("CANJag Timeout Exception on Shooter Conveyor"); } }
/** Shooter conveyor goes in reverse at feeder station */ public static void feedMode() { try { shooterConveyor.setX(Constants.CONV_SHOOTER_POWER); } catch (CANTimeoutException ex) { System.out.println("CAN TIMEOUT EXCEPTION ON SHOOTER CONVEYOR"); Log.write("CANJag Timeout Exception on Shooter Conveyor"); } }
/** Ingestor conveyor stops */ public static void stopIngest() { try { ingestConveyor.setX(0.0); } catch (CANTimeoutException ex) { System.out.println("CAN TIMEOUT EXCEPTION ON INGEST CONVEYOR"); Log.write("CANJag Timeout Exception on Ingest Conveyor"); } }
/** Invoked by the HTTPClient. */ public void responsePhase3Handler(Response resp, RoRequest req) throws IOException, ModuleException { String ce = resp.getHeader("Content-Encoding"); if (ce == null || req.getMethod().equals("HEAD") || resp.getStatusCode() == 206) return; Vector pce; try { pce = Util.parseHeader(ce); } catch (ParseException pe) { throw new ModuleException(pe.toString()); } if (pce.size() == 0) return; String encoding = ((HttpHeaderElement) pce.firstElement()).getName(); if (encoding.equalsIgnoreCase("gzip") || encoding.equalsIgnoreCase("x-gzip")) { Log.write(Log.MODS, "CEM: pushing gzip-input-stream"); resp.inp_stream = new GZIPInputStream(resp.inp_stream); pce.removeElementAt(pce.size() - 1); resp.deleteHeader("Content-length"); } else if (encoding.equalsIgnoreCase("deflate")) { Log.write(Log.MODS, "CEM: pushing inflater-input-stream"); resp.inp_stream = new InflaterInputStream(resp.inp_stream); pce.removeElementAt(pce.size() - 1); resp.deleteHeader("Content-length"); } else if (encoding.equalsIgnoreCase("compress") || encoding.equalsIgnoreCase("x-compress")) { Log.write(Log.MODS, "CEM: pushing uncompress-input-stream"); resp.inp_stream = new UncompressInputStream(resp.inp_stream); pce.removeElementAt(pce.size() - 1); resp.deleteHeader("Content-length"); } else if (encoding.equalsIgnoreCase("identity")) { Log.write(Log.MODS, "CEM: ignoring 'identity' token"); pce.removeElementAt(pce.size() - 1); } else { Log.write(Log.MODS, "CEM: Unknown content encoding '" + encoding + "'"); } if (pce.size() > 0) resp.setHeader("Content-Encoding", Util.assembleHeader(pce)); else resp.deleteHeader("Content-Encoding"); }
private Conveyors() { try { ingestConveyor = new CANJaguar(Constants.CONV_INGEST_JAG_POS); shooterConveyor = new CANJaguar(Constants.CONV_SHOOT_JAG_POS); } catch (CANTimeoutException ex) { System.out.println("CAN TIMEOUT EXCEPTION ON CONVEYORS"); Log.write("CANJag Timeout Exception on Conveyors"); } timer = new Timer(); }
/** * Sets the request method (e.g. "PUT" or "HEAD"). Can only be set * before connect() is called. * * @param method the http method. * @exception ProtocolException if already connected. */ public void setRequestMethod(String method) throws ProtocolException { if (connected) throw new ProtocolException("Already connected!"); Log.write(Log.URLC, "URLC: (" + urlString + ") Setting request method: " + method); this.method = method.trim().toUpperCase(); method_set = true; }
/** * Executes the specified command. * * @param cmd command to be executed * @throws IOException I/O exception */ private void execute(final Command cmd) throws IOException { log.write(this, cmd + " [...]"); final DecodingInput di = new DecodingInput(in); try { cmd.setInput(di); cmd.execute(context); success(cmd.info()); } catch (final BaseXException ex) { di.flush(); error(ex.getMessage()); } }
/** Exits the session. */ public synchronized void quit() { running = false; if (log != null) log.write(this, "LOGOUT " + context.user.name, OK); // wait until running command was stopped if (command != null) { command.stop(); while (command != null) Performance.sleep(50); } context.delete(this); try { new Close().execute(context); socket.close(); if (events) { esocket.close(); // remove this session from all events in pool for (final Sessions s : context.events.values()) s.remove(this); } } catch (final Exception ex) { if (log != null) log.write(ex.getMessage()); Util.stack(ex); } }
@Override public void run() { // initialize the session via cram-md5 authentication try { final String ts = Long.toString(System.nanoTime()); final byte[] address = socket.getInetAddress().getAddress(); // send {TIMESTAMP}0 out = PrintOutput.get(socket.getOutputStream()); out.print(ts); send(true); // evaluate login data in = new BufferInput(socket.getInputStream()); // receive {USER}0{PASSWORD}0 final String us = in.readString(); final String pw = in.readString(); context.user = context.users.get(us); running = context.user != null && md5(string(context.user.password) + ts).equals(pw); // write log information if (running) { log.write(this, "LOGIN " + context.user.name, OK); // send {OK} send(true); server.unblock(address); context.add(this); } else { if (!us.isEmpty()) log.write(this, ACCESS_DENIED + COLS + us); new ClientDelayer(server.block(address), this, server).start(); } } catch (final IOException ex) { Util.stack(ex); log.write(ex.getMessage()); return; } if (!running) return; // authentification done, start command loop ServerCmd sc = null; String cmd = null; try { while (running) { command = null; try { final int b = in.read(); if (b == -1) { // end of stream: exit session quit(); break; } last = System.currentTimeMillis(); perf.time(); sc = ServerCmd.get(b); cmd = null; if (sc == ServerCmd.CREATE) { create(); } else if (sc == ServerCmd.ADD) { add(); } else if (sc == ServerCmd.WATCH) { watch(); } else if (sc == ServerCmd.UNWATCH) { unwatch(); } else if (sc == ServerCmd.REPLACE) { replace(); } else if (sc == ServerCmd.STORE) { store(); } else if (sc != ServerCmd.COMMAND) { query(sc); } else { // database command cmd = new ByteList().add(b).add(in.readBytes()).toString(); } } catch (final IOException ex) { // this exception may be thrown if a session is stopped quit(); break; } if (sc != ServerCmd.COMMAND) continue; // parse input and create command instance try { command = new CommandParser(cmd, context).parseSingle(); } catch (final QueryException ex) { // log invalid command final String msg = ex.getMessage(); log.write(this, cmd, ERROR_C + msg); // send 0 to mark end of potential result out.write(0); // send {INFO}0 out.writeString(msg); // send 1 to mark error send(false); continue; } // start timeout command.startTimeout(context.mprop.num(MainProp.TIMEOUT)); log.write(this, command.toString().replace('\r', ' ').replace('\n', ' ')); // execute command and send {RESULT} boolean ok = true; String info; try { command.execute(context, new EncodingOutput(out)); info = command.info(); } catch (final BaseXException ex) { ok = false; info = ex.getMessage(); if (info.startsWith(INTERRUPTED)) info = TIMEOUT_EXCEEDED; } // stop timeout command.stopTimeout(); // send 0 to mark end of result out.write(0); // send info info(info, ok); // stop console if (command instanceof Exit) { command = null; quit(); } } } catch (final IOException ex) { log.write(this, sc == ServerCmd.COMMAND ? cmd : sc, ERROR_C + ex.getMessage()); Util.debug(ex); command = null; quit(); } command = null; }
/** Invoked by the HTTPClient. */ public void responsePhase1Handler(Response resp, RoRequest roreq) throws IOException, ModuleException { try { resp.getStatusCode(); } catch (RetryException re) { Log.write(Log.MODS, "RtryM: Caught RetryException"); boolean got_lock = false; try { synchronized (re.first) { got_lock = true; // initialize idempotent sequence checking IdempotentSequence seq = new IdempotentSequence(); for (RetryException e = re.first; e != null; e = e.next) seq.add(e.request); for (RetryException e = re.first; e != null; e = e.next) { Log.write(Log.MODS, "RtryM: handling exception ", e); Request req = e.request; HTTPConnection con = req.getConnection(); /* Don't retry if either the sequence is not idempotent * (Sec 8.1.4 and 9.1.2), or we've already retried enough * times, or the headers have been read and parsed * already */ if (!seq.isIdempotent(req) || (con.ServProtVersKnown && con.ServerProtocolVersion >= HTTP_1_1 && req.num_retries > 0) || ((!con.ServProtVersKnown || con.ServerProtocolVersion <= HTTP_1_0) && req.num_retries > 4) || e.response.got_headers) { e.first = null; continue; } /** * if an output stream was used (i.e. we don't have the data to resend) then delegate * the responsibility for resending to the application. */ if (req.getStream() != null) { if (HTTPConnection.deferStreamed) { req.getStream().reset(); e.response.setRetryRequest(true); } e.first = null; continue; } /* If we have an entity then setup either the entity-delay * or the Expect header */ if (req.getData() != null && e.conn_reset) { if (con.ServProtVersKnown && con.ServerProtocolVersion >= HTTP_1_1) addToken(req, "Expect", "100-continue"); else req.delay_entity = 5000L << req.num_retries; } /* If the next request in line has an entity and we're * talking to an HTTP/1.0 server then close the socket * after this request. This is so that the available() * call (to watch for an error response from the server) * will work correctly. */ if (e.next != null && e.next.request.getData() != null && (!con.ServProtVersKnown || con.ServerProtocolVersion < HTTP_1_1) && e.conn_reset) { addToken(req, "Connection", "close"); } /* If this an HTTP/1.1 server then don't pipeline retries. * The problem is that if the server for some reason * decides not to use persistent connections and it does * not do a correct shutdown of the connection, then the * response will be ReSeT. If we did pipeline then we * would keep falling into this trap indefinitely. * * Note that for HTTP/1.0 servers, if they don't support * keep-alives then the normal code will already handle * this accordingly and won't pipe over the same * connection. */ if (con.ServProtVersKnown && con.ServerProtocolVersion >= HTTP_1_1 && e.conn_reset) { req.dont_pipeline = true; } // The above is too risky - for moment let's be safe // and never pipeline retried request at all. req.dont_pipeline = true; // now resend the request Log.write( Log.MODS, "RtryM: Retrying request '" + req.getMethod() + " " + req.getRequestURI() + "'"); if (e.conn_reset) req.num_retries++; e.response.http_resp.set(req, con.sendRequest(req, e.response.timeout)); e.exception = null; e.first = null; } } } catch (NullPointerException npe) { if (got_lock) throw npe; } catch (ParseException pe) { throw new IOException(pe.getMessage()); } if (re.exception != null) throw re.exception; re.restart = true; throw re; } }
/** * Closes the stream and causes the data to be sent if it has not already been done so. This * method <strong>must</strong> be invoked when all data has been written. * * @exception IOException if any exception is thrown by the underlying socket, or if too few bytes * were written. * @exception IllegalAccessError if this stream has not been associated with a request yet. */ public synchronized void close() throws IOException, IllegalAccessError { if (req == null) throw new IllegalAccessError("Stream not associated with a request"); if (ignore) return; if (bos != null) { req.setData(bos.toByteArray()); req.setStream(null); if (trailers.length > 0) { NVPair[] hdrs = req.getHeaders(); // remove any Trailer header field int len = hdrs.length; for (int idx = 0; idx < len; idx++) { if (hdrs[idx].getName().equalsIgnoreCase("Trailer")) { System.arraycopy(hdrs, idx + 1, hdrs, idx, len - idx - 1); len--; } } // add the trailers to the headers hdrs = Util.resizeArray(hdrs, len + trailers.length); System.arraycopy(trailers, 0, hdrs, len, trailers.length); req.setHeaders(hdrs); } Log.write(Log.CONN, "OutS: Sending request"); try { resp = req.getConnection().sendRequest(req, con_to); } catch (ModuleException me) { throw new IOException(me.toString()); } notify(); } else { if (rcvd < length) { IOException ioe = new IOException( "Premature close: only " + rcvd + " bytes written instead of the " + "expected " + length); req.getConnection().closeDemux(ioe, false); req.getConnection().outputFinished(); throw ioe; } try { if (length == -1) { if (Log.isEnabled(Log.CONN) && trailers.length > 0) { Log.write(Log.CONN, "OutS: Sending trailers:"); for (int idx = 0; idx < trailers.length; idx++) Log.write( Log.CONN, " " + trailers[idx].getName() + ": " + trailers[idx].getValue()); } os.write(Codecs.chunkedEncode(null, 0, 0, trailers, true)); } os.flush(); Log.write(Log.CONN, "OutS: All data sent"); } catch (IOException ioe) { req.getConnection().closeDemux(ioe, true); throw ioe; } finally { req.getConnection().outputFinished(); } } }
/** * Processes the query iterator. * * @param sc server command * @throws IOException I/O exception */ private void query(final ServerCmd sc) throws IOException { // iterator argument (query or identifier) String arg = in.readString(); String err = null; try { final QueryListener qp; if (sc == ServerCmd.QUERY) { final String query = arg; qp = new QueryListener(query, context); arg = Integer.toString(id++); queries.put(arg, qp); // send {ID}0 out.writeString(arg); // write log file log.write(this, sc + "(" + arg + ')', query, OK, perf); } else { // find query process qp = queries.get(arg); // ID has already been removed if (qp == null) { if (sc != ServerCmd.CLOSE) throw new IOException("Unknown Query ID: " + arg); } else if (sc == ServerCmd.BIND) { final String key = in.readString(); final String val = in.readString(); final String typ = in.readString(); qp.bind(key, val, typ); log.write(this, sc + "(" + arg + ')', key, val, typ, OK, perf); } else if (sc == ServerCmd.ITER) { qp.execute(true, out, true); } else if (sc == ServerCmd.EXEC) { qp.execute(false, out, true); } else if (sc == ServerCmd.INFO) { out.print(qp.info()); } else if (sc == ServerCmd.OPTIONS) { out.print(qp.options()); } else if (sc == ServerCmd.CLOSE) { queries.remove(arg); } else if (sc == ServerCmd.NEXT) { throw new Exception("Protocol for query iteration is out-of-dated."); } // send 0 as end marker out.write(0); } // send 0 as success flag out.write(0); // write log file (bind and execute have been logged before) if (sc != ServerCmd.BIND) log.write(this, sc + "(" + arg + ')', OK, perf); } catch (final Exception ex) { // log exception (static or runtime) err = ex.getMessage(); log.write(this, sc + "(" + arg + ')', ERROR_C + err); queries.remove(arg); } if (err != null) { // send 0 as end marker, 1 as error flag, and {MSG}0 out.write(0); out.write(1); out.writeString(err); } out.flush(); }
/** Invoked by the HTTPClient. */ public int requestHandler(Request req, Response[] resp) { // First remove any Cookie headers we might have set for a previous // request NVPair[] hdrs = req.getHeaders(); int length = hdrs.length; for (int idx = 0; idx < hdrs.length; idx++) { int beg = idx; while (idx < hdrs.length && hdrs[idx].getName().equalsIgnoreCase("Cookie")) idx++; if (idx - beg > 0) { length -= idx - beg; System.arraycopy(hdrs, idx, hdrs, beg, length - beg); } } if (length < hdrs.length) { hdrs = Util.resizeArray(hdrs, length); req.setHeaders(hdrs); } // Now set any new cookie headers Hashtable cookie_list = Util.getList(cookie_cntxt_list, req.getConnection().getContext()); if (cookie_list.size() == 0) return REQ_CONTINUE; // no need to create a lot of objects Vector names = new Vector(); Vector lens = new Vector(); int version = 0; synchronized (cookie_list) { Enumeration list = cookie_list.elements(); Vector remove_list = null; while (list.hasMoreElements()) { Cookie cookie = (Cookie) list.nextElement(); if (cookie.hasExpired()) { Log.write(Log.COOKI, "CookM: cookie has expired and is " + "being removed: " + cookie); if (remove_list == null) remove_list = new Vector(); remove_list.addElement(cookie); continue; } if (cookie.sendWith(req) && (cookie_handler == null || cookie_handler.sendCookie(cookie, req))) { int len = cookie.getPath().length(); int idx; // insert in correct position for (idx = 0; idx < lens.size(); idx++) if (((Integer) lens.elementAt(idx)).intValue() < len) break; names.insertElementAt(cookie.toExternalForm(), idx); lens.insertElementAt(new Integer(len), idx); if (cookie instanceof Cookie2) version = Math.max(version, ((Cookie2) cookie).getVersion()); } } // remove any marked cookies // Note: we can't do this during the enumeration! if (remove_list != null) { for (int idx = 0; idx < remove_list.size(); idx++) cookie_list.remove(remove_list.elementAt(idx)); } } if (!names.isEmpty()) { StringBuffer value = new StringBuffer(); if (version > 0) value.append("$Version=\"" + version + "\"; "); value.append((String) names.elementAt(0)); for (int idx = 1; idx < names.size(); idx++) { value.append("; "); value.append((String) names.elementAt(idx)); } hdrs = Util.resizeArray(hdrs, hdrs.length + 1); hdrs[hdrs.length - 1] = new NVPair("Cookie", value.toString()); // add Cookie2 header if necessary if (version != 1) // we currently know about version 1 only { int idx; for (idx = 0; idx < hdrs.length; idx++) if (hdrs[idx].getName().equalsIgnoreCase("Cookie2")) break; if (idx == hdrs.length) { hdrs = Util.resizeArray(hdrs, hdrs.length + 1); hdrs[hdrs.length - 1] = new NVPair("Cookie2", "$Version=\"1\""); } } req.setHeaders(hdrs); Log.write(Log.COOKI, "CookM: Sending cookies '" + value + "'"); } return REQ_CONTINUE; }
/** * Write a GestureType to a file * * @param path * @param type * @throws IOException */ public static void writeToFile(String path, GestureType type) throws IOException { // File file = new File(path); // file.createNewFile(); FileWriter writer = new FileWriter(path + "/" + type.getName() + ".dat"); BufferedWriter out = new BufferedWriter(writer); Log.write(Log.DEBUG, "IO: Beginning to write to File", null); /* normale Variablen */ out.write("#STATES"); out.newLine(); out.write(String.valueOf(type.states)); out.newLine(); out.write("#OBSERVATIONS"); out.newLine(); out.write(String.valueOf(type.observations)); out.newLine(); out.write("#DEFAULTPROBABILITY"); out.newLine(); out.write(String.valueOf(type.getDefaultProbability())); out.newLine(); /* Quantisierer */ Quantizer quantizer = type.getQuantizer(); out.write("#QUANTIZER"); out.newLine(); out.write("$map"); out.newLine(); writeArr(quantizer.map, out); /* Hidden Markov Model */ HMM markovModel = type.getMarkovModel(); out.write("#HMM"); out.newLine(); out.write("$pi"); out.newLine(); for (int i = 0; i < markovModel.pi.length; i++) { out.write(String.valueOf(markovModel.pi[i]) + "\t"); } out.newLine(); out.write("$a"); out.newLine(); writeArr(markovModel.a, out); out.write("$b"); out.newLine(); writeArr(markovModel.b, out); /* ActionExecutor */ ActionExecutor executor = type.getExecutor(); out.write("#EXECUTOR"); out.newLine(); out.write("$mode"); out.newLine(); out.write(String.valueOf(executor.getMode())); out.newLine(); out.write("$key"); out.newLine(); out.write(String.valueOf(executor.getKey())); out.newLine(); out.write("$modifiers"); out.newLine(); out.write(String.valueOf(executor.getModifiers())); out.newLine(); out.write("$command"); out.newLine(); out.write(executor.getCommand()); out.newLine(); out.write("#END"); out.close(); Log.write(Log.DEBUG, "IO: Finished writing to File", null); }