/** * Resets the cipher object to its original state. This is used when doFinal is called in the * Cipher class, so that the cipher can be reused (with its original key and iv). */ void reset() { if (aadBuffer == null) { aadBuffer = new ByteArrayOutputStream(); } else { aadBuffer.reset(); } if (gctrPAndC != null) gctrPAndC.reset(); if (ghashAllToS != null) ghashAllToS.reset(); processed = 0; sizeOfAAD = 0; if (ibuffer != null) { ibuffer.reset(); } }
public byte[] getTileImageData(int x, int y, int zoom) { mStream.reset(); Matrix matrix = new Matrix(mBaseMatrix); float scale = (float) (Math.pow(2, zoom) * mScale); matrix.postScale(scale, scale); matrix.postTranslate(-x * mDimension, -y * mDimension); mBitmap.eraseColor(Color.TRANSPARENT); Canvas c = new Canvas(mBitmap); c.setMatrix(matrix); // NOTE: Picture is not thread-safe. synchronized (mSvgPicture) { mSvgPicture.draw(c); } BufferedOutputStream stream = new BufferedOutputStream(mStream); mBitmap.compress(Bitmap.CompressFormat.PNG, 0, stream); try { stream.close(); } catch (IOException e) { Log.e(TAG, "Error while closing tile byte stream."); e.printStackTrace(); } return mStream.toByteArray(); }
/** * Add the entries from the supplied {@link ZipInputStream} to this archive instance. * * @param zipStream The zip stream. * @return This archive instance. * @throws IOException Error reading zip stream. */ public Archive addEntries(ZipInputStream zipStream) throws IOException { AssertArgument.isNotNull(zipStream, "zipStream"); try { ZipEntry zipEntry = zipStream.getNextEntry(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); byte[] byteReadBuffer = new byte[512]; int byteReadCount; while (zipEntry != null) { if (zipEntry.isDirectory()) { addEntry(zipEntry.getName(), (byte[]) null); } else { while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) { outByteStream.write(byteReadBuffer, 0, byteReadCount); } addEntry(zipEntry.getName(), outByteStream.toByteArray()); outByteStream.reset(); } zipEntry = zipStream.getNextEntry(); } } finally { try { zipStream.close(); } catch (IOException e) { logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e); } } return this; }
/** * Initializes the cipher in the specified mode with the given key and iv. * * @param decrypting flag indicating encryption or decryption * @param algorithm the algorithm name * @param key the key * @param iv the iv * @param tagLenBytes the length of tag in bytes * @exception InvalidKeyException if the given key is inappropriate for initializing this cipher */ void init(boolean decrypting, String algorithm, byte[] keyValue, byte[] ivValue, int tagLenBytes) throws InvalidKeyException { if (keyValue == null || ivValue == null) { throw new InvalidKeyException("Internal error"); } // always encrypt mode for embedded cipher this.embeddedCipher.init(false, algorithm, keyValue); this.subkeyH = new byte[AES_BLOCK_SIZE]; this.embeddedCipher.encryptBlock(new byte[AES_BLOCK_SIZE], 0, this.subkeyH, 0); this.iv = ivValue.clone(); preCounterBlock = getJ0(iv, subkeyH); byte[] j0Plus1 = preCounterBlock.clone(); increment32(j0Plus1); gctrPAndC = new GCTR(embeddedCipher, j0Plus1); ghashAllToS = new GHASH(subkeyH); this.tagLenBytes = tagLenBytes; if (aadBuffer == null) { aadBuffer = new ByteArrayOutputStream(); } else { aadBuffer.reset(); } processed = 0; sizeOfAAD = 0; if (decrypting) { ibuffer = new ByteArrayOutputStream(); } }
/** Restores the content of this cipher to the previous saved one. */ void restore() { processed = processedSave; sizeOfAAD = sizeOfAADSave; if (aadBuffer != null) { aadBuffer.reset(); if (aadBufferSave != null) { aadBuffer.write(aadBufferSave, 0, aadBufferSave.length); } } if (gctrPAndC != null) gctrPAndC.restore(); if (ghashAllToS != null) ghashAllToS.restore(); if (ibuffer != null) { ibuffer.reset(); ibuffer.write(ibufferSave, 0, ibufferSave.length); } }
public void sendMessage(String name, Serializable message) throws IOException { setCall(); try { if (!statics.isTeamRobot()) { throw new IOException("You are not on a team."); } byteStreamWriter.reset(); ObjectOutputStream objectStreamWriter = new ObjectOutputStream(byteStreamWriter); objectStreamWriter.writeObject(message); objectStreamWriter.flush(); byteStreamWriter.flush(); final byte[] bytes = byteStreamWriter.toByteArray(); objectStreamWriter.reset(); if (bytes.length > MAX_MESSAGE_SIZE) { throw new IOException("Message too big. " + bytes.length + ">" + MAX_MESSAGE_SIZE); } commands.getTeamMessages().add(new TeamMessage(getName(), name, bytes)); } catch (IOException e) { out.printStackTrace(e); throw e; } }
/** * Test method for {@link cpath.converter.internal.UniprotCleanerImpl#cleane(java.lang.String)}. * * @throws IOException */ @Test public void testCleaner() throws IOException { // read data from file and look for accessions before being cleaned ByteArrayOutputStream os = new ByteArrayOutputStream(); CPathUtils.unzip( new ZipInputStream( CPathUtils.LOADER.getResource("/test_uniprot_data.dat.zip").getInputStream()), os); byte[] bytes = os.toByteArray(); String data = new String(bytes); assertTrue(data.indexOf(CALR3_HUMAN_BEFORE) != -1); assertTrue(data.indexOf(CALRL_HUMAN_BEFORE) != -1); Cleaner cleaner = new UniProtCleanerImpl(); os.reset(); cleaner.clean(new ByteArrayInputStream(bytes), os); bytes = os.toByteArray(); data = new String(bytes); assertTrue(data.indexOf(CALR3_HUMAN_AFTER) != -1); assertTrue(data.indexOf(CALRL_HUMAN_AFTER) != -1); // dump owl for review String outFilename = getClass().getClassLoader().getResource("").getPath() + File.separator + "testCleanUniProt.out.dat"; Writer out = new OutputStreamWriter(new FileOutputStream(outFilename)); out.write(data); out.close(); }
private void doTest(String prefix) throws IOException { int n = 0; int failed = 0; for (String name : myMap.keySet()) { if (prefix == null && name.contains("/")) { continue; } if (prefix != null && !name.startsWith(prefix)) { continue; } System.out.print("filename = " + name); n++; final MainParseTest.Test test = myMap.get(name); try { myFixture.testHighlighting(test.showWarnings, true, test.showInfo, name); if (test.expectedResult == Result.ERR) { System.out.println( " FAILED. Expression incorrectly parsed OK: " + FileUtil.loadFile(new File(getTestDataPath(), name))); failed++; } else { System.out.println(" OK"); } } catch (Throwable e) { if (test.expectedResult == Result.ERR) { System.out.println(" OK"); } else { e.printStackTrace(); System.out.println( " FAILED. Expression = " + FileUtil.loadFile(new File(getTestDataPath(), name))); if (myOut.size() > 0) { String line; final BufferedReader reader = new BufferedReader(new StringReader(myOut.toString())); do { line = reader.readLine(); } while (line != null && (line.trim().length() == 0 || line.trim().equals("ERROR:"))); if (line != null) { if (line.matches(".*java.lang.Error: junit.framework.AssertionFailedError:.*")) { System.out.println( "ERROR: " + line.replace( "java.lang.Error: junit.framework.AssertionFailedError:", "")); } } else { System.out.println("ERROR: " + myOut.toString()); } } failed++; } } myOut.reset(); } System.out.println(""); System.out.println(n + " Tests executed, " + failed + " failed"); assertFalse(failed > 0); }
// ----------------------------------------------------------- // for "SrvRqst" // find the matched URLs with (type, scope, predicate, ltag) // return: error code (short) // number of matched URLs (short) // URL blocks (decided bt previous #URL) // ----------------------------------------------------------- public synchronized byte[] getMatchedURL(String type, String scope, String pred, String ltag) { byte[] buf = null; int ecode = Const.OK; if (!Util.shareString(daf.getScope(), scope, ",")) { ecode = Const.SCOPE_NOT_SUPPORTED; } b.reset(); try { int count = 0; d.writeShort(ecode); // error code d.writeShort(count); // URL count, place holder if (ecode == Const.OK) { // no error, find matched URLs Iterator values = table.values().iterator(); while (values.hasNext()) { Entry e = (Entry) values.next(); if (e.match(type, scope, pred, ltag)) { count++; d.writeByte(0); d.writeShort(e.getLifetime()); d.writeShort(e.getURL().length()); d.writeBytes(e.getURL()); d.writeByte(0); } } } buf = b.toByteArray(); if (count > 0) Util.writeInt(buf, 2, count, 2); // update count } catch (Exception e) { if (ServiceLocationManager.displayMSLPTrace) e.printStackTrace(); } return buf; }
public void run() { while (controller.okToRun) { try { recordControl.setRecordStream(bos); capturePlayer.start(); recordControl.startRecord(); Thread.sleep(recordingTime); recordControl.stopRecord(); recordControl.commit(); bos.flush(); // Insert the recorded data into the shared buffer. buffer.insert(bos.toByteArray()); // Reset the ByteArrayOutputStream for reuse. bos.reset(); } catch (InterruptedException e) { // If Thread was interrupted, we just want to terminate. // Close any open Players // Do we need to do this if we set the threads to null // from TunerMIDlet? if (capturePlayer != null) { capturePlayer.close(); } } catch (Exception e) { controller.showError(e.getMessage(), new FatalForm(controller)); } } }
private int testObjectSer( ObjectWriter writer, MediaItem value, int reps, ByteArrayOutputStream result) throws Exception { for (int i = 0; i < reps; ++i) { result.reset(); writer.writeValue(result, value); } return result.size(); }
public void flush() { try { m_txtArea.append(new String(buffer.toByteArray(), encoding)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } buffer.reset(); }
@Override public synchronized void flush() throws IOException { super.flush(); String record = this.toString(); super.reset(); if (record.length() > 0 && !record.equals(separator)) { logger.logp(level, "LoggerOutputStream", "log" + level, record); } }
@Override public synchronized void flush() throws IOException { super.flush(); String record = this.toString(); super.reset(); if (record.length() > 0 && !record.equals(separator)) { jTerminal.print(record); jFrame.repaint(); } }
private FileStatus getFileStatus(FileStatus fileStatus) throws IOException { FileStatus status = new FileStatus(); buffer.reset(); DataOutputStream out = new DataOutputStream(buffer); fileStatus.write(out); in.reset(buffer.toByteArray(), 0, buffer.size()); status.readFields(in); return status; }
private int testAvroSer(GenericRecord value, int reps, ByteArrayOutputStream result) throws Exception { BinaryEncoder avroEncoder = null; for (int i = 0; i < reps; ++i) { result.reset(); // reuse? // avroEncoder = ENCODER_FACTORY.binaryEncoder(result, null); avroEncoder = ENCODER_FACTORY.binaryEncoder(result, avroEncoder); WRITER.write(value, avroEncoder); avroEncoder.flush(); } return result.size(); // just to get some non-optimizable number }
byte[] messageToBuffer(Message msg) throws Exception { ObjectOutputStream out; // BufferedOutputStream bos; out_stream.reset(); // bos=new BufferedOutputStream(out_stream); out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version // bos.write(Version.version_id, 0, Version.version_id.length); // write the version out = new ObjectOutputStream(out_stream); // out=new ObjectOutputStream(bos); msg.writeExternal(out); out.flush(); // needed if out buffers its output to out_stream return out_stream.toByteArray(); }
public static void main(String... args) throws Exception { DefaultObjectModel om = new DefaultObjectModel(args[1]); om.setWrapper(Class.forName(args[2])); CompactReader rd = new CompactReader(om); String task = args[0]; if (task.equals("roundtrip")) { DefaultBlock result = new DefaultBlock(); ByteArrayOutputStream os = new ByteArrayOutputStream(); CompactWriter wr = new CompactWriter(om, os); int count = 0; long decTime = 0; long encTime = 0; FileInputStream is = new FileInputStream(args[3]); Buf buf = DirectBuf.newInstance(); try { for (; ; ) { if (!buf.fillFrom(is)) break; buf.flip(); result.clear(); os.reset(); long t1 = System.currentTimeMillis(); rd.read(buf, result); long t2 = System.currentTimeMillis(); for (Object o : result) wr.write(o); wr.flush(); long t3 = System.currentTimeMillis(); decTime += t2 - t1; encTime += t3 - t2; count += result.size(); } } finally { is.close(); } System.out.printf( "Decoded %d msgs in %d ms (%.2f msgs/s)%n", count, decTime, 1000 * (double) count / (double) decTime); System.out.printf( "Encoded %d msgs in %d ms (%.2f msgs/s)%n", count, encTime, 1000 * (double) count / (double) encTime); } else throw new RuntimeException("Unknown PerfTest task: " + task); }
public static void main(String[] args) { TreeMap<String, ArrayList<String>> topicToQuestionMap = Utility.getTopicToQuestionMap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); JsonObject info = new JsonObject(); Gson gson = new GsonBuilder().disableHtmlEscaping().create(); for (Map.Entry<String, ArrayList<String>> entry : topicToQuestionMap.entrySet()) { String topic = entry.getKey(); ArrayList<String> questions = entry.getValue(); JsonObject quesToSol = new JsonObject(); for (String question : questions) { baos.reset(); question = question.split("\\.")[0]; Class cls = null; try { cls = Class.forName(topic + "." + question); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { Method method = cls.getMethod("main", String[].class); method.invoke(null, new Object[] {new String[] {}}); } catch (Exception e) { System.out.println("This is a helper class to be used by other programs."); } System.out.flush(); String solution = baos.toString(); quesToSol.addProperty(question, solution); } info.addProperty(topic, gson.toJson(quesToSol)); } System.setOut(old); System.out.println(info); try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE))) { writer.write(info.toString()); } catch (IOException e) { e.printStackTrace(); } }
/** * Checks for the next item. * * @return result of check * @throws IOException I/O exception */ public boolean more() throws IOException { if (cache == null) { out.write(4); send(id); cache = new ArrayList<byte[]>(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); while (in.read() > 0) { receive(in, os); cache.add(os.toByteArray()); os.reset(); } if (!ok()) throw new IOException(receive()); pos = 0; } if (pos < cache.size()) return true; cache = null; return false; }
/** * Performs decryption operation for the last time. * * <p>NOTE: For cipher feedback modes which does not perform special handling for the last few * blocks, this is essentially the same as <code>encrypt(...)</code>. Given most modes do not do * special handling, the default impl for this method is to simply call <code>decrypt(...)</code>. * * @param in the input buffer with the data to be decrypted * @param inOfs the offset in <code>cipher</code> * @param len the length of the input data * @param out the buffer for the decryption result * @param outOfs the offset in <code>plain</code> * @return the number of bytes placed into the <code>out</code> buffer */ int decryptFinal(byte[] in, int inOfs, int len, byte[] out, int outOfs) throws IllegalBlockSizeException, AEADBadTagException, ShortBufferException { if (len < tagLenBytes) { throw new AEADBadTagException("Input too short - need tag"); } if (out.length - outOfs < ((ibuffer.size() + len) - tagLenBytes)) { throw new ShortBufferException("Output buffer too small"); } processAAD(); if (len != 0) { ibuffer.write(in, inOfs, len); } // refresh 'in' to all buffered-up bytes in = ibuffer.toByteArray(); inOfs = 0; len = in.length; ibuffer.reset(); byte[] tag = new byte[tagLenBytes]; // get the trailing tag bytes from 'in' System.arraycopy(in, len - tagLenBytes, tag, 0, tagLenBytes); len -= tagLenBytes; if (len > 0) { doLastBlock(in, inOfs, len, out, outOfs, false); } byte[] lengthBlock = getLengthBlock(sizeOfAAD * 8, processed * 8); ghashAllToS.update(lengthBlock); byte[] s = ghashAllToS.digest(); byte[] sOut = new byte[s.length]; GCTR gctrForSToTag = new GCTR(embeddedCipher, this.preCounterBlock); gctrForSToTag.doFinal(s, 0, s.length, sOut, 0); for (int i = 0; i < tagLenBytes; i++) { if (tag[i] != sOut[i]) { throw new AEADBadTagException("Tag mismatch!"); } } return len; }
/** * Parses custom packet serialized by hessian marshaller. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Parser state. * @return Parsed message. * @throws IOException If packet parsing or deserialization failed. */ @Nullable private GridClientMessage parseCustomPacket(GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException { assert state.packetType() == PacketType.GRIDGAIN; assert state.packet() == null; ByteArrayOutputStream tmp = state.buffer(); int len = state.index(); while (buf.remaining() > 0) { byte b = buf.get(); if (len == 0) { tmp.write(b); if (tmp.size() == 4) { len = U.bytesToInt(tmp.toByteArray(), 0); tmp.reset(); if (len == 0) return PING_MESSAGE; else if (len < 0) throw new IOException( "Failed to parse incoming packet (invalid packet length) [ses=" + ses + ", len=" + len + ']'); state.index(len); } } else { tmp.write(b); if (tmp.size() == len) return marshaller.unmarshal(tmp.toByteArray()); } } return null; }
public void run() { String objRouter = applet.getParameter("name"); // No Internationalisation try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream outp = new DataOutputStream(byteStream); outp.writeInt(GenericConstants.ROUTER_PROPERTIES); outp.writeUTF(objRouter); outp.flush(); byte[] bytes = byteStream.toByteArray(); outp.close(); byteStream.reset(); byteStream.close(); byte[] data = GenericSession.getInstance().syncSend(bytes); if (data != null) { DataInputStream inp = new DataInputStream(new ByteArrayInputStream(data)); int reqId = inp.readInt(); if (reqId == GenericConstants.ROUTER_PROPERTIES) { int length = inp.readInt(); byte serverData[] = new byte[length]; inp.readFully(serverData); routerobject = NmsClientUtil.deSerializeVector(serverData); } init(); refresh(); super.setVisible(true); } /*init(); refresh(); super.setVisible(true);*/ else close(); } catch (Exception e) { // NmsClientUtil.err(NmsClientUtil.getFrame(app),"IO Error sending request to server. // "+e);//No Internationalisation } }
private String[] getOutputsFromSysOutRecorder() { List<String> returned = new ArrayList<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()))); out.reset(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { returned.add(line); } return returned.toArray(new String[0]); } catch (IOException e) { throw new IllegalStateException("Getting outputs failed.", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } }
/** * Convert a hex-encoded String to binary data * * @param str A String containing the encoded data * @return An array containing the binary data, or null if the string is invalid */ public static byte[] fromString(String str) { ByteArrayOutputStream bs = new ByteArrayOutputStream(); byte[] raw = str.getBytes(); for (int i = 0; i < raw.length; i++) { if (!Character.isWhitespace((char) raw[i])) bs.write(raw[i]); } byte[] in = bs.toByteArray(); if (in.length % 2 != 0) { return null; } bs.reset(); DataOutputStream ds = new DataOutputStream(bs); for (int i = 0; i < in.length; i += 2) { byte high = (byte) Base16.indexOf(Character.toUpperCase((char) in[i])); byte low = (byte) Base16.indexOf(Character.toUpperCase((char) in[i + 1])); try { ds.writeByte((high << 4) + low); } catch (IOException e) { } } return bs.toByteArray(); }
public static void testMiddleware() { rdfStream = new ByteArrayOutputStream(); Thread rdfThread = new Thread() { public void run() { File buildFile = new File("../rdfUtils/build.xml"); Project project = new Project(); project.setUserProperty("ant.file", buildFile.getAbsolutePath()); PrintStream ps = new PrintStream(rdfStream); try { project.fireBuildStarted(); DefaultLogger consoleLogger = new DefaultLogger(); consoleLogger.setErrorPrintStream(System.err); consoleLogger.setOutputPrintStream(ps); consoleLogger.setMessageOutputLevel(Project.MSG_INFO); project.addBuildListener(consoleLogger); project.init(); ProjectHelper projectHelper = ProjectHelper.getProjectHelper(); project.addReference("ant.projectHelper", projectHelper); projectHelper.parse(project, buildFile); project.executeTarget("run-rdfTest-nointeract"); project.fireBuildFinished(null); } catch (Exception e) { System.out.println(e); } } }; rdfThread.start(); System.out.println("RDF Module should be running, starting tests.."); try { long endTime = testStartTime + maxTestRunDuration; System.out.println("Started at " + testStartTime + " and running until " + endTime); while ((endTime > System.currentTimeMillis()) && rdfThread.isAlive()) { if (rdfStream.size() > 0) { String latestString = rdfStream.toString("UTF8"); System.out.println(latestString); if (latestString.contains("TestRDF Rate")) { String[] splited = latestString.split("\\s+"); RDFSent = Integer.parseInt(splited[8]); RDFRec = Integer.parseInt(splited[11]); System.out.println("RDF sent " + RDFSent + " and rec " + RDFRec); if (RDFSent > 1000) { // System.out.println("RDF min send/rec rate test passed"); RDFCheck = true; } } else if (latestString.contains("TestRDF Loss")) { String[] splited = latestString.split("\\s+"); RDFLossSent = Integer.parseInt(splited[7]); RDFLossRec = Integer.parseInt(splited[10]); System.out.println("RDFLoss sent " + RDFLossSent + " and rec " + RDFLossRec); rdfLossResult = splited[12]; System.out.println("overall loss result " + rdfLossResult); if (rdfLossResult.equals("OK")) { RDFLossCheck = true; // System.out.println("RDF packet loss test passed"); } } rdfStream.reset(); } } System.out.println("ending test" + endS); if (rdfThread.isAlive()) { rdfThread.interrupt(); } } catch (Exception e) { System.out.println(e); } try { if (RDFCheck) { testResults.write( "<testcase classname=\"RDF\" name=\"Sent\" status=\"" + RDFSent + "\"/>" + endS); testResults.write( "<testcase classname=\"RDF\" name=\"Received\" status=\"" + RDFRec + "\"/>" + endS); } else { testResults.write("<testcase classname=\"RDF\" name=\"Sent\">" + endS); testResults.write( " <failure type=\"Middleware Performanace, sent\"> " + RDFSent + " </failure>" + endS); testResults.write("</testcase>" + endS); testResults.write("<testcase classname=\"RDF\" name=\"Received\">" + endS); testResults.write( " <failure type=\"Middleware Performanace, received\"> " + RDFRec + " </failure>" + endS); testResults.write("</testcase>" + endS); } if (RDFLossCheck) { testResults.write( "<testcase classname=\"RDF\" name=\"Loss\" status=\"" + (RDFLossSent - RDFLossRec) + "\"/>" + endS); } else { testResults.write("<testcase classname=\"RDF\" name=\"Loss\">" + endS); testResults.write( " <failure type=\"Message loss \"> " + (RDFLossSent - RDFLossRec) + " </failure>" + endS); testResults.write("</testcase>" + endS); } } catch (Exception e) { System.out.println("error writing to file"); } }
/** Method to keep the connection alive with the name server */ public void run() { boolean connected = false; int ticket = 0; int serial = -1; int time = 1000; DatagramPacket inPack = new DatagramPacket(new byte[1024], 1024); DatagramPacket outPack = new DatagramPacket(new byte[1024], 1024); ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); DataInputStream inData; DataOutputStream outData = new DataOutputStream(outBuf); while (running) { if (!connected) { // Thoust ought Register thine self try { outBuf.reset(); outData.writeByte(0); outData.writeUTF(userName); outData.writeInt(portNum); outData.flush(); outPack.setData(outBuf.toByteArray()); nameServer.send(outPack); } catch (IOException e) { System.err.println("LeetActive: " + e); } } else { // Thoust ought Renew thine self try { outBuf.reset(); outData.writeByte(2); outData.writeInt(ticket); outData.flush(); outPack.setData(outBuf.toByteArray()); nameServer.send(outPack); } catch (IOException e) { System.err.println(e); } } // Now we will receive a packet... try { nameServer.receive(inPack); inData = new DataInputStream(new ByteArrayInputStream(inPack.getData())); byte type = inData.readByte(); if (type == 1) { // Twas a ticket packet try { ticket = inData.readInt(); if (ticket > -1) { // Make sure its not evil connected = true; } else { connected = false; } time = inData.readInt(); } catch (IOException e) { System.err.println(e); } } if (type == 5) { // Twas an update packet try { int s = inData.readInt(); if (s > serial) { // Make sure its not old serial = s; int size = inData.readInt(); ArrayList newList = new ArrayList(size); for (int x = 0; x < size; x++) { newList.add( new String( "" + inData.readUTF() + "@" + inData.readUTF() + ":" + inData.readInt())); } if (!newList.equals(hostList)) { hostList = newList; updated = true; } } } catch (IOException e) { System.err.println(e); } } } catch (SocketTimeoutException e) { // Server hates you connected = false; System.err.println(e); } catch (IOException e) { System.err.println(e); } try { // Take a nap sleep(time / 4); } catch (InterruptedException e) { } } }
/** * Parses memcache protocol message. * * @param ses Session. * @param buf Buffer containing not parsed bytes. * @param state Current parser state. * @return Parsed packet.s * @throws IOException If packet cannot be parsed. * @throws GridException If deserialization error occurred. */ @Nullable private GridClientMessage parseMemcachePacket( GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, GridException { assert state.packetType() == PacketType.MEMCACHE; assert state.packet() != null; assert state.packet() instanceof GridTcpRestPacket; GridTcpRestPacket req = (GridTcpRestPacket) state.packet(); ByteArrayOutputStream tmp = state.buffer(); int i = state.index(); while (buf.remaining() > 0) { byte b = buf.get(); if (i == 0) req.requestFlag(b); else if (i == 1) req.operationCode(b); else if (i == 2 || i == 3) { tmp.write(b); if (i == 3) { req.keyLength(U.bytesToShort(tmp.toByteArray(), 0)); tmp.reset(); } } else if (i == 4) req.extrasLength(b); else if (i >= 8 && i <= 11) { tmp.write(b); if (i == 11) { req.totalLength(U.bytesToInt(tmp.toByteArray(), 0)); tmp.reset(); } } else if (i >= 12 && i <= 15) { tmp.write(b); if (i == 15) { req.opaque(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN && i < HDR_LEN + req.extrasLength()) { tmp.write(b); if (i == HDR_LEN + req.extrasLength() - 1) { req.extras(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN + req.extrasLength() && i < HDR_LEN + req.extrasLength() + req.keyLength()) { tmp.write(b); if (i == HDR_LEN + req.extrasLength() + req.keyLength() - 1) { req.key(tmp.toByteArray()); tmp.reset(); } } else if (i >= HDR_LEN + req.extrasLength() + req.keyLength() && i < HDR_LEN + req.totalLength()) { tmp.write(b); if (i == HDR_LEN + req.totalLength() - 1) { req.value(tmp.toByteArray()); tmp.reset(); } } if (i == HDR_LEN + req.totalLength() - 1) // Assembled the packet. return assemble(ses, req); i++; } state.index(i); return null; }
public boolean authenticate( String[] mechs, final String realm, final String authzid, final String u, final String p) throws ProtocolException { synchronized (pr) { // authenticate method should be synchronized List<Response> v = new ArrayList<Response>(); String tag = null; Response r = null; boolean done = false; if (logger.isLoggable(Level.FINE)) { logger.fine("SASL Mechanisms:"); for (int i = 0; i < mechs.length; i++) logger.fine(" " + mechs[i]); logger.fine(""); } SaslClient sc; CallbackHandler cbh = new CallbackHandler() { public void handle(Callback[] callbacks) { if (logger.isLoggable(Level.FINE)) logger.fine("SASL callback length: " + callbacks.length); for (int i = 0; i < callbacks.length; i++) { if (logger.isLoggable(Level.FINE)) logger.fine("SASL callback " + i + ": " + callbacks[i]); if (callbacks[i] instanceof NameCallback) { NameCallback ncb = (NameCallback) callbacks[i]; ncb.setName(u); } else if (callbacks[i] instanceof PasswordCallback) { PasswordCallback pcb = (PasswordCallback) callbacks[i]; pcb.setPassword(p.toCharArray()); } else if (callbacks[i] instanceof RealmCallback) { RealmCallback rcb = (RealmCallback) callbacks[i]; rcb.setText(realm != null ? realm : rcb.getDefaultText()); } else if (callbacks[i] instanceof RealmChoiceCallback) { RealmChoiceCallback rcb = (RealmChoiceCallback) callbacks[i]; if (realm == null) rcb.setSelectedIndex(rcb.getDefaultChoice()); else { // need to find specified realm in list String[] choices = rcb.getChoices(); for (int k = 0; k < choices.length; k++) { if (choices[k].equals(realm)) { rcb.setSelectedIndex(k); break; } } } } } } }; try { sc = Sasl.createSaslClient(mechs, authzid, name, host, (Map) props, cbh); } catch (SaslException sex) { logger.log(Level.FINE, "Failed to create SASL client", sex); throw new UnsupportedOperationException(sex.getMessage(), sex); } if (sc == null) { logger.fine("No SASL support"); throw new UnsupportedOperationException("No SASL support"); } if (logger.isLoggable(Level.FINE)) logger.fine("SASL client " + sc.getMechanismName()); try { Argument args = new Argument(); args.writeAtom(sc.getMechanismName()); if (pr.hasCapability("SASL-IR") && sc.hasInitialResponse()) { String irs; byte[] ba = sc.evaluateChallenge(new byte[0]); if (ba.length > 0) { ba = BASE64EncoderStream.encode(ba); irs = ASCIIUtility.toString(ba, 0, ba.length); } else irs = "="; args.writeAtom(irs); } tag = pr.writeCommand("AUTHENTICATE", args); } catch (Exception ex) { logger.log(Level.FINE, "SASL AUTHENTICATE Exception", ex); return false; } OutputStream os = pr.getIMAPOutputStream(); // stream to IMAP server /* * Wrap a BASE64Encoder around a ByteArrayOutputstream * to craft b64 encoded username and password strings * * Note that the encoded bytes should be sent "as-is" to the * server, *not* as literals or quoted-strings. * * Also note that unlike the B64 definition in MIME, CRLFs * should *not* be inserted during the encoding process. So, I * use Integer.MAX_VALUE (0x7fffffff (> 1G)) as the bytesPerLine, * which should be sufficiently large ! */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] CRLF = {(byte) '\r', (byte) '\n'}; // Hack for Novell GroupWise XGWTRUSTEDAPP authentication mechanism // http://www.novell.com/developer/documentation/gwimap/? // page=/developer/documentation/gwimap/gwimpenu/data/al7te9j.html boolean isXGWTRUSTEDAPP = sc.getMechanismName().equals("XGWTRUSTEDAPP") && PropUtil.getBooleanProperty( props, "mail." + name + ".sasl.xgwtrustedapphack.enable", true); while (!done) { // loop till we are done try { r = pr.readResponse(); if (r.isContinuation()) { byte[] ba = null; if (!sc.isComplete()) { ba = r.readByteArray().getNewBytes(); if (ba.length > 0) ba = BASE64DecoderStream.decode(ba); if (logger.isLoggable(Level.FINE)) logger.fine("SASL challenge: " + ASCIIUtility.toString(ba, 0, ba.length) + " :"); ba = sc.evaluateChallenge(ba); } if (ba == null) { logger.fine("SASL no response"); os.write(CRLF); // write out empty line os.flush(); // flush the stream bos.reset(); // reset buffer } else { if (logger.isLoggable(Level.FINE)) logger.fine("SASL response: " + ASCIIUtility.toString(ba, 0, ba.length) + " :"); ba = BASE64EncoderStream.encode(ba); if (isXGWTRUSTEDAPP) bos.write(ASCIIUtility.getBytes("XGWTRUSTEDAPP ")); bos.write(ba); bos.write(CRLF); // CRLF termination os.write(bos.toByteArray()); // write out line os.flush(); // flush the stream bos.reset(); // reset buffer } } else if (r.isTagged() && r.getTag().equals(tag)) // Ah, our tagged response done = true; else if (r.isBYE()) // outta here done = true; else // hmm .. unsolicited response here ?! v.add(r); } catch (Exception ioex) { logger.log(Level.FINE, "SASL Exception", ioex); // convert this into a BYE response r = Response.byeResponse(ioex); done = true; // XXX - ultimately return true??? } } if (sc.isComplete() /*&& res.status == SUCCESS*/) { String qop = (String) sc.getNegotiatedProperty(Sasl.QOP); if (qop != null && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf"))) { // XXX - NOT SUPPORTED!!! logger.fine("SASL Mechanism requires integrity or confidentiality"); return false; } } /* Dispatch untagged responses. * NOTE: in our current upper level IMAP classes, we add the * responseHandler to the Protocol object only *after* the * connection has been authenticated. So, for now, the below * code really ends up being just a no-op. */ Response[] responses = v.toArray(new Response[v.size()]); pr.notifyResponseHandlers(responses); // Handle the final OK, NO, BAD or BYE response pr.handleResult(r); pr.setCapabilities(r); /* * If we're using the Novell Groupwise XGWTRUSTEDAPP mechanism * to run as a specified authorization ID, we have to issue a * LOGIN command to select the user we want to operate as. */ if (isXGWTRUSTEDAPP && authzid != null) { Argument args = new Argument(); args.writeString(authzid); responses = pr.command("LOGIN", args); // dispatch untagged responses pr.notifyResponseHandlers(responses); // Handle result of this command pr.handleResult(responses[responses.length - 1]); // If the response includes a CAPABILITY response code, process it pr.setCapabilities(responses[responses.length - 1]); } return true; } }
public void reset() { outputStream.reset(); writer.getBuffer().delete(0, writer.getBuffer().length()); }