/** * Returns a new byte array containing the characters of this string encoded using the * given charset. * * <p>The behavior when this string cannot be represented in the given charset * is to replace malformed input and unmappable characters with the charset's default * replacement byte array. Use {@link java.nio.charset.CharsetEncoder} for more control. * * @since 1.6 */ public byte[] getBytes(Charset charset) { String canonicalCharsetName = charset.name(); if (canonicalCharsetName.equals("UTF-8")) { return Charsets.toUtf8Bytes(value, offset, count); } else if (canonicalCharsetName.equals("ISO-8859-1")) { return Charsets.toIsoLatin1Bytes(value, offset, count); } else if (canonicalCharsetName.equals("US-ASCII")) { return Charsets.toAsciiBytes(value, offset, count); } else { CharBuffer chars = CharBuffer.wrap(this.value, this.offset, this.count); ByteBuffer buffer = charset.encode(chars.asReadOnlyBuffer()); byte[] bytes = new byte[buffer.limit()]; buffer.get(bytes); return bytes; } }
@Override public byte[] getByteArray(String key, byte[] deflt) { String svalue = get(key, null); if (svalue == null) { return deflt; } if (svalue.length() == 0) { return new byte[0]; } try { byte[] bavalue = svalue.getBytes(Charsets.US_ASCII); if (bavalue.length % 4 != 0) { return deflt; } return Base64.decode(bavalue); } catch (Exception e) { return deflt; } }
/** * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') * and legal characters are converted into their hexidecimal value prepended * by '%'. * <p> * For example: '#' -> %23 * Other characters, which are unicode chars that are not US-ASCII, and are * not ISO Control or are not ISO Space chars, are preserved. * <p> * Called from {@code URI.quoteComponent()} (for multiple argument * constructors) * * @param s * java.lang.String the string to be converted * @param legal * java.lang.String the characters allowed to be preserved in the * string s * @return java.lang.String the converted string */ static String quoteIllegal(String s, String legal) throws UnsupportedEncodingException { StringBuilder buf = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || legal.indexOf(ch) > -1 || (ch > 127 && !Character.isSpaceChar(ch) && !Character .isISOControl(ch))) { buf.append(ch); } else { byte[] bytes = new String(new char[] { ch }).getBytes(Charsets.UTF_8); for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(digits.charAt((bytes[j] & 0xf0) >> 4)); buf.append(digits.charAt(bytes[j] & 0xf)); } } } return buf.toString(); }
/** * Other characters, which are Unicode chars that are not US-ASCII, and are * not ISO Control or are not ISO Space chars are not preserved. They are * converted into their hexidecimal value prepended by '%'. * <p> * For example: Euro currency symbol -> "%E2%82%AC". * <p> * Called from URI.toASCIIString() * * @param s * java.lang.String the string to be converted * @return java.lang.String the converted string */ static String encodeOthers(String s) throws UnsupportedEncodingException { StringBuilder buf = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch <= 127) { buf.append(ch); } else { byte[] bytes = new String(new char[] { ch }).getBytes(Charsets.UTF_8); for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(digits.charAt((bytes[j] & 0xf0) >> 4)); buf.append(digits.charAt(bytes[j] & 0xf)); } } } return buf.toString(); }
public void setEncodingContent(BerOutputStream out) { AttributeValue av = (AttributeValue) out.content; if (av.encoded != null) { out.length = av.encoded.length; } else { if (av.getTag() == ASN1Constants.TAG_UTF8STRING) { out.content = av.rawString; ASN1StringType.UTF8STRING.setEncodingContent(out); av.bytes = (byte[]) out.content; out.content = av; } else { av.bytes = av.rawString.getBytes(Charsets.UTF_8); out.length = av.bytes.length; } } }
public void setEncodingContent(BerOutputStream out) { SimpleDateFormat sdf = new SimpleDateFormat(GEN_PATTERN); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String temp = sdf.format(out.content); // cut off trailing 0s int nullId; int currLength; while (((nullId = temp.lastIndexOf('0', currLength = temp.length() - 1)) != -1) & (nullId == currLength)) { temp = temp.substring(0, nullId); } // deal with point (cut off if it is last char) if (temp.charAt(currLength) == '.') { temp = temp.substring(0, currLength); } out.content = (temp + "Z").getBytes(Charsets.UTF_8); out.length = ((byte[]) out.content).length; }
/** * Prepares the HTTP headers and sends them to the server. * * <p>For streaming requests with a body, headers must be prepared * <strong>before</strong> the output stream has been written to. Otherwise * the body would need to be buffered! * * <p>For non-streaming requests with a body, headers must be prepared * <strong>after</strong> the output stream has been written to and closed. * This ensures that the {@code Content-Length} header receives the proper * value. */ private void writeRequestHeaders(OutputStream out) throws IOException { Header header = prepareRequestHeaders(); StringBuilder result = new StringBuilder(256); result.append(header.getStatusLine()).append("\r\n"); for (int i = 0; i < header.length(); i++) { String key = header.getKey(i); String value = header.get(i); if (key != null) { result.append(key).append(": ").append(value).append("\r\n"); } } result.append("\r\n"); out.write(result.toString().getBytes(Charsets.ISO_8859_1)); sentRequestHeaders = true; }
/** * Create a new NDEF Record containing a URI.<p> * Use this method to encode a URI (or URL) into an NDEF Record.<p> * Uses the well known URI type representation: {@link #TNF_WELL_KNOWN} * and {@link #RTD_URI}. This is the most efficient encoding * of a URI into NDEF.<p> * The uri parameter will be normalized with * {@link Uri#normalizeScheme} to set the scheme to lower case to * follow Android best practices for intent filtering. * However the unchecked exception * {@link IllegalArgumentException} may be thrown if the uri * parameter has serious problems, for example if it is empty, so always * catch this exception if you are passing user-generated data into this * method.<p> * * Reference specification: NFCForum-TS-RTD_URI_1.0 * * @param uri URI to encode. * @return an NDEF Record containing the URI * @throws IllegalArugmentException if the uri is empty or invalid */ public static NdefRecord createUri(Uri uri) { if (uri == null) throw new NullPointerException("uri is null"); uri = uri.normalizeScheme(); String uriString = uri.toString(); if (uriString.length() == 0) throw new IllegalArgumentException("uri is empty"); byte prefix = 0; for (int i = 1; i < URI_PREFIX_MAP.length; i++) { if (uriString.startsWith(URI_PREFIX_MAP[i])) { prefix = (byte) i; uriString = uriString.substring(URI_PREFIX_MAP[i].length()); break; } } byte[] uriBytes = uriString.getBytes(Charsets.UTF_8); byte[] recordBytes = new byte[uriBytes.length + 1]; recordBytes[0] = prefix; System.arraycopy(uriBytes, 0, recordBytes, 1, uriBytes.length); return new NdefRecord(TNF_WELL_KNOWN, RTD_URI, null, recordBytes); }
/** * Return complete URI of {@link #TNF_WELL_KNOWN}, {@link #RTD_URI} records. * @return complete URI, or null if invalid */ private Uri parseWktUri() { if (mPayload.length < 2) { return null; } // payload[0] contains the URI Identifier Code, as per // NFC Forum "URI Record Type Definition" section 3.2.2. int prefixIndex = (mPayload[0] & (byte)0xFF); if (prefixIndex < 0 || prefixIndex >= URI_PREFIX_MAP.length) { return null; } String prefix = URI_PREFIX_MAP[prefixIndex]; String suffix = new String(Arrays.copyOfRange(mPayload, 1, mPayload.length), Charsets.UTF_8); return Uri.parse(prefix + suffix); }
public ReaderInputStream(InputStream stream, String encoding) { try { reader = new InputStreamReader(stream, Charsets.UTF_8); writer = new OutputStreamWriter(out, encoding); } catch (UnsupportedEncodingException e) { // Should never happen, since UTF-8 and platform encoding must be // supported. throw new RuntimeException(e); } }
private void readName() throws IOException { int i = 0; int mark = pos; while (pos < buf.length) { byte b = buf[pos++]; if (b == ':') { byte[] nameBuffer = Arrays.copyOfRange(buf, mark, pos - 1); if (buf[pos++] != ' ') { String name = new String(nameBuffer, Charsets.UTF_8); throw new IOException(String.format("Invalid value for attribute '%s'", name)); } name = new Attributes.Name(nameBuffer); return; } if (!((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == '-' || (b >= '0' && b <= '9'))) { throw new IOException("Invalid byte " + b + " in attribute"); } } if (i > 0) { throw new IOException("Invalid attribute name: " + Arrays.toString(Arrays.copyOfRange(buf, mark, buf.length))); } }
private void readValue() throws IOException { boolean lastCr = false; int mark = pos; int last = pos; valueBuffer.rewind(); while (pos < buf.length) { byte next = buf[pos++]; switch (next) { case 0: throw new IOException("NUL character in a manifest"); case '\n': if (lastCr) { lastCr = false; } else { consecutiveLineBreaks++; } continue; case '\r': lastCr = true; consecutiveLineBreaks++; continue; case ' ': if (consecutiveLineBreaks == 1) { valueBuffer.write(buf, mark, last - mark); mark = pos; consecutiveLineBreaks = 0; continue; } } if (consecutiveLineBreaks >= 1) { pos--; break; } last = pos; } valueBuffer.write(buf, mark, last - mark); value = valueBuffer.toString(Charsets.UTF_8); }
private boolean verify(Attributes attributes, String entry, byte[] data, int start, int end, boolean ignoreSecondEndline, boolean ignorable) { String algorithms = attributes.getValue("Digest-Algorithms"); if (algorithms == null) { algorithms = "SHA SHA1"; } StringTokenizer tokens = new StringTokenizer(algorithms); while (tokens.hasMoreTokens()) { String algorithm = tokens.nextToken(); String hash = attributes.getValue(algorithm + entry); if (hash == null) { continue; } MessageDigest md; try { md = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { continue; } if (ignoreSecondEndline && data[end - 1] == '\n' && data[end - 2] == '\n') { md.update(data, start, end - 1 - start); } else { md.update(data, start, end - start); } byte[] b = md.digest(); byte[] hashBytes = hash.getBytes(Charsets.ISO_8859_1); return MessageDigest.isEqual(b, Base64.decode(hashBytes)); } return ignorable; }
/** * Checks the correctness of the string representation of DNS name. * The correctness is checked as specified in RFC 1034 p. 10, and modified * by RFC 1123 (section 2.1). */ public static void checkDNS(String dns) throws IOException { byte[] bytes = dns.toLowerCase().getBytes(Charsets.UTF_8); // indicates if it is a first letter of the label boolean first_letter = true; for (int i=0; i<bytes.length; i++) { byte ch = bytes[i]; if (first_letter) { if ((bytes.length > 2) && (ch == '*') && (bytes[1] == '.')) { first_letter = false; continue; } if ((ch > 'z' || ch < 'a') && (ch < '0' || ch > '9')) { throw new IOException("DNS name must start with a letter: " + dns); } first_letter = false; continue; } if (!((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || (ch == '-') || (ch == '.'))) { throw new IOException("Incorrect DNS name: " + dns); } if (ch == '.') { // check the end of the previous label, it should not // be '-' sign if (bytes[i-1] == '-') { throw new IOException("Incorrect DNS name: label ends with '-': " + dns); } first_letter = true; } } }
/** * Converts OID into array of bytes. */ public static int[] oidStrToInts(String oid) throws IOException { byte[] bytes = oid.getBytes(Charsets.UTF_8); if (bytes[bytes.length-1] == '.') { throw new IOException("Bad OID: " + oid); } int[] result = new int[bytes.length/2+1]; // best case: a.b.c.d.e int number = 0; // the number of OID's components for (int i=0; i<bytes.length; i++) { int value = 0; int pos = i; while ((i < bytes.length) && (bytes[i] >= '0') && (bytes[i] <= '9')) { value = 10 * value + (bytes[i++] - 48); } if (i == pos) { // the number was not read throw new IOException("Bad OID: " + oid); } result[number++] = value; if (i >= bytes.length) { break; } if (bytes[i] != '.') { throw new IOException("Bad OID: " + oid); } } if (number < 2) { throw new IOException("OID should consist of no less than 2 components: " + oid); } int[] res = new int[number]; for (int i=0; i<number; i++) { res[i] = result[i]; } return res; }
/** * Reads the file indicating the database version in use. If the file is not * present or is unreadable, we assume a version of "2007h". */ private static String readVersion() { RandomAccessFile versionFile = null; try { versionFile = new RandomAccessFile(ZONE_DIRECTORY_NAME + "zoneinfo.version", "r"); byte[] buf = new byte[(int) versionFile.length()]; versionFile.readFully(buf); return new String(buf, 0, buf.length, Charsets.ISO_8859_1).trim(); } catch (IOException ex) { throw new RuntimeException(ex); } finally { IoUtils.closeQuietly(versionFile); } }
private static String nullName(byte[] bytes, int begin) { if (begin < 0) { return null; } int end = begin; while (end < bytes.length && bytes[end] != 0) { ++end; } return new String(bytes, begin, end - begin, Charsets.US_ASCII); }
private int getReply() throws IOException { byte[] code = new byte[3]; for (int i = 0; i < code.length; i++) { final int tmp = ctrlInput.read(); if (tmp == -1) { throw new EOFException(); } code[i] = (byte) tmp; } replyCode = new String(code, 0, code.length, Charsets.ISO_8859_1); boolean multiline = false; if (ctrlInput.read() == '-') { multiline = true; } readLine(); /* Skip the rest of the first line */ if (multiline) { while (readMultiLine()) {/* Read all of a multiline reply */ } } try { return Integer.parseInt(replyCode); } catch (NumberFormatException e) { throw (IOException)(new IOException("reply code is invalid").initCause(e)); } }
/** * Returns the authorization credentials on the base of provided challenge. */ private String getAuthorizationCredentials(String challenge) throws IOException { int idx = challenge.indexOf(" "); if (idx == -1) { return null; } String scheme = challenge.substring(0, idx); int realm = challenge.indexOf("realm=\"") + 7; String prompt = null; if (realm != -1) { int end = challenge.indexOf('"', realm); if (end != -1) { prompt = challenge.substring(realm, end); } } // use the global authenticator to get the password PasswordAuthentication pa = Authenticator.requestPasswordAuthentication( getConnectToInetAddress(), getConnectToPort(), url.getProtocol(), prompt, scheme); if (pa == null) { return null; } // base64 encode the username and password String usernameAndPassword = pa.getUserName() + ":" + new String(pa.getPassword()); byte[] bytes = usernameAndPassword.getBytes(Charsets.ISO_8859_1); String encoded = Base64.encode(bytes, Charsets.ISO_8859_1); return scheme + " " + encoded; }
/** * Get a String from the buffer at the offset given. The method reads until * it encounters a null value or reaches the maxLength given. */ private String getString(int offset, int maxLength) { int index = offset; int lastIndex = index + maxLength; while (index < lastIndex && (buffer[index] != 0)) { index++; } return new String(buffer, offset, index - offset, Charsets.ISO_8859_1); }
/** * Put a string into the buffer at the offset given. */ private void setString(int offset, int maxLength, String theString) { byte[] stringBytes = theString.getBytes(Charsets.ISO_8859_1); int length = Math.min(stringBytes.length, maxLength); System.arraycopy(stringBytes, 0, buffer, offset, length); buffer[offset + length] = 0; }
ZipEntry(LittleEndianReader ler, InputStream in) throws IOException { /* * We're seeing performance issues when we call readShortLE and * readIntLE, so we're going to read the entire header at once * and then parse the results out without using any function calls. * Uglier, but should be much faster. * * Note that some lines look a bit different, because the corresponding * fields or locals are long and so we need to do & 0xffffffffl to avoid * problems induced by sign extension. */ byte[] hdrBuf = ler.hdrBuf; myReadFully(in, hdrBuf); long sig = (hdrBuf[0] & 0xff) | ((hdrBuf[1] & 0xff) << 8) | ((hdrBuf[2] & 0xff) << 16) | ((hdrBuf[3] << 24) & 0xffffffffL); if (sig != CENSIG) { throw new ZipException("Central Directory Entry not found"); } compressionMethod = (hdrBuf[10] & 0xff) | ((hdrBuf[11] & 0xff) << 8); time = (hdrBuf[12] & 0xff) | ((hdrBuf[13] & 0xff) << 8); modDate = (hdrBuf[14] & 0xff) | ((hdrBuf[15] & 0xff) << 8); crc = (hdrBuf[16] & 0xff) | ((hdrBuf[17] & 0xff) << 8) | ((hdrBuf[18] & 0xff) << 16) | ((hdrBuf[19] << 24) & 0xffffffffL); compressedSize = (hdrBuf[20] & 0xff) | ((hdrBuf[21] & 0xff) << 8) | ((hdrBuf[22] & 0xff) << 16) | ((hdrBuf[23] << 24) & 0xffffffffL); size = (hdrBuf[24] & 0xff) | ((hdrBuf[25] & 0xff) << 8) | ((hdrBuf[26] & 0xff) << 16) | ((hdrBuf[27] << 24) & 0xffffffffL); nameLen = (hdrBuf[28] & 0xff) | ((hdrBuf[29] & 0xff) << 8); int extraLen = (hdrBuf[30] & 0xff) | ((hdrBuf[31] & 0xff) << 8); int commentLen = (hdrBuf[32] & 0xff) | ((hdrBuf[33] & 0xff) << 8); mLocalHeaderRelOffset = (hdrBuf[42] & 0xff) | ((hdrBuf[43] & 0xff) << 8) | ((hdrBuf[44] & 0xff) << 16) | ((hdrBuf[45] << 24) & 0xffffffffL); byte[] nameBytes = new byte[nameLen]; myReadFully(in, nameBytes); byte[] commentBytes = null; if (commentLen > 0) { commentBytes = new byte[commentLen]; myReadFully(in, commentBytes); } if (extraLen > 0) { extra = new byte[extraLen]; myReadFully(in, extra); } // The RI has always assumed UTF-8. (If GPBF_UTF8_FLAG isn't set, the encoding is // actually IBM-437.) name = new String(nameBytes, 0, nameBytes.length, Charsets.UTF_8); if (commentBytes != null) { comment = new String(commentBytes, 0, commentBytes.length, Charsets.UTF_8); } else { comment = null; } }
/** * Invoked for each new JAR entry read operation from the input * stream. This method constructs and returns a new {@link VerifierEntry} * which contains the certificates used to sign the entry and its hash value * as specified in the JAR MANIFEST format. * * @param name * the name of an entry in a JAR file which is <b>not</b> in the * {@code META-INF} directory. * @return a new instance of {@link VerifierEntry} which can be used by * callers as an {@link OutputStream}. */ VerifierEntry initEntry(String name) { // If no manifest is present by the time an entry is found, // verification cannot occur. If no signature files have // been found, do not verify. if (man == null || signatures.size() == 0) { return null; } Attributes attributes = man.getAttributes(name); // entry has no digest if (attributes == null) { return null; } Vector<Certificate> certs = new Vector<Certificate>(); Iterator<Map.Entry<String, HashMap<String, Attributes>>> it = signatures .entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, HashMap<String, Attributes>> entry = it.next(); HashMap<String, Attributes> hm = entry.getValue(); if (hm.get(name) != null) { // Found an entry for entry name in .SF file String signatureFile = entry.getKey(); Vector<Certificate> newCerts = getSignerCertificates( signatureFile, certificates); Iterator<Certificate> iter = newCerts.iterator(); while (iter.hasNext()) { certs.add(iter.next()); } } } // entry is not signed if (certs.size() == 0) { return null; } Certificate[] certificatesArray = new Certificate[certs.size()]; certs.toArray(certificatesArray); String algorithms = attributes.getValue("Digest-Algorithms"); if (algorithms == null) { algorithms = "SHA SHA1"; } StringTokenizer tokens = new StringTokenizer(algorithms); while (tokens.hasMoreTokens()) { String algorithm = tokens.nextToken(); String hash = attributes.getValue(algorithm + "-Digest"); if (hash == null) { continue; } byte[] hashBytes = hash.getBytes(Charsets.ISO_8859_1); try { return new VerifierEntry(name, MessageDigest .getInstance(algorithm), hashBytes, certificatesArray); } catch (NoSuchAlgorithmException e) { // ignored } } return null; }
@Override public void putByteArray(String key, byte[] value) { put(key, Base64.encode(value, Charsets.US_ASCII)); }
public void setEncodingContent(BerOutputStream out) { SimpleDateFormat sdf = new SimpleDateFormat(UTC_PATTERN); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); out.content = sdf.format(out.content).getBytes(Charsets.UTF_8); out.length = ((byte[]) out.content).length; }
public Object getDecodedObject(BerInputStream in) throws IOException { return new String(in.buffer, in.contentOffset, in.length, Charsets.UTF_8); }
public void setEncodingContent(BerOutputStream out) { byte[] bytes = ((String) out.content).getBytes(Charsets.UTF_8); out.content = bytes; out.length = bytes.length; }
private void write(String command) throws IOException { ctrlOutput.write(command.getBytes(Charsets.ISO_8859_1)); }
protected CharsetDecoder initialValue() { return Charsets.UTF_8.newDecoder(); }
protected CharsetEncoder initialValue() { return Charsets.UTF_8.newEncoder(); }
/** * Create a new NDEF Record containing MIME data.<p> * Use this method to encode MIME-typed data into an NDEF Record, * such as "text/plain", or "image/jpeg".<p> * The mimeType parameter will be normalized with * {@link Intent#normalizeMimeType} to follow Android best * practices for intent filtering, for example to force lower-case. * However the unchecked exception * {@link IllegalArgumentException} may be thrown * if the mimeType parameter has serious problems, * for example if it is empty, so always catch this * exception if you are passing user-generated data into this method. * <p> * For efficiency, This method might not make an internal copy of the * mimeData byte array, so take care not * to modify the mimeData byte array while still using the returned * NdefRecord. * * @param mimeType a valid MIME type * @param mimeData MIME data as bytes * @return an NDEF Record containing the MIME-typed data * @throws IllegalArugmentException if the mimeType is empty or invalid * */ public static NdefRecord createMime(String mimeType, byte[] mimeData) { if (mimeType == null) throw new NullPointerException("mimeType is null"); // We only do basic MIME type validation: trying to follow the // RFCs strictly only ends in tears, since there are lots of MIME // types in common use that are not strictly valid as per RFC rules mimeType = Intent.normalizeMimeType(mimeType); if (mimeType.length() == 0) throw new IllegalArgumentException("mimeType is empty"); int slashIndex = mimeType.indexOf('/'); if (slashIndex == 0) throw new IllegalArgumentException("mimeType must have major type"); if (slashIndex == mimeType.length() - 1) { throw new IllegalArgumentException("mimeType must have minor type"); } // missing '/' is allowed // MIME RFCs suggest ASCII encoding for content-type byte[] typeBytes = mimeType.getBytes(Charsets.US_ASCII); return new NdefRecord(TNF_MIME_MEDIA, typeBytes, null, mimeData); }
/** * Create a new NDEF Record containing external (application-specific) data.<p> * Use this method to encode application specific data into an NDEF Record. * The data is typed by a domain name (usually your Android package name) and * a domain-specific type. This data is packaged into a "NFC Forum External * Type" NDEF Record.<p> * NFC Forum requires that the domain and type used in an external record * are treated as case insensitive, however Android intent filtering is * always case sensitive. So this method will force the domain and type to * lower-case before creating the NDEF Record.<p> * The unchecked exception {@link IllegalArgumentException} will be thrown * if the domain and type have serious problems, for example if either field * is empty, so always catch this * exception if you are passing user-generated data into this method.<p> * There are no such restrictions on the payload data.<p> * For efficiency, This method might not make an internal copy of the * data byte array, so take care not * to modify the data byte array while still using the returned * NdefRecord. * * Reference specification: NFCForum-TS-RTD_1.0 * @param domain domain-name of issuing organization * @param type domain-specific type of data * @param data payload as bytes * @throws IllegalArugmentException if either domain or type are empty or invalid */ public static NdefRecord createExternal(String domain, String type, byte[] data) { if (domain == null) throw new NullPointerException("domain is null"); if (type == null) throw new NullPointerException("type is null"); domain = domain.trim().toLowerCase(Locale.US); type = type.trim().toLowerCase(Locale.US); if (domain.length() == 0) throw new IllegalArgumentException("domain is empty"); if (type.length() == 0) throw new IllegalArgumentException("type is empty"); byte[] byteDomain = domain.getBytes(Charsets.UTF_8); byte[] byteType = type.getBytes(Charsets.UTF_8); byte[] b = new byte[byteDomain.length + 1 + byteType.length]; System.arraycopy(byteDomain, 0, b, 0, byteDomain.length); b[byteDomain.length] = ':'; System.arraycopy(byteType, 0, b, byteDomain.length + 1, byteType.length); return new NdefRecord(TNF_EXTERNAL_TYPE, b, null, data); }
/** * Create a new Android Application Record (AAR). * <p> * This record indicates to other Android devices the package * that should be used to handle the entire NDEF message. * You can embed this record anywhere into your message * to ensure that the intended package receives the message. * <p> * When an Android device dispatches an {@link NdefMessage} * containing one or more Android application records, * the applications contained in those records will be the * preferred target for the {@link NfcAdapter#ACTION_NDEF_DISCOVERED} * intent, in the order in which they appear in the message. * This dispatch behavior was first added to Android in * Ice Cream Sandwich. * <p> * If none of the applications have a are installed on the device, * a Market link will be opened to the first application. * <p> * Note that Android application records do not overrule * applications that have called * {@link NfcAdapter#enableForegroundDispatch}. * * @param packageName Android package name * @return Android application NDEF record */ public static NdefRecord createApplicationRecord(String packageName) { if (packageName == null) throw new NullPointerException("packageName is null"); if (packageName.length() == 0) throw new IllegalArgumentException("packageName is empty"); return new NdefRecord(TNF_EXTERNAL_TYPE, RTD_ANDROID_APP, null, packageName.getBytes(Charsets.UTF_8)); }
/** * Map this record to a MIME type, or return null if it cannot be mapped.<p> * Currently this method considers all {@link #TNF_MIME_MEDIA} records to * be MIME records, as well as some {@link #TNF_WELL_KNOWN} records such as * {@link #RTD_TEXT}. If this is a MIME record then the MIME type as string * is returned, otherwise null is returned.<p> * This method does not perform validation that the MIME type is * actually valid. It always attempts to * return a string containing the type if this is a MIME record.<p> * The returned MIME type will by normalized to lower-case using * {@link Intent#normalizeMimeType}.<p> * The MIME payload can be obtained using {@link #getPayload}. * * @return MIME type as a string, or null if this is not a MIME record */ public String toMimeType() { switch (mTnf) { case NdefRecord.TNF_WELL_KNOWN: if (Arrays.equals(mType, NdefRecord.RTD_TEXT)) { return "text/plain"; } break; case NdefRecord.TNF_MIME_MEDIA: String mimeType = new String(mType, Charsets.US_ASCII); return Intent.normalizeMimeType(mimeType); } return null; }
/** * Returns this attribute name. * * @return the attribute name. */ @Override public String toString() { return new String(name, Charsets.ISO_8859_1); }
/** * Extracts String object from BER input stream. * * @param in - BER input stream * @return java.land.String object */ public Object getDecodedObject(BerInputStream in) throws IOException { /* To ensure we get the correct encoding on non-ASCII platforms, specify that we wish to convert from ASCII to the default platform encoding */ return new String(in.buffer, in.contentOffset, in.length, Charsets.ISO_8859_1); }