public void run() { for (int i = 1; i <= number_of_msgs; i++) { try { Message msg = new Message(null, buf); if (oob) msg.setFlag(Message.Flag.OOB); if (dont_bundle) msg.setFlag(Message.Flag.DONT_BUNDLE); if (i > 0 && do_print > 0 && i % do_print == 0) System.out.println("-- sent " + i); Buffer buffer = writeMessage(msg); output_lock.lock(); // need to sync if we have more than 1 sender try { // msg.writeTo(output); output.writeInt(buffer.getLength()); output.write(buffer.getBuf(), buffer.getOffset(), buffer.getLength()); // output.flush(); } finally { output_lock.unlock(); } } catch (Exception e) { e.printStackTrace(); } } }
void sendMessages() throws Exception { if (num_threads > 1 && num_msgs % num_threads != 0) { System.err.println( "num_msgs (" + num_msgs + " ) has to be divisible by num_threads (" + num_threads + ")"); return; } System.out.println( "sending " + num_msgs + " messages (" + Util.printBytes(msg_size) + ") to " + remote + ": oob=" + oob + ", " + num_threads + " sender thread(s)"); ByteBuffer buf = ByteBuffer.allocate(Global.BYTE_SIZE + Global.LONG_SIZE).put(START).putLong(num_msgs); Message msg = new Message(null, buf.array()); // msg.writeTo(output); ExposedByteArrayOutputStream out_stream = new ExposedByteArrayOutputStream((int) (msg.size())); ExposedDataOutputStream dos = new ExposedDataOutputStream(out_stream); byte flags = 0; dos.writeShort(Version.version); // write the version if (msg.getDest() == null) flags += (byte) 2; dos.writeByte(flags); msg.writeTo(dos); Buffer buffer = new Buffer(out_stream.getRawBuffer(), 0, out_stream.size()); output_lock.lock(); // need to sync if we have more than 1 sender try { // msg.writeTo(output); output.writeInt(buffer.getLength()); output.write(buffer.getBuf(), buffer.getOffset(), buffer.getLength()); } finally { output_lock.unlock(); } int msgs_per_sender = num_msgs / num_threads; Sender[] senders = new Sender[num_threads]; for (int i = 0; i < senders.length; i++) senders[i] = new Sender(msgs_per_sender, msg_size, num_msgs / 10); for (Sender sender : senders) sender.start(); for (Sender sender : senders) sender.join(); output.flush(); System.out.println("done sending " + num_msgs + " to " + remote); }
public synchronized void write(Buffer buffer) throws IOException { long bufOffset = buffer.getOffset(); if (bufOffset == -1) { if (file.getFilePointer() != this.offset) { throw new IOException("Invalid offset: " + bufOffset); } } else { file.seek(bufOffset); } file.write(buffer.getBuffer(), 0, buffer.getLength()); this.offset += buffer.getLength(); }
// @Override @Override public int read() throws IOException { // TODO: how do we detect IOException? fillBuffer(); if (buffer.getLength() == 0 && buffer.isEOM()) // TODO: will always be // EOM if length is 0 return -1; final byte[] data = (byte[]) buffer.getData(); final int result = data[buffer.getOffset()] & 0xff; buffer.setOffset(buffer.getOffset() + 1); buffer.setLength(buffer.getLength() - 1); return result; }
private static void _testMessage(Message msg) throws Exception { Buffer buf = Util.messageToByteBuffer(msg); Message msg2 = Util.byteBufferToMessage(buf.getBuf(), buf.getOffset(), buf.getLength()); Assert.assertEquals(msg.getSrc(), msg2.getSrc()); Assert.assertEquals(msg.getDest(), msg2.getDest()); Assert.assertEquals(msg.getLength(), msg2.getLength()); }
public VideoTrack(PullSourceStream stream) throws ResourceUnavailableException { super(); this.stream = stream; // set format // read first frame to determine format final Buffer buffer = new Buffer(); readFrame(buffer); if (buffer.isDiscard() || buffer.isEOM()) throw new ResourceUnavailableException("Unable to read first frame"); // TODO: catch runtime exception too? // parse jpeg final java.awt.Image image; try { image = ImageIO.read( new ByteArrayInputStream( (byte[]) buffer.getData(), buffer.getOffset(), buffer.getLength())); } catch (IOException e) { logger.log(Level.WARNING, "" + e, e); throw new ResourceUnavailableException("Error reading image: " + e); } if (image == null) { logger.log(Level.WARNING, "Failed to read image (ImageIO.read returned null)."); throw new ResourceUnavailableException(); } if (frameContentType.equals("image/jpeg")) format = new JPEGFormat( new Dimension(image.getWidth(null), image.getHeight(null)), Format.NOT_SPECIFIED, Format.byteArray, -1.f, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED); else if (frameContentType.equals("image/gif")) format = new GIFFormat( new Dimension(image.getWidth(null), image.getHeight(null)), Format.NOT_SPECIFIED, Format.byteArray, -1.f); else if (frameContentType.equals("image/png")) format = new PNGFormat( new Dimension(image.getWidth(null), image.getHeight(null)), Format.NOT_SPECIFIED, Format.byteArray, -1.f); else throw new ResourceUnavailableException( "Unsupported frame content type: " + frameContentType); // TODO: this discards first image. save and return first time // readFrame is called. }
// @Override @Override public int read(byte[] b, int off, int len) throws IOException { // TODO: how do we detect IOException? fillBuffer(); if (buffer.getLength() == 0 && buffer.isEOM()) // TODO: will always be // EOM if length is 0 return -1; final byte[] data = (byte[]) buffer.getData(); int lengthToCopy = buffer.getLength() < len ? buffer.getLength() : len; System.arraycopy(data, buffer.getOffset(), b, off, lengthToCopy); buffer.setOffset(buffer.getOffset() + lengthToCopy); buffer.setLength(buffer.getLength() - lengthToCopy); return lengthToCopy; }
/** * Reads media data from this <tt>PullBufferStream</tt> into a specific <tt>Buffer</tt> with * blocking. * * @param buffer the <tt>Buffer</tt> in which media data is to be read from this * <tt>PullBufferStream</tt> * @throws IOException if anything goes wrong while reading media data from this * <tt>PullBufferStream</tt> into the specified <tt>buffer</tt> * @see javax.media.protocol.PullBufferStream#read(javax.media.Buffer) */ public void read(Buffer buffer) throws IOException { if (setThreadPriority) { setThreadPriority = false; setThreadPriority(); } Object data = buffer.getData(); int length = this.length; if (data instanceof byte[]) { if (((byte[]) data).length < length) data = null; } else data = null; if (data == null) { data = new byte[length]; buffer.setData(data); } int toRead = length; byte[] bytes = (byte[]) data; int offset = 0; buffer.setLength(0); while (toRead > 0) { int read; synchronized (this) { if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) read = audioRecord.read(bytes, offset, toRead); else break; } if (read < 0) { throw new IOException( AudioRecord.class.getName() + "#read(byte[], int, int) returned " + read); } else { buffer.setLength(buffer.getLength() + read); offset += read; toRead -= read; } } buffer.setOffset(0); // Apply software gain. if (gainControl != null) { BasicVolumeControl.applyGain(gainControl, bytes, buffer.getOffset(), buffer.getLength()); } }
private void fillBuffer() { if (buffer == null) { buffer = new Buffer(); buffer.setFormat(track.getFormat()); } do { if (buffer.isEOM()) return; if (buffer.getLength() > 0) return; // still have data in buffer // TODO: any fields to set? track.readFrame(buffer); logger.fine("Read buffer from track: " + buffer.getLength()); } while (buffer.isDiscard()); }
/** * Inserts the bytes written as header and puts the write pointer at the end of the stream. * * @throws IOException if write fails */ public void append() throws IOException { // append the top-level buffer super.byteAlign(); if (currentBuffer + 1 >= bufferList.size()) { // there is no buffer to append return; } Buffer append = bufferList.get(currentBuffer + 1); if (append.getLength() > 0) { if (currentBuffer >= 0) { bufferList.get(currentBuffer).add(append); } else { super.write(append.getBytes(), 0, append.getLength()); } } bufferList.remove(currentBuffer + 1); }
void add(Buffer append) { int appendLength = append.getLength(); int needed = len + appendLength; if (needed > buffer.length) { byte[] newBuffer = new byte[needed]; System.arraycopy(buffer, 0, newBuffer, 0, len); buffer = newBuffer; } System.arraycopy(append.getBytes(), 0, buffer, len, appendLength); len += appendLength; }
@Override public int process(Buffer input, Buffer output) { if (!checkInputBuffer(input)) { return BUFFER_PROCESSED_FAILED; } if (isEOM(input)) { propagateEOM(output); // TODO: what about data? can there be any? return BUFFER_PROCESSED_OK; } try { // TODO: this is very inefficient - it allocates a new byte array // (or more) every time final ByteArrayInputStream is = new ByteArrayInputStream((byte[]) input.getData(), input.getOffset(), input.getLength()); final BufferedImage image = ImageIO.read(is); is.close(); final Buffer b = ImageToBuffer.createBuffer(image, ((VideoFormat) outputFormat).getFrameRate()); output.setData(b.getData()); output.setOffset(b.getOffset()); output.setLength(b.getLength()); output.setFormat(b.getFormat()); // TODO: this is a bit hacky, this // format will be more specific // than the actual set output // format, because now we know what // ImageIO gave us for a // BufferedImage as far as pixel // masks, etc. return BUFFER_PROCESSED_OK; } catch (IOException e) { output.setDiscard(true); output.setLength(0); return BUFFER_PROCESSED_FAILED; } }
/** * Finds the next instance of the search string in the specified buffer. * * @param view The view * @param buffer The buffer * @param start Location where to start the search * @param firstTime See {@link * SearchMatcher#nextMatch(CharSequence,boolean,boolean,boolean,boolean)}. * @since jEdit 4.1pre7 */ public static boolean find( View view, Buffer buffer, int start, boolean firstTime, boolean reverse) throws Exception { EditBus.send(new PositionChanging(view.getEditPane())); SearchMatcher matcher = getSearchMatcher(); if (matcher == null) { view.getToolkit().beep(); return false; } CharSequence text; boolean startOfLine; boolean endOfLine; if (reverse) { text = new ReverseCharSequence(buffer.getSegment(0, start)); startOfLine = true; endOfLine = (buffer.getLineEndOffset(buffer.getLineOfOffset(start)) - 1 == start); } else { text = buffer.getSegment(start, buffer.getLength() - start); startOfLine = (buffer.getLineStartOffset(buffer.getLineOfOffset(start)) == start); endOfLine = true; } String noWordSep = buffer.getStringProperty("noWordSep"); matcher.setNoWordSep(noWordSep); SearchMatcher.Match match = matcher.nextMatch(text, startOfLine, endOfLine, firstTime, reverse); if (match != null) { jEdit.commitTemporary(buffer); view.setBuffer(buffer, true); JEditTextArea textArea = view.getTextArea(); if (reverse) { textArea.setSelection(new Selection.Range(start - match.end, start - match.start)); // make sure end of match is visible textArea.scrollTo(start - match.start, false); textArea.moveCaretPosition(start - match.end); } else { textArea.setSelection(new Selection.Range(start + match.start, start + match.end)); textArea.moveCaretPosition(start + match.end); // make sure start of match is visible textArea.scrollTo(start + match.start, false); } return true; } else return false; } // }}}
/** decode the buffer * */ public int process(Buffer inputBuffer, Buffer outputBuffer) { if (!checkInputBuffer(inputBuffer)) { return BUFFER_PROCESSED_FAILED; } if (isEOM(inputBuffer)) { propagateEOM(outputBuffer); return BUFFER_PROCESSED_OK; } Object outData = outputBuffer.getData(); outputBuffer.setData(inputBuffer.getData()); inputBuffer.setData(outData); outputBuffer.setLength(inputBuffer.getLength()); outputBuffer.setFormat(outputFormat); outputBuffer.setOffset(inputBuffer.getOffset()); return BUFFER_PROCESSED_OK; }
@Override public void read(Buffer buffer) throws IOException { pbs.read(buffer); // Remap the time stamps so it won't wrap around // while changing to a new file. if (buffer.getTimeStamp() != Buffer.TIME_UNKNOWN) { long diff = buffer.getTimeStamp() - lastTS; lastTS = buffer.getTimeStamp(); if (diff > 0) timeStamp += diff; buffer.setTimeStamp(timeStamp); } // If this track is to be used as the master time base, // we'll need to compute the master time based on this track. if (useAsMaster) { if (buffer.getFormat() instanceof AudioFormat) { AudioFormat af = (AudioFormat) buffer.getFormat(); masterAudioLen += buffer.getLength(); long t = af.computeDuration(masterAudioLen); if (t > 0) { masterTime = t; } else { masterTime = buffer.getTimeStamp(); } } else { masterTime = buffer.getTimeStamp(); } } if (buffer.isEOM()) { tInfo.done = true; if (!ds.handleEOM(tInfo)) { // This is not the last processor to be done. // We'll need to un-set the EOM flag. buffer.setEOM(false); buffer.setDiscard(true); } } }
@Override public void write(Buffer buffer) throws IOException { byte[] data = buffer.getBuffer(); int len = buffer.getLength(); int i = 0; while (i < len && pos < buf.length) { if (data[i] == '\r' || data[i] == '\n') { if (pos > 0) { try { writer.write(new MlsxEntry(new String(buf, 0, pos, StandardCharsets.UTF_8))); } catch (FTPException ex) { throw new IOException(); } } pos = 0; while (i < len && data[i] < ' ') ++i; } else { buf[pos++] = data[i++]; } } }
/** {@inheritDoc} */ @Override protected int doProcess(Buffer inBuffer, Buffer outBuffer) { byte[] inData = (byte[]) inBuffer.getData(); int inOffset = inBuffer.getOffset(); if (!VP8PayloadDescriptor.isValid(inData, inOffset)) { logger.warn("Invalid RTP/VP8 packet discarded."); outBuffer.setDiscard(true); return BUFFER_PROCESSED_FAILED; // XXX: FAILED or OK? } long inSeq = inBuffer.getSequenceNumber(); long inRtpTimestamp = inBuffer.getRtpTimeStamp(); int inPictureId = VP8PayloadDescriptor.getPictureId(inData, inOffset); boolean inMarker = (inBuffer.getFlags() & Buffer.FLAG_RTP_MARKER) != 0; boolean inIsStartOfFrame = VP8PayloadDescriptor.isStartOfFrame(inData, inOffset); int inLength = inBuffer.getLength(); int inPdSize = VP8PayloadDescriptor.getSize(inData, inOffset); int inPayloadLength = inLength - inPdSize; if (empty && lastSentSeq != -1 && seqNumComparator.compare(inSeq, lastSentSeq) != 1) { if (logger.isInfoEnabled()) logger.info("Discarding old packet (while empty) " + inSeq); outBuffer.setDiscard(true); return BUFFER_PROCESSED_OK; } if (!empty) { // if the incoming packet has a different PictureID or timestamp // than those of the current frame, then it belongs to a different // frame. if ((inPictureId != -1 && pictureId != -1 && inPictureId != pictureId) | (timestamp != -1 && inRtpTimestamp != -1 && inRtpTimestamp != timestamp)) { if (seqNumComparator.compare(inSeq, firstSeq) != 1) // inSeq <= firstSeq { // the packet belongs to a previous frame. discard it if (logger.isInfoEnabled()) logger.info("Discarding old packet " + inSeq); outBuffer.setDiscard(true); return BUFFER_PROCESSED_OK; } else // inSeq > firstSeq (and also presumably isSeq > lastSeq) { // the packet belongs to a subsequent frame (to the one // currently being held). Drop the current frame. if (logger.isInfoEnabled()) logger.info( "Discarding saved packets on arrival of" + " a packet for a subsequent frame: " + inSeq); // TODO: this would be the place to complain about the // not-well-received PictureID by sending a RTCP SLI or NACK. reinit(); } } } // a whole frame in a single packet. avoid the extra copy to // this.data and output it immediately. if (empty && inMarker && inIsStartOfFrame) { byte[] outData = validateByteArraySize(outBuffer, inPayloadLength, false); System.arraycopy(inData, inOffset + inPdSize, outData, 0, inPayloadLength); outBuffer.setOffset(0); outBuffer.setLength(inPayloadLength); outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp()); if (TRACE) logger.trace("Out PictureID=" + inPictureId); lastSentSeq = inSeq; return BUFFER_PROCESSED_OK; } // add to this.data Container container = free.poll(); if (container == null) container = new Container(); if (container.buf == null || container.buf.length < inPayloadLength) container.buf = new byte[inPayloadLength]; if (data.get(inSeq) != null) { if (logger.isInfoEnabled()) logger.info("(Probable) duplicate packet detected, discarding " + inSeq); outBuffer.setDiscard(true); return BUFFER_PROCESSED_OK; } System.arraycopy(inData, inOffset + inPdSize, container.buf, 0, inPayloadLength); container.len = inPayloadLength; data.put(inSeq, container); // update fields frameLength += inPayloadLength; if (firstSeq == -1 || (seqNumComparator.compare(firstSeq, inSeq) == 1)) firstSeq = inSeq; if (lastSeq == -1 || (seqNumComparator.compare(inSeq, lastSeq) == 1)) lastSeq = inSeq; if (empty) { // the first received packet for the current frame was just added empty = false; timestamp = inRtpTimestamp; pictureId = inPictureId; } if (inMarker) haveEnd = true; if (inIsStartOfFrame) haveStart = true; // check if we have a full frame if (frameComplete()) { byte[] outData = validateByteArraySize(outBuffer, frameLength, false); int ptr = 0; Container b; for (Map.Entry<Long, Container> entry : data.entrySet()) { b = entry.getValue(); System.arraycopy(b.buf, 0, outData, ptr, b.len); ptr += b.len; } outBuffer.setOffset(0); outBuffer.setLength(frameLength); outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp()); if (TRACE) logger.trace("Out PictureID=" + inPictureId); lastSentSeq = lastSeq; // prepare for the next frame reinit(); return BUFFER_PROCESSED_OK; } else { // frame not complete yet outBuffer.setDiscard(true); return OUTPUT_BUFFER_NOT_FILLED; } }
public boolean next(Buffer _buf) throws Exception { int i, j; switch (state) { case SSH_MSG_KEX_DH_GEX_GROUP: // byte SSH_MSG_KEX_DH_GEX_GROUP(31) // mpint p, safe prime // mpint g, generator for subgroup in GF (p) _buf.getInt(); _buf.getByte(); j = _buf.getByte(); if (j != SSH_MSG_KEX_DH_GEX_GROUP) { System.err.println("type: must be SSH_MSG_KEX_DH_GEX_GROUP " + j); return false; } p = _buf.getMPInt(); g = _buf.getMPInt(); dh.setP(p); dh.setG(g); // The client responds with: // byte SSH_MSG_KEX_DH_GEX_INIT(32) // mpint e <- g^x mod p // x is a random number (1 < x < (p-1)/2) e = dh.getE(); packet.reset(); buf.putByte((byte) SSH_MSG_KEX_DH_GEX_INIT); buf.putMPInt(e); session.write(packet); if (JSch.getLogger().isEnabled(Logger.INFO)) { JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEX_DH_GEX_INIT sent"); JSch.getLogger().log(Logger.INFO, "expecting SSH_MSG_KEX_DH_GEX_REPLY"); } state = SSH_MSG_KEX_DH_GEX_REPLY; return true; // break; case SSH_MSG_KEX_DH_GEX_REPLY: // The server responds with: // byte SSH_MSG_KEX_DH_GEX_REPLY(33) // string server public host key and certificates (K_S) // mpint f // string signature of H j = _buf.getInt(); j = _buf.getByte(); j = _buf.getByte(); if (j != SSH_MSG_KEX_DH_GEX_REPLY) { System.err.println("type: must be SSH_MSG_KEX_DH_GEX_REPLY " + j); return false; } K_S = _buf.getString(); byte[] f = _buf.getMPInt(); byte[] sig_of_H = _buf.getString(); dh.setF(f); dh.checkRange(); K = normalize(dh.getK()); // The hash H is computed as the HASH hash of the concatenation of the // following: // string V_C, the client's version string (CR and NL excluded) // string V_S, the server's version string (CR and NL excluded) // string I_C, the payload of the client's SSH_MSG_KEXINIT // string I_S, the payload of the server's SSH_MSG_KEXINIT // string K_S, the host key // uint32 min, minimal size in bits of an acceptable group // uint32 n, preferred size in bits of the group the server should send // uint32 max, maximal size in bits of an acceptable group // mpint p, safe prime // mpint g, generator for subgroup // mpint e, exchange value sent by the client // mpint f, exchange value sent by the server // mpint K, the shared secret // This value is called the exchange hash, and it is used to authenti- // cate the key exchange. buf.reset(); buf.putString(V_C); buf.putString(V_S); buf.putString(I_C); buf.putString(I_S); buf.putString(K_S); buf.putInt(min); buf.putInt(preferred); buf.putInt(max); buf.putMPInt(p); buf.putMPInt(g); buf.putMPInt(e); buf.putMPInt(f); buf.putMPInt(K); byte[] foo = new byte[buf.getLength()]; buf.getByte(foo); sha.update(foo, 0, foo.length); H = sha.digest(); // System.err.print("H -> "); dump(H, 0, H.length); i = 0; j = 0; j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); String alg = Util.byte2str(K_S, i, j); i += j; boolean result = verify(alg, K_S, i, sig_of_H); state = STATE_END; return result; } return false; }
public int process(Buffer inputBuffer, Buffer outputBuffer) { if (pendingFrames > 0) { // System.out.println("packetizing"); return BUFFER_PROCESSED_OK; } if (!checkInputBuffer(inputBuffer)) { return BUFFER_PROCESSED_FAILED; } if (isEOM(inputBuffer)) { propagateEOM(outputBuffer); return BUFFER_PROCESSED_OK; } int inpOffset = inputBuffer.getOffset(); int inpLength = inputBuffer.getLength(); int outLength = 0; int outOffset = 0; byte[] inpData = (byte[]) inputBuffer.getData(); byte[] outData = validateByteArraySize(outputBuffer, calculateOutputSize(inpData.length + historySize)); int historyLength = history.getLength(); byte[] historyData = validateByteArraySize(history, historySize); int framesNumber = calculateFramesNumber(inpData.length + historySize); if ((regions == null) || (regions.length < framesNumber + 1)) regions = new int[framesNumber + 1]; if ((regionsTypes == null) || (regionsTypes.length < framesNumber)) regionsTypes = new int[framesNumber]; if (historyLength != 0) { int bytesToCopy = (historyData.length - historyLength); if (bytesToCopy > inpLength) { bytesToCopy = inpLength; } System.arraycopy(inpData, inpOffset, historyData, historyLength, bytesToCopy); codecProcess( historyData, 0, outData, outOffset, historyLength + bytesToCopy, readBytes, writeBytes, frameNumber, regions, regionsTypes); if (readBytes[0] <= 0) { if (writeBytes[0] <= 0) { // System.err.println("Returning output buffer not filled"); return OUTPUT_BUFFER_NOT_FILLED; } else { updateOutput(outputBuffer, outputFormat, writeBytes[0], 0); // System.err.println("Returning OK"); return BUFFER_PROCESSED_OK; } } // System.out.println("1: "+inpLength+" "+readBytes[0]+" "+writeBytes[0]); outOffset += writeBytes[0]; outLength += writeBytes[0]; inpOffset += (readBytes[0] - historyLength); inpLength += (historyLength - readBytes[0]); } codecProcess( inpData, inpOffset, outData, outOffset, inpLength, readBytes, writeBytes, frameNumber, regions, regionsTypes); // System.out.println("2: "+inpLength+" "+readBytes[0]+" "+writeBytes[0]); // debug // for (int i=0; i<frameNumber[0];i++ ) { // System.out.println(i+" "+regions[i]+" - "+regions[i+1]+" type "+regionsTypes[i]); // } outLength += writeBytes[0]; inpOffset += readBytes[0]; inpLength -= readBytes[0]; System.arraycopy(inpData, inpOffset, historyData, 0, inpLength); history.setLength(inpLength); updateOutput(outputBuffer, outputFormat, outLength, 0); return BUFFER_PROCESSED_OK; }
public int process(Buffer inBuffer, Buffer outBuffer) { try { if (frameConverter == null) { frameConverter = new BufferToImage((VideoFormat) inBuffer.getFormat()); } // Convert the Buffer to an AWT Image. Image frameImage = frameConverter.createImage(inBuffer); // Derive a JAI image from the AWT image. PlanarImage jaiImage = JAI.create("AWTImage", frameImage); int index; boolean emboss = false; if (control != null) { index = control.getEffectIndex(); if (control.getEffectName().equals("None")) { outBuffer.setData(inBuffer.getData()); outBuffer.setFormat(inBuffer.getFormat()); outBuffer.setFlags(inBuffer.getFlags()); outBuffer.setLength(inBuffer.getLength()); return BUFFER_PROCESSED_OK; } if (control.getEffectName().equals("Emboss")) { emboss = true; // Special case } } else index = 0; if (kernels[index] == null) { kernels[index] = new KernelJAI(3, 3, matrices[index]); } jaiImage = JAI.create("convolve", jaiImage, kernels[index]); if (emboss) { // add 128 to make it brighter double[] constants = new double[] {128., 128., 128.}; ParameterBlock pb = new ParameterBlock(); pb.addSource(jaiImage); pb.add(constants); jaiImage = JAI.create("addconst", pb, null); } // Now convert the image to a buffer BufferedImage bim = jaiImage.getAsBufferedImage(); Buffer out = ImageToBuffer.createBuffer(bim, 15.F); if (out == null) { if (debug) { System.out.println("ImageToBuffer returned null"); } return BUFFER_PROCESSED_FAILED; } outBuffer.setData(out.getData()); outBuffer.setFormat(out.getFormat()); outBuffer.setFlags(out.getFlags()); outBuffer.setLength(out.getLength()); } catch (Exception e) { System.err.println(e); return BUFFER_PROCESSED_FAILED; } catch (Error e) { System.err.println(e); return BUFFER_PROCESSED_FAILED; } return BUFFER_PROCESSED_OK; }
/** * Replaces all occurrences of the search string with the replacement string. * * @param view The view * @param dontOpenChangedFiles Whether to open changed files or to autosave them quietly * @return the number of modified files */ public static boolean replaceAll(View view, boolean dontOpenChangedFiles) { // component that will parent any dialog boxes Component comp = SearchDialog.getSearchDialog(view); if (comp == null) comp = view; if (fileset.getFileCount(view) == 0) { GUIUtilities.error(comp, "empty-fileset", null); return false; } record(view, "replaceAll(view)", true, true); view.showWaitCursor(); boolean smartCaseReplace = getSmartCaseReplace(); int fileCount = 0; int occurCount = 0; try { SearchMatcher matcher = getSearchMatcher(); if (matcher == null) return false; initReplace(); String path = fileset.getFirstFile(view); loop: while (path != null) { Buffer buffer = jEdit.openTemporary(view, null, path, false); /* this is stupid and misleading. * but 'path' is not used anywhere except * the above line, and if this is done * after the 'continue', then we will * either hang, or be forced to duplicate * it inside the buffer == null, or add * a 'finally' clause. you decide which one's * worse. */ path = fileset.getNextFile(view, path); if (buffer == null) continue loop; // Wait for buffer to finish loading if (buffer.isPerformingIO()) VFSManager.waitForRequests(); if (!buffer.isEditable()) continue loop; // Leave buffer in a consistent state if // an error occurs int retVal = 0; try { buffer.beginCompoundEdit(); retVal = _replace(view, buffer, matcher, 0, buffer.getLength(), smartCaseReplace); } finally { buffer.endCompoundEdit(); } if (retVal != 0) { fileCount++; occurCount += retVal; if (dontOpenChangedFiles) { buffer.save(null, null); } else { jEdit.commitTemporary(buffer); jEdit.getBufferSetManager().addBuffer(view, buffer); } } } } catch (Exception e) { handleError(comp, e); } finally { view.hideWaitCursor(); } /* Don't do this when playing a macro, cos it's annoying */ if (!BeanShell.isScriptRunning()) { Object[] args = {Integer.valueOf(occurCount), Integer.valueOf(fileCount)}; view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.replace-all", args)); if (occurCount == 0) view.getToolkit().beep(); } return (fileCount != 0); } // }}}
/** Returns the length of the input. */ public int getLength() { return buffer.getLength(); }
/** * Finds the next occurrence of the search string. * * @param view The view * @return True if the operation was successful, false otherwise */ public static boolean find(View view) { // component that will parent any dialog boxes Component comp = SearchDialog.getSearchDialog(view); if (comp == null || !comp.isShowing()) comp = view; String path = fileset.getNextFile(view, null); if (path == null) { GUIUtilities.error(comp, "empty-fileset", null); return false; } try { view.showWaitCursor(); SearchMatcher matcher = getSearchMatcher(); if (matcher == null) { view.getToolkit().beep(); return false; } record(view, "find(view)", false, true); boolean repeat = false; loop: for (; ; ) { while (path != null) { Buffer buffer = jEdit.openTemporary(view, null, path, false); /* this is stupid and misleading. * but 'path' is not used anywhere except * the above line, and if this is done * after the 'continue', then we will * either hang, or be forced to duplicate * it inside the buffer == null, or add * a 'finally' clause. you decide which one's * worse. */ if (reverse) { path = fileset.getPrevFile(view, path); } else { path = fileset.getNextFile(view, path); } if (buffer == null) continue loop; // Wait for the buffer to load if (!buffer.isLoaded()) VFSManager.waitForRequests(); int start; if (view.getBuffer() == buffer && !repeat) { JEditTextArea textArea = view.getTextArea(); Selection s = textArea.getSelectionAtOffset(textArea.getCaretPosition()); if (s == null) start = textArea.getCaretPosition(); else if (reverse) start = s.getStart(); else start = s.getEnd(); } else if (reverse) start = buffer.getLength(); else start = 0; if (find(view, buffer, start, repeat, reverse)) return true; } if (repeat) { if (!BeanShell.isScriptRunning()) { view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.search-not-found")); view.getToolkit().beep(); } return false; } boolean restart; // if auto wrap is on, always restart search. // if auto wrap is off, and we're called from // a macro, stop search. If we're called // interactively, ask the user what to do. if (wrap) { if (!BeanShell.isScriptRunning()) { view.getStatus().setMessageAndClear(jEdit.getProperty("view.status.auto-wrap")); // beep if beep property set if (jEdit.getBooleanProperty("search.beepOnSearchAutoWrap")) { view.getToolkit().beep(); } } restart = true; } else if (BeanShell.isScriptRunning()) { restart = false; } else { Integer[] args = {Integer.valueOf(reverse ? 1 : 0)}; int result = GUIUtilities.confirm( comp, "keepsearching", args, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); restart = (result == JOptionPane.YES_OPTION); } if (restart) { // start search from beginning path = fileset.getFirstFile(view); repeat = true; } else break loop; } } catch (Exception e) { handleError(comp, e); } finally { view.hideWaitCursor(); } return false; } // }}}