code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
protected PasswordAuthentication getPasswordAuthentication() {
// Don't worry, this is just a hack to figure out if we were able
// to set this Authenticator through the setDefault method.
if (!sInitialized && MAGIC.equals(getRequestingScheme()) && getRequestingPort() == FOURTYTWO) {
... | java |
public PasswordAuthentication registerPasswordAuthentication(URL pURL, PasswordAuthentication pPA) {
return registerPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL),
pURL.getPort(),
pURL.getProtocol(),
null, // Prompt/Realm
BASIC,
... | java |
public PasswordAuthentication registerPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme, PasswordAuthentication pPA) {
/*
System.err.println("registerPasswordAuthentication");
System.err.println(pAddress);
System.err.println(pPort... | java |
public PasswordAuthentication unregisterPasswordAuthentication(URL pURL) {
return unregisterPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), pURL.getPort(), pURL.getProtocol(), null, BASIC);
} | java |
public PasswordAuthentication unregisterPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme) {
return passwordAuthentications.remove(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme));
} | java |
@InitParam(name = "accept-mappings-file")
public void setAcceptMappingsFile(String pPropertiesFile) throws ServletConfigException {
// NOTE: Format is:
// <agent-name>=<reg-exp>
// <agent-name>.accept=<http-accept-header>
Properties mappings = new Properties();
try {
... | java |
public int doEndTag() throws JspException {
// Trim
String trimmed = truncateWS(bodyContent.getString());
try {
// Print trimmed content
//pageContext.getOut().print("<!--TWS-->\n");
pageContext.getOut().print(trimmed);
//pageContext.getOut(... | java |
private static String truncateWS(String pStr) {
char[] chars = pStr.toCharArray();
int count = 0;
boolean lastWasWS = true; // Avoids leading WS
for (int i = 0; i < chars.length; i++) {
if (!Character.isWhitespace(chars[i])) {
// if char is not WS, jus... | java |
private ImageServletResponse createImageServletResponse(final ServletRequest pRequest, final ServletResponse pResponse) {
if (pResponse instanceof ImageServletResponseImpl) {
ImageServletResponseImpl response = (ImageServletResponseImpl) pResponse;
// response.setRequest(pRequest);
... | java |
protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
// Get angle
double ang = getAngle(pRequest);
// Get bounds
Rectangle2D rect = getBounds(pRequest, pImage, ang);
int width = (int) rect.getWidth();
in... | java |
private double getAngle(ServletRequest pReq) {
double angle = 0.0;
String str = pReq.getParameter(PARAM_ANGLE);
if (!StringUtil.isEmpty(str)) {
angle = Double.parseDouble(str);
// Convert to radians, if needed
str = pReq.getParameter(PARAM_ANGLE_UNITS)... | java |
private Rectangle2D getBounds(ServletRequest pReq, BufferedImage pImage,
double pAng) {
// Get dimensions of original image
int width = pImage.getWidth(); // loads the image
int height = pImage.getHeight();
// Test if we want to crop image (defaul... | java |
void initIRGB(int[] pTemp) {
final int x = (1 << TRUNCBITS); // 8 the size of 1 Dimension of each quantized cell
final int xsqr = 1 << (TRUNCBITS * 2); // 64 - twice the smallest step size vale of quantized colors
final int xsqr2 = xsqr + xsqr;
for (int i = 0; i < numColors;... | java |
public static Class unwrapType(Class pType) {
if (pType == Boolean.class) {
return Boolean.TYPE;
}
else if (pType == Byte.class) {
return Byte.TYPE;
}
else if (pType == Character.class) {
return Character.TYPE;
}
else ... | java |
private static boolean canRead(final DataInput pInput, final boolean pReset) {
long pos = FREE_SID;
if (pReset) {
try {
if (pInput instanceof InputStream && ((InputStream) pInput).markSupported()) {
((InputStream) pInput).mark(8);
}
... | java |
private SIdChain getSIdChain(final int pSId, final long pStreamSize) throws IOException {
SIdChain chain = new SIdChain();
int[] sat = isShortStream(pStreamSize) ? shortSAT : SAT;
int sid = pSId;
while (sid != END_OF_CHAIN_SID && sid != FREE_SID) {
chain.addSID(sid);... | java |
private void seekToSId(final int pSId, final long pStreamSize) throws IOException {
long pos;
if (isShortStream(pStreamSize)) {
// The short stream is not continuous...
Entry root = getRootEntry();
if (shortStreamSIdChain == null) {
shortStream... | java |
protected Object initPropertyValue(String pValue, String pType, String pFormat) throws ClassNotFoundException {
// System.out.println("pValue=" + pValue + " pType=" + pType
// + " pFormat=" + pFormat);
// No value to convert
if (pValue == null) {
return null;
}
/... | java |
private Object createInstance(Class pClass, Object pParam) {
Object value;
try {
// Create param and argument arrays
Class[] param = { pParam.getClass() };
Object[] arg = { pParam };
// Get constructor
Constructor constructor = pClass.getDeclaredConstructor(param);
... | java |
private Object invokeStaticMethod(Class pClass, String pMethod, Object pParam) {
Object value = null;
try {
// Create param and argument arrays
Class[] param = { pParam.getClass() };
Object[] arg = { pParam };
// Get method
// *** If more than one such method is fou... | java |
public synchronized String setPropertyFormat(String pKey, String pFormat) {
// Insert format
return StringUtil.valueOf(mFormats.put(pKey, pFormat));
} | java |
private static void insertElement(Document pDocument, String pName, Object pValue, String pFormat) {
// Get names of all elements we need
String[] names = StringUtil.toStringArray(pName, ".");
// Get value formatted as string
String value = null;
if (pValue != null) {
// ---
... | java |
public int doEndTag() throws JspException {
// Get body content (trim is CRUCIAL, as some XML parsers are picky...)
String body = bodyContent.getString().trim();
// Do transformation
transform(new StreamSource(new ByteArrayInputStream(body.getBytes())));
return super.doE... | java |
public void transform(Source pIn) throws JspException {
try {
// Create transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(getSource(mStylesheetURI));
// Store temporary output in a bytearray, as the transformer w... | java |
private StreamSource getSource(String pURI)
throws IOException, MalformedURLException {
if (pURI != null && pURI.indexOf("://") < 0) {
// If local, get as stream
return new StreamSource(getResourceAsStream(pURI));
}
// ...else, create from URI string
... | java |
private static BufferedImage createSolid(BufferedImage pOriginal, Color pBackground) {
// Create a temporary image of same dimension and type
BufferedImage solid = new BufferedImage(pOriginal.getColorModel(), pOriginal.copyData(null), pOriginal.isAlphaPremultiplied(), null);
Graphics2D g = so... | java |
private static void applyAlpha(BufferedImage pImage, BufferedImage pAlpha) {
// Apply alpha as transparency, using threshold of 25%
for (int y = 0; y < pAlpha.getHeight(); y++) {
for (int x = 0; x < pAlpha.getWidth(); x++) {
// Get alpha component of pixel, if less than... | java |
@Override
public byte[] toByteArray() {
byte newBuf[] = new byte[count];
System.arraycopy(buf, 0, newBuf, 0, count);
return newBuf;
} | java |
public void writeHeadersTo(final CacheResponse pResponse) {
String[] headers = getHeaderNames();
for (String header : headers) {
// HACK...
// Strip away internal headers
if (HTTPCache.HEADER_CACHED_TIME.equals(header)) {
continue;
}... | java |
public void writeContentsTo(final OutputStream pStream) throws IOException {
if (content == null) {
throw new IOException("Cache is null, no content to write.");
}
content.writeTo(pStream);
} | java |
public String[] getHeaderNames() {
Set<String> headers = this.headers.keySet();
return headers.toArray(new String[headers.size()]);
} | java |
public Path2D path() throws IOException {
List<List<AdobePathSegment>> subPaths = new ArrayList<List<AdobePathSegment>>();
List<AdobePathSegment> currentPath = null;
int currentPathLength = 0;
AdobePathSegment segment;
while ((segment = nextSegment()) != null) {
if ... | java |
private int getFontStyle(String pStyle) {
if (pStyle == null || StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_PLAIN)) {
return Font.PLAIN;
}
// Try to find bold/italic
int style = Font.PLAIN;
if (StringUtil.containsIgnoreCase(pStyle, FONT_STYLE_BOLD)) {
... | java |
private double getAngle(ServletRequest pRequest) {
// Get angle
double angle = ServletUtil.getDoubleParameter(pRequest, PARAM_TEXT_ROTATION, 0.0);
// Convert to radians, if needed
String units = pRequest.getParameter(PARAM_TEXT_ROTATION_UNITS);
if (!StringUtil.isEmpty(unit... | java |
public final String getName() {
switch (type) {
case ServletConfig:
return servletConfig.getServletName();
case FilterConfig:
return filterConfig.getFilterName();
case ServletContext:
return servletContext.getServletConte... | java |
public final ServletContext getServletContext() {
switch (type) {
case ServletConfig:
return servletConfig.getServletContext();
case FilterConfig:
return filterConfig.getServletContext();
case ServletContext:
return servl... | java |
protected int fill() throws IOException {
buffer.clear();
int read = decoder.decode(in, buffer);
// TODO: Enforce this in test case, leave here to aid debugging
if (read > buffer.capacity()) {
throw new AssertionError(
String.format(
... | java |
public void logDebug(String message, Exception exception) {
if (!(logDebug || globalLog.logDebug))
return;
if (debugLog != null)
log(debugLog, "DEBUG", owner, message, exception);
else
log(globalLog.debugLog, "DEBUG", owner, message, exception);
... | java |
public void logWarning(String message, Exception exception) {
if (!(logWarning || globalLog.logWarning))
return;
if (warningLog != null)
log(warningLog, "WARNING", owner, message, exception);
else
log(globalLog.warningLog, "WARNING", owner, message, e... | java |
public void logError(String message, Exception exception) {
if (!(logError || globalLog.logError))
return;
if (errorLog != null)
log(errorLog, "ERROR", owner, message, exception);
else
log(globalLog.errorLog, "ERROR", owner, message, exception);
... | java |
public void logInfo(String message, Exception exception) {
if (!(logInfo || globalLog.logInfo))
return;
if (infoLog != null)
log(infoLog, "INFO", owner, message, exception);
else
log(globalLog.infoLog, "INFO", owner, message, exception);
} | java |
private static OutputStream getStream(String name) throws IOException {
OutputStream os = null;
synchronized (streamCache) {
if ((os = (OutputStream) streamCache.get(name)) != null)
return os;
os = new FileOutputStream(name, true);
strea... | java |
private static void log(PrintStream ps, String header,
String owner, String message, Exception ex) {
// Only allow one instance to print to the given stream.
synchronized (ps) {
// Create output stream for logging
LogStream logStream = new LogStr... | java |
public final Point getHotSpot(final int pImageIndex) throws IOException {
DirectoryEntry.CUREntry entry = (DirectoryEntry.CUREntry) getEntry(pImageIndex);
return entry.getHotspot();
} | java |
public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (StringUtil.isEmpty(pString))
return null;
TimeFormat format;
try {
if (pFormat == null) {
// Use system default format
... | java |
static Entry readEntry(final DataInput pInput) throws IOException {
Entry p = new Entry();
p.read(pInput);
return p;
} | java |
private void read(final DataInput pInput) throws IOException {
byte[] bytes = new byte[64];
pInput.readFully(bytes);
// NOTE: Length is in bytes, including the null-terminator...
int nameLength = pInput.readShort();
name = new String(bytes, 0, nameLength - 2, Charset.forNa... | java |
public static Path2D readPath(final ImageInputStream stream) throws IOException {
notNull(stream, "stream");
int magic = readMagic(stream);
if (magic == PSD.RESOURCE_TYPE) {
// This is a PSD Image Resource Block, we can parse directly
return buildPathFromPhotoshopResour... | java |
public static BufferedImage applyClippingPath(final Shape clip, final BufferedImage image) {
return applyClippingPath(clip, notNull(image, "image"), new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB));
} | java |
public static BufferedImage readClipped(final ImageInputStream stream) throws IOException {
Shape clip = readPath(stream);
stream.seek(0);
BufferedImage image = ImageIO.read(stream);
if (clip == null) {
return image;
}
return applyClippingPath(clip, image);... | java |
protected void service(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException {
// Sanity check configuration
if (remoteServer == null) {
log(MESSAGE_REMOTE_SERVER_NOT_CONFIGURED);
pResponse.sendError(HttpServletResponse.SC_INTERNAL_S... | java |
private String createRemoteRequestURI(HttpServletRequest pRequest) {
StringBuilder requestURI = new StringBuilder(remotePath);
requestURI.append(pRequest.getPathInfo());
if (!StringUtil.isEmpty(pRequest.getQueryString())) {
requestURI.append("?");
requestURI.append... | java |
public void setExpiryTime(long pExpiryTime) {
long oldEexpiryTime = expiryTime;
expiryTime = pExpiryTime;
if (expiryTime < oldEexpiryTime) {
// Expire now
nextExpiryTime = 0;
removeExpiredEntries();
}
} | java |
private synchronized void removeExpiredEntriesSynced(long pTime) {
if (pTime > nextExpiryTime) {
////
long next = Long.MAX_VALUE;
nextExpiryTime = next; // Avoid multiple runs...
for (Iterator<Entry<K, V>> iterator = new EntryIterator(); iterator.hasNext();) ... | java |
static void bitRotateCW(final byte[] pSrc, int pSrcPos, int pSrcStep,
final byte[] pDst, int pDstPos, int pDstStep) {
int idx = pSrcPos;
int lonyb;
int hinyb;
long lo = 0;
long hi = 0;
for (int i = 0; i < 8; i++) {
lonyb = pSrc[id... | java |
public static void readPixels(DataInput in, float[] data, int numpixels) throws IOException {
byte[] rgbe = new byte[4];
float[] rgb = new float[3];
int offset = 0;
while (numpixels-- > 0) {
in.readFully(rgbe);
rgbe2float(rgb, rgbe, 0);
data[offset+... | java |
public static void float2rgbe(byte[] rgbe, float red, float green, float blue) {
float v;
int e;
v = red;
if (green > v) {
v = green;
}
if (blue > v) {
v = blue;
}
if (v < 1e-32f) {
rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3]... | java |
protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
// Get crop coordinates
int x = ServletUtil.getIntParameter(pRequest, PARAM_CROP_X, -1);
int y = ServletUtil.getIntParameter(pRequest, PARAM_CROP_Y, -1);
int width = Serv... | java |
private static String hashFile(final File file, final int pieceSize)
throws InterruptedException, IOException {
return hashFiles(Collections.singletonList(file), pieceSize);
} | java |
public static PeerMessage parse(ByteBuffer buffer, TorrentInfo torrent)
throws ParseException {
int length = buffer.getInt();
if (length == 0) {
return KeepAliveMessage.parse(buffer, torrent);
} else if (length != buffer.remaining()) {
throw new ParseException("Message size did not mat... | java |
private void serveError(Status status, String error, RequestHandler requestHandler) throws IOException {
this.serveError(status, HTTPTrackerErrorMessage.craft(error), requestHandler);
} | java |
private void serveError(Status status, ErrorMessage.FailureReason reason, RequestHandler requestHandler) throws IOException {
this.serveError(status, reason.getMessage(), requestHandler);
} | java |
protected String formatAnnounceEvent(
AnnounceRequestMessage.RequestEvent event) {
return AnnounceRequestMessage.RequestEvent.NONE.equals(event)
? ""
: String.format(" %s", event.name());
} | java |
protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents, String hexInfoHash) throws AnnounceException {
if (message instanceof ErrorMessage) {
ErrorMessage error = (ErrorMessage) message;
throw new AnnounceException(error.... | java |
protected void fireAnnounceResponseEvent(int complete, int incomplete, int interval, String hexInfoHash) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleAnnounceResponse(interval, complete, incomplete, hexInfoHash);
}
} | java |
protected void fireDiscoveredPeersEvent(List<Peer> peers, String hexInfoHash) {
for (AnnounceResponseListener listener : this.listeners) {
listener.handleDiscoveredPeers(peers, hexInfoHash);
}
} | java |
@Override
public void finish() throws IOException {
try {
myLock.writeLock().lock();
logger.debug("Closing file channel to " + this.current.getName() +
" (download complete).");
if (this.channel.isOpen()) {
this.channel.force(true);
}
// Nothing more to do if w... | java |
public static HTTPAnnounceResponseMessage craft(int interval,
int complete, int incomplete,
List<Peer> peers, String hexInfoHash) throws IOException, UnsupportedEncodingException {
Map<String, BEValue> response = new... | java |
private List<FileOffset> select(long offset, long length) {
if (offset + length > this.size) {
throw new IllegalArgumentException("Buffer overrun (" +
offset + " + " + length + " > " + this.size + ") !");
}
List<FileOffset> selected = new LinkedList<FileOffset>();
long bytes = 0;
... | java |
@Override
protected void handleTrackerAnnounceResponse(TrackerMessage message,
boolean inhibitEvents, String hexInfoHash) throws AnnounceException {
this.validateTrackerResponse(message);
super.handleTrackerAnnounceResponse(message, inhibitEvents, hexInfoHash);
... | java |
@Override
protected void close() {
this.stop = true;
// Close the socket to force blocking operations to return.
if (this.socket != null && !this.socket.isClosed()) {
this.socket.close();
}
} | java |
private void validateTrackerResponse(TrackerMessage message)
throws AnnounceException {
if (message instanceof ErrorMessage) {
throw new AnnounceException(((ErrorMessage) message).getReason());
}
if (message instanceof UDPTrackerMessage &&
(((UDPTrackerMessage) message).getTrans... | java |
private void handleTrackerConnectResponse(TrackerMessage message)
throws AnnounceException {
this.validateTrackerResponse(message);
if (!(message instanceof ConnectionResponseMessage)) {
throw new AnnounceException("Unexpected tracker message type " +
message.getType().name() + "!... | java |
private void send(ByteBuffer data) {
try {
this.socket.send(new DatagramPacket(
data.array(),
data.capacity(),
this.address));
} catch (IOException ioe) {
logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage());
... | java |
private ByteBuffer recv(int attempt)
throws IOException, SocketException, SocketTimeoutException {
int timeout = UDP_BASE_TIMEOUT_SECONDS * (int) Math.pow(2, attempt);
logger.trace("Setting receive timeout to {}s for attempt {}...",
timeout, attempt);
this.socket.setSoTimeout(timeout *... | java |
public String getString(String encoding) throws InvalidBEncodingException {
try {
return new String(this.getBytes(), encoding);
} catch (ClassCastException cce) {
throw new InvalidBEncodingException(cce.toString());
} catch (UnsupportedEncodingException uee) {
throw new InternalError(uee.t... | java |
public Number getNumber() throws InvalidBEncodingException {
try {
return (Number) this.value;
} catch (ClassCastException cce) {
throw new InvalidBEncodingException(cce.toString());
}
} | java |
@SuppressWarnings("unchecked")
public List<BEValue> getList() throws InvalidBEncodingException {
if (this.value instanceof ArrayList) {
return (ArrayList<BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Excepted List<BEvalue> !");
}
} | java |
@SuppressWarnings("unchecked")
public Map<String, BEValue> getMap() throws InvalidBEncodingException {
if (this.value instanceof HashMap) {
return (Map<String, BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Expected Map<String, BEValue> !");
}
} | java |
public void start(final boolean startPeerCleaningThread) throws IOException {
logger.info("Starting BitTorrent tracker on {}...",
getAnnounceUrl());
connection = new SocketConnection(new ContainerServer(myTrackerServiceContainer));
List<SocketAddress> tries = new ArrayList<SocketAddress>() {{
... | java |
public void announce(final AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents, final AnnounceableInformation torrentInfo, final List<Peer> adresses) throws AnnounceException {
logAnnounceRequest(event, torrentInfo);
final List<HTTPTrackerMessage> trackerResponses = new Arra... | java |
private HTTPAnnounceRequestMessage buildAnnounceRequest(
AnnounceRequestMessage.RequestEvent event, AnnounceableInformation torrentInfo, Peer peer)
throws IOException,
MessageValidationException {
// Build announce request message
final long uploaded = torrentInfo.getUploaded();
... | java |
public URL buildAnnounceURL(URL trackerAnnounceURL)
throws UnsupportedEncodingException, MalformedURLException {
String base = trackerAnnounceURL.toString();
StringBuilder url = new StringBuilder(base);
url.append(base.contains("?") ? "&" : "?")
.append("info_hash=")
.appen... | java |
public synchronized void add(long count) {
this.bytes += count;
if (this.reset == 0) {
this.reset = System.currentTimeMillis();
}
this.last = System.currentTimeMillis();
} | java |
public byte[] getRawIp() {
final InetAddress address = this.address.getAddress();
if (address == null) return null;
return address.getAddress();
} | java |
public static void main(String[] args) {
BasicConfigurator.configure(new ConsoleAppender(
new PatternLayout("%d [%-25t] %-5p: %m%n")));
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option help = parser.addBooleanOption('h', "help");
CmdLineParser.Option port = parser.addIntegerOption('p', "port... | java |
public static void main(String[] args) {
BasicConfigurator.configure(new ConsoleAppender(
new PatternLayout("%d [%-25t] %-5p: %m%n")));
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option help = parser.addBooleanOption('h', "help");
CmdLineParser.Option output = parser.addStrin... | java |
public Piece getPiece(int index) {
if (this.pieces == null) {
throw new IllegalStateException("Torrent not initialized yet.");
}
if (index >= this.pieces.length) {
throw new IllegalArgumentException("Invalid piece index!");
}
return this.pieces[index];
} | java |
public synchronized void markCompleted(Piece piece) {
if (this.completedPieces.get(piece.getIndex())) {
return;
}
// A completed piece means that's that much data left to download for
// this torrent.
myTorrentStatistic.addLeft(-piece.size());
this.completedPieces.set(piece.getIndex());
... | java |
public void start(final URI defaultTrackerURI, final AnnounceResponseListener listener, final Peer[] peers, final int announceInterval) {
myAnnounceInterval = announceInterval;
myPeers.addAll(Arrays.asList(peers));
if (defaultTrackerURI != null) {
try {
myDefaultTracker = myTrackerClientFactor... | java |
public void setAnnounceInterval(int announceInterval) {
if (announceInterval <= 0) {
this.stop(true);
return;
}
if (this.myAnnounceInterval == announceInterval) {
return;
}
logger.trace("Setting announce interval to {}s per tracker request.",
announceInterval);
th... | java |
public TrackerClient getCurrentTrackerClient(AnnounceableInformation torrent) {
final URI uri = getURIForTorrent(torrent);
if (uri == null) return null;
return this.clients.get(uri.toString());
} | java |
public static BEValue bdecode(ByteBuffer data) throws IOException {
return BDecoder.bdecode(new ByteArrayInputStream(data.array()));
} | java |
public BEValue bdecode() throws IOException {
if (this.getNextIndicator() == -1)
return null;
if (this.indicator >= '0' && this.indicator <= '9')
return this.bdecodeBytes();
else if (this.indicator == 'i')
return this.bdecodeNumber();
else if (this.indicator == 'l')
return this.... | java |
public BEValue bdecodeBytes() throws IOException {
int c = this.getNextIndicator();
int num = c - '0';
if (num < 0 || num > 9)
throw new InvalidBEncodingException("Number expected, not '"
+ (char) c + "'");
this.indicator = 0;
c = this.read();
int i = c - '0';
while (i >... | java |
public BEValue bdecodeNumber() throws IOException {
int c = this.getNextIndicator();
if (c != 'i') {
throw new InvalidBEncodingException("Expected 'i', not '" +
(char) c + "'");
}
this.indicator = 0;
c = this.read();
if (c == '0') {
c = this.read();
if (c == 'e')... | java |
public BEValue bdecodeList() throws IOException {
int c = this.getNextIndicator();
if (c != 'l') {
throw new InvalidBEncodingException("Expected 'l', not '" +
(char) c + "'");
}
this.indicator = 0;
List<BEValue> result = new ArrayList<BEValue>();
c = this.getNextIndicator();... | java |
public boolean validate(SharedTorrent torrent, Piece piece) throws IOException {
logger.trace("Validating {}...", this);
// TODO: remove cast to int when large ByteBuffer support is
// implemented in Java.
byte[] pieceBytes = data.array();
final byte[] calculatedHash = TorrentUtils.calculateSha1Ha... | java |
private ByteBuffer _read(long offset, long length, ByteBuffer buffer) throws IOException {
if (offset + length > this.length) {
throw new IllegalArgumentException("Piece#" + this.index +
" overrun (" + offset + " + " + length + " > " +
this.length + ") !");
}
// TODO: remo... | java |
public ByteBuffer read(long offset, int length, ByteBuffer block)
throws IllegalArgumentException, IllegalStateException, IOException {
if (!this.valid) {
throw new IllegalStateException("Attempting to read an " +
"known-to-be invalid piece!");
}
return this._read(offset, leng... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.