/** Converts the Message to a String. */ public String toString() { StringBuffer sb = new StringBuffer(); OPTRecord opt = getOPT(); if (opt != null) sb.append(header.toStringWithRcode(getRcode()) + "\n"); else sb.append(header + "\n"); if (isSigned()) { sb.append(";; TSIG "); if (isVerified()) sb.append("ok"); else sb.append("invalid"); sb.append('\n'); } if (opt != null) { sb.append(";; OPT PSEUDOSECTION:\n"); sb.append("; EDNS: version: "); sb.append(opt.getVersion()); sb.append(", flags:"); if ((opt.getFlags() & ExtendedFlags.DO) != 0) { sb.append(" do"); } sb.append("; udp: "); sb.append(opt.getPayloadSize()); sb.append("\n"); } for (int i = 0; i < 4; i++) { if (header.getOpcode() != Opcode.UPDATE) sb.append(";; " + Section.longString(i) + ":\n"); else sb.append(";; " + Section.updString(i) + ":\n"); sb.append(sectionToString(i) + "\n"); } sb.append(";; Message size: " + numBytes() + " bytes"); return sb.toString(); }
Message(DNSInput in) throws IOException { this(new Header(in)); boolean isUpdate = (header.getOpcode() == Opcode.UPDATE); boolean truncated = header.getFlag(Flags.TC); try { for (int i = 0; i < 4; i++) { int count = header.getCount(i); if (count > 0) sections[i] = new ArrayList(count); for (int j = 0; j < count; j++) { int pos = in.current(); Record rec = Record.fromWire(in, i, isUpdate); sections[i].add(rec); if (i == Section.ADDITIONAL) { if (rec.getType() == Type.TSIG) tsigstart = pos; if (rec.getType() == Type.SIG) { SIGRecord sig = (SIGRecord) rec; if (sig.getTypeCovered() == 0) sig0start = pos; } } } } } catch (WireParseException e) { if (!truncated) throw e; } size = in.current(); }
public Rectangle[] draw( Graphics g, int xOffSet, int yOffSet, double xScale, double yScale, boolean isSelected) { Color temp = g.getColor(); int left = (int) (this.getLeft() * xScale); int top = (int) (this.getTop() * yScale); int width = (int) ((this.getRight() - this.getLeft()) * xScale); int height = (int) ((this.getBottom() - this.getTop()) * yScale); Rectangle[] crossHairs = null; if (isSelected) { g.setColor(Color.red); crossHairs = new Rectangle[4]; g.drawRect(left - 2, top - 2, 4, 4); g.drawRect(left + width - 2, top - 2, 4, 4); g.drawRect(left - 2, top + height - 2, 4, 4); g.drawRect(left + width - 2, top + height - 2, 4, 4); crossHairs[0] = new Rectangle(left - 2, top - 2, 4, 4); crossHairs[1] = new Rectangle(left + width - 2, top - 2, 4, 4); crossHairs[2] = new Rectangle(left - 2, top + height - 2, 4, 4); crossHairs[3] = new Rectangle(left + width - 2, top + height - 2, 4, 4); g.drawRect(left, top, width, height); } g.drawRect( (int) (this.getLeft() * xScale), (int) (this.getTop() * yScale), (int) ((this.getRight() - this.getLeft()) * xScale), (int) ((this.getBottom() - this.getTop()) * yScale)); for (Header header : headersToData.keySet()) { g.setColor(header.getType().getColor()); header.draw(g, xOffSet, yOffSet, xScale, yScale); headersToData.get(header).draw(g, xOffSet, yOffSet, xScale, yScale); } g.setColor(temp); return crossHairs; }
/** * Switch to parent fragment and store the grand parent's info * * @param className name of the activity wrapper for the parent fragment. */ private void switchToParent(String className) { final ComponentName cn = new ComponentName(this, className); try { final PackageManager pm = getPackageManager(); final ActivityInfo parentInfo = pm.getActivityInfo(cn, PackageManager.GET_META_DATA); if (parentInfo != null && parentInfo.metaData != null) { String fragmentClass = parentInfo.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS); CharSequence fragmentTitle = parentInfo.loadLabel(pm); Header parentHeader = new Header(); parentHeader.fragment = fragmentClass; parentHeader.title = fragmentTitle; mCurrentHeader = parentHeader; switchToHeaderLocal(parentHeader); highlightHeader(mTopLevelHeaderId); mParentHeader = new Header(); mParentHeader.fragment = parentInfo.metaData.getString(META_DATA_KEY_PARENT_FRAGMENT_CLASS); mParentHeader.title = parentInfo.metaData.getString(META_DATA_KEY_PARENT_TITLE); } } catch (NameNotFoundException nnfe) { Log.w(LOG_TAG, "Could not find parent activity : " + className); } }
@Override public void visit(Header header) { this.defaultNoteLength = header.getDefaultLength(); this.beatsPerMinute = header.getBeatsPerMinute(); this.tempoBeat = header.getTempoBeat(); System.out.println(header); }
public synchronized List<Header> getHeaders(String key) { List<Header> keyh = new ArrayList<Header>(); for (Header h : this.headers) { if (h.getName().equalsIgnoreCase(key.trim())) keyh.add(h); } return keyh; }
private String getNotModified(String dataId, CacheData cacheData, HttpMethod httpMethod) { Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5); if (null == md5Header) { throw new RuntimeException("RP_NO_CHANGE response not contain MD5"); } String md5 = md5Header.getValue(); if (!cacheData.getMd5().equals(md5)) { String lastMd5 = cacheData.getMd5(); cacheData.setMd5(Constants.NULL); cacheData.setLastModifiedHeader(Constants.NULL); throw new RuntimeException( "MD5 verify error,DataID:[" + dataId + "]MD5 last:[" + lastMd5 + "]MD5 current:[" + md5 + "]"); } cacheData.setMd5(md5); changeSpacingInterval(httpMethod); if (log.isInfoEnabled()) { log.info("DataId: " + dataId + ",not changed"); } return null; }
/** * Return a ByteBuffer representing this group of header elements. * * @return ByteBuffer representing this Header */ public ByteBuffer getByteBuffer() { // note: according to the spec this may exceed MAX_HEADER_LEN, // but since there are practically only 3 header elements used // it's safe to assume this implemention detail. ByteBuffer buffer = ByteBuffer.allocate(MAX_HEADER_LEN); for (Header header : headers) { byte[] name; try { name = header.getName().getBytes("UTF-8"); } catch (UnsupportedEncodingException never) { throw new Error("Required UTF-8 encoding not available."); } byte[] value = header.getValue(); assert name.length <= 255; assert value.length <= 65535; buffer.put((byte) name.length); buffer.put(name); buffer.putShort((short) value.length); buffer.put(value); } // write empty header buffer.put((byte) 0); buffer.flip(); return buffer; }
@Test public void testDefaultHeaderFormat() { final Header header = Header.DEFAULT; final Identifier identifier = header.getIdentifier(); assertSame(Header.Identifier.INSTANCE, identifier); assertArrayEquals(new byte[] {'B', 'X', 'M', 'L', 0x00}, identifier.getName()); assertArrayEquals(new byte[] {(byte) 0xFF, 0x0D, 0x0A}, identifier.getBinaryCheck()); final Header.Version version = header.getVersion(); assertSame(Header.Version.DEFAULT_VERSION, version); final Compression compression = header.getCompression(); assertSame(Compression.NO_COMPRESSION, compression); final Flags flags = header.getFlags(); final int flags1 = flags.getFlags1(); int expectedFlags1 = 0x00; // isLittleEndian = true expectedFlags1 |= 0x01; // charsAreLittleEndian = true // expectedFlags1 |= 0x02; // hasRandomAccessInfo = false // expectedFlags1 |= 0x10; final String msg = Integer.toBinaryString(expectedFlags1) + " != " + Integer.toBinaryString(flags1); assertEquals(msg, expectedFlags1, flags1); final int flags2 = flags.getFlags2(); assertEquals(0x00, flags2); }
void prepareRequest(HttpURLConnection connection, Request request) throws IOException { // HttpURLConnection artificially restricts request method try { connection.setRequestMethod(request.getMethod()); } catch (ProtocolException e) { try { methodField.set(connection, request.getMethod()); } catch (IllegalAccessException e1) { throw RetrofitError.unexpectedError(request.getUrl(), e1); } } connection.setDoInput(true); for (Header header : request.getHeaders()) { connection.addRequestProperty(header.getName(), header.getValue()); } TypedOutput body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty("Content-Type", body.mimeType()); long length = body.length(); if (length != -1) { connection.setFixedLengthStreamingMode((int) length); connection.addRequestProperty("Content-Length", String.valueOf(length)); } else { connection.setChunkedStreamingMode(CHUNK_SIZE); } body.writeTo(connection.getOutputStream()); } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addHeadersFromResources(R.xml.headers); addHeaderAt( Header.createHeaderRow( "Prime version", "Please buy prime to let me make some money", R.drawable.ic_pref_general, false, null, 0, Color.RED), 0); addHeaderAt( Header.createHeaderRow( "Not set as deault", "Click to set solid as default launcher", R.drawable.abc_ic_search_api_mtrl_alpha, false, null, 0, Color.CYAN), 1); }
@Override public View getSectionHeaderView(int section, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Header header = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.item_reply_group, null); header = new Header(); header.groupImg = (ImageView) convertView.findViewById(R.id.reply_img); header.name = (TextView) convertView.findViewById(R.id.reply_light_text); convertView.setTag(header); } else header = (Header) convertView.getTag(); if (ReplyList.size() == 2) { if (section == 0) { header.groupImg.setImageResource(R.drawable.icon_light_down); header.name.setText("这些评论亮了"); } else { header.groupImg.setImageResource(R.drawable.icon_new_reply); header.name.setText("最新评论"); } } else { header.groupImg.setImageResource(R.drawable.icon_new_reply); header.name.setText("最新评论"); } return convertView; }
@Override public View getView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; View view; if (convertView == null) { view = mInflater.inflate(R.layout.preference_header_item, parent, false); holder = new HeaderViewHolder(); holder.icon = (ImageView) view.findViewById(android.R.id.icon); holder.title = (TextView) view.findViewById(android.R.id.title); holder.summary = (TextView) view.findViewById(android.R.id.summary); view.setTag(holder); } else { view = convertView; holder = (HeaderViewHolder) view.getTag(); } // All view fields must be updated every time, because the view may be recycled Header header = getItem(position); holder.icon.setImageResource(header.iconRes); holder.title.setText(header.getTitle(getContext().getResources())); CharSequence summary = header.getSummary(getContext().getResources()); if (!TextUtils.isEmpty(summary)) { holder.summary.setVisibility(View.VISIBLE); holder.summary.setText(summary); } else { holder.summary.setVisibility(View.GONE); } return view; }
public static void validateContentTransferEncoding(final Header headers) throws BatchDeserializerException { final HeaderField contentTransferField = headers.getHeaderField(BatchParserCommon.CONTENT_TRANSFER_ENCODING); if (contentTransferField != null) { final List<String> contentTransferValues = contentTransferField.getValues(); if (contentTransferValues.size() == 1) { String encoding = contentTransferValues.get(0); if (!BatchParserCommon.BINARY_ENCODING.equalsIgnoreCase(encoding)) { throw new BatchDeserializerException( "Invalid content transfer encoding", MessageKeys.INVALID_CONTENT_TRANSFER_ENCODING, Integer.toString(headers.getLineNumber())); } } else { throw new BatchDeserializerException( "Invalid Content-Transfer-Encoding header", MessageKeys.INVALID_CONTENT_TRANSFER_ENCODING, Integer.toString(headers.getLineNumber())); } } else { throw new BatchDeserializerException( "Missing mandatory content transfer encoding", MessageKeys.MISSING_CONTENT_TRANSFER_ENCODING, Integer.toString(headers.getLineNumber())); } }
/** * Reads and parses the next frame from the input source. * * @return the Header describing details of the frame read, or null if the end of the stream has * been reached. */ public Header readFrame() throws BitstreamException { Header result = null; try { result = readNextFrame(); // E.B, Parse VBR (if any) first frame. if (firstframe == true) { result.parseVBR(frame_bytes); firstframe = false; } } catch (BitstreamException ex) { if ((ex.getErrorCode() == INVALIDFRAME)) { // Try to skip this frame. // System.out.println("INVALIDFRAME"); try { closeFrame(); result = readNextFrame(); } catch (BitstreamException e) { if ((e.getErrorCode() != STREAM_EOF)) { // wrap original exception so stack trace is maintained. throw newBitstreamException(e.getErrorCode(), e); } } } else if ((ex.getErrorCode() != STREAM_EOF)) { // wrap original exception so stack trace is maintained. throw newBitstreamException(ex.getErrorCode(), ex); } } return result; }
private NettyMessage buildLoginReq() { NettyMessage message = new NettyMessage(); Header header = new Header(); header.setType((byte) MessageType.HAND_REQ.value); message.setHeader(header); return message; }
public static Header consumeHeaders(List<Line> remainingMessage) { final int headerLineNumber = remainingMessage.size() != 0 ? remainingMessage.get(0).getLineNumber() : 0; final Header headers = new Header(headerLineNumber); final Iterator<Line> iter = remainingMessage.iterator(); Line currentLine; boolean isHeader = true; while (iter.hasNext() && isHeader) { currentLine = iter.next(); final Matcher headerMatcher = PATTERN_HEADER_LINE.matcher(currentLine.toString()); if (headerMatcher.matches() && headerMatcher.groupCount() == 2) { iter.remove(); String headerName = headerMatcher.group(1).trim(); String headerValue = headerMatcher.group(2).trim(); headers.addHeader( headerName, Header.splitValuesByComma(headerValue), currentLine.getLineNumber()); } else { isHeader = false; } } return headers; }
private static void logRequest(Request request) { LOGGER.fine("---> HTTP " + request.getMethod() + " " + request.getUrl()); for (Header header : request.getHeaders()) { LOGGER.fine(header.getName() + ": " + header.getValue()); } LOGGER.fine("---> END HTTP"); }
/** * Create a copy of this header instance. * * @return - Copy of header. */ public Header copy() { Header h = new Header(); h.id = this.id; h.timestamp = this.timestamp; h.sendtime = this.sendtime; return h; }
@Override public OutputStream getOutputStream() throws IOException { if (!doOutput) { throw new ProtocolException(Msg.getString("K008e")); // $NON-NLS-1$ } // you can't write after you read if (sentRequest) { throw new ProtocolException(Msg.getString("K0090")); // $NON-NLS-1$ } if (os != null) { return os; } // they are requesting a stream to write to. This implies a POST method if (method == GET) { method = POST; } // If the request method is neither PUT or POST, then you're not writing if (method != PUT && method != POST) { throw new ProtocolException(Msg.getString("K008f", method)); // $NON-NLS-1$ } int limit = -1; String contentLength = reqHeader.get("Content-Length"); // $NON-NLS-1$ if (contentLength != null) { limit = Integer.parseInt(contentLength); } String encoding = reqHeader.get("Transfer-Encoding"); // $NON-NLS-1$ if (httpVersion > 0 && encoding != null) { encoding = encoding.toLowerCase(); if ("chunked".equals(encoding)) { // $NON-NLS-1$ sendChunked = true; limit = -1; } } // if user has set chunk/fixedLength mode, use that value if (chunkLength > 0) { sendChunked = true; limit = -1; } if (fixedContentLength >= 0) { limit = fixedContentLength; } if ((httpVersion > 0 && sendChunked) || limit >= 0) { os = new HttpOutputStream(limit); doRequest(); return os; } if (!connected) { // connect and see if there is cache available. connect(); } return os = new HttpOutputStream(); }
public void write(ByteBuffer buf) { ByteBuffer dup = buf.duplicate(); NIOUtils.skip(buf, 8); doWrite(buf); header.setBodySize(buf.position() - dup.position() - 8); Assert.assertEquals(header.headerSize(), 8); header.write(dup); }
public void remove(String name) { Iterator<Header> it = headers.iterator(); while (it.hasNext()) { Header header = it.next(); if (header.getName().equals(name)) { it.remove(); } } }
/** Whether the Header is equal to Object <i>obj</i> */ public boolean equals(Object obj) { try { Header hd = (Header) obj; if (hd.getName().equals(this.getName()) && hd.getValue().equals(this.getValue())) return true; else return false; } catch (Exception e) { return false; } }
/** * Generates a byte array representing the contents of this page. Used to serialize this page to * disk. * * <p>The invariant here is that it should be possible to pass the byte array generated by * getPageData to the HeapPage constructor and have it produce an identical HeapPage object. * * @see #HeapPage * @return A byte array correspond to the bytes of this page. */ public byte[] getPageData() { // int len = header.length*4 + BufferPool.PAGE_SIZE; int len = BufferPool.PAGE_SIZE; ByteArrayOutputStream baos = new ByteArrayOutputStream(len); DataOutputStream dos = new DataOutputStream(baos); // create the header of the page try { dos.write(header.getHeader()); } catch (IOException e) { // this really shouldn't happen e.printStackTrace(); } // create the tuples for (int i = 0; i < numSlots; i++) { // empty slot if (!getSlot(i)) { for (int j = 0; j < td.getSize(); j++) { try { dos.writeByte(0); } catch (IOException e) { e.printStackTrace(); } } continue; } // non-empty slot for (int j = 0; j < td.numFields(); j++) { Field f = tuples[i].getField(j); try { f.serialize(dos); } catch (IOException e) { e.printStackTrace(); } } } // padding int zerolen = BufferPool.PAGE_SIZE - numSlots * td.getSize() - header.length(); byte[] zeroes = new byte[zerolen]; try { dos.write(zeroes, 0, zerolen); } catch (IOException e) { e.printStackTrace(); } try { dos.flush(); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); }
/** * Adds the specified tuple to the page. * * @throws DbException if the page is full (no empty slots) or tupledesc is mismatch. * @param t The tuple to add. */ public void addTuple(Tuple t) throws DbException { int index = header.findFirstEmptySlot(); if (index == -1) { throw new DbException("No empty slot for new tuple"); } else { header.setSlotVal(index, true); tuples[index] = t; } }
void showBreadCrumbs(Header header) { if (header != null) { CharSequence title = header.getBreadCrumbTitle(getResources()); if (title == null) title = header.getTitle(getResources()); if (title == null) title = getTitle(); showBreadCrumbs(title, header.getBreadCrumbShortTitle(getResources())); } else { showBreadCrumbs(getTitle(), null); } }
protected void setupRequestHeader() { Header header = request.getHeader(); if (null != header) { for (String key : header.keys()) { conn.setRequestProperty(key, header.get(key)); } } URL url = request.getUrl(); conn.setRequestProperty("host", url.getHost() + ":" + url.getPort()); }
private Header getHeader(String name) { for (Header header : headers) { if (header.getName().equals(name)) { return header; } } Header header = new Header(name); headers.add(header); return header; }
@Override public void onBuildHeaders(List<Header> target) { super.onBuildHeaders(target); // add back button to header list Header backHeader = new Header(); backHeader.id = R.string.back; backHeader.titleRes = R.string.back; target.add(backHeader); }
/** * Gets all of the headers matching the specified name * * @param name the name of the header we are seeking. */ public Iterator<Header> getHeader(String name) { List<Header> matchingHeaders = new ArrayList<Header>(); for (Header aHeader : headers) { if (name.equals(aHeader.getName())) { matchingHeaders.add(aHeader); } } return matchingHeaders.iterator(); }