下面列出了android.os.NetworkOnMainThreadException#java.io.DataOutputStream 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static boolean killKIKService(Activity activity) throws IOException {
ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo serviceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) {
String packageName = serviceInfo.service.getPackageName();
if (packageName.equals("kik.android")) {
Process suProcess = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
os.writeBytes("adb shell" + "\n");
os.flush();
os.writeBytes("am force-stop kik.android" + "\n");
os.flush();
return true;
}
}
return false;
}
/**
* Generate the constructor method for the proxy class.
*/
private MethodInfo generateConstructor() throws IOException {
MethodInfo minfo = new MethodInfo(
"<init>", "(Ljava/lang/reflect/InvocationHandler;)V",
ACC_PUBLIC);
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
code_aload(1, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef(
superclassName,
"<init>", "(Ljava/lang/reflect/InvocationHandler;)V"));
out.writeByte(opc_return);
minfo.maxStack = 10;
minfo.maxLocals = 2;
minfo.declaredExceptions = new short[0];
return minfo;
}
/**
* Tests compatibility with pre-0.21 versions of TupleWritable
*/
public void testPreVersion21Compatibility() throws Exception {
Writable[] manyWrits = makeRandomWritables(64);
PreVersion21TupleWritable oldTuple = new PreVersion21TupleWritable(manyWrits);
for (int i =0; i<manyWrits.length; i++) {
if (i % 3 == 0) {
oldTuple.setWritten(i);
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
oldTuple.write(new DataOutputStream(out));
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
TupleWritable dTuple = new TupleWritable();
dTuple.readFields(new DataInputStream(in));
assertTrue("Tuple writable is unable to read pre-0.21 versions of TupleWritable", oldTuple.isCompatible(dTuple));
assertEquals("All tuple data has not been read from the stream",-1,in.read());
}
@Override
public void write(DataOutputStream out) throws IOException {
// logger.info("Writing out CompressedDataBuffer");
// here we should mimic to usual DataBuffer array
out.writeUTF(allocationMode.name());
out.writeLong(compressionDescriptor.getCompressedLength());
out.writeUTF(DataType.COMPRESSED.name());
// at this moment we don't care about mimics anymore
//ByteIndexer indexer = ByteIndexer.create((BytePointer) pointer);
out.writeUTF(compressionDescriptor.getCompressionAlgorithm());
out.writeLong(compressionDescriptor.getCompressedLength());
out.writeLong(compressionDescriptor.getOriginalLength());
out.writeLong(compressionDescriptor.getNumberOfElements());
out.writeInt(compressionDescriptor.getOriginalDataType().ordinal());
// out.write(((BytePointer) pointer).getStringBytes());
for (int x = 0; x < pointer.capacity() * pointer.sizeof(); x++) {
byte b = pointer.asByteBuffer().get(x);
out.writeByte(b);
}
}
@Test
public void testGetBlockIndexV2() throws IOException {
final File file = new File("target/" + UUID.randomUUID().toString());
try (final OutputStream out = new FileOutputStream(file);
final DataOutputStream dos = new DataOutputStream(out)) {
out.write(2);
out.write(0);
for (int i=0; i < 1024; i++) {
dos.writeLong(i * 1024L);
dos.writeLong(0L);
}
}
try {
try(final StandardTocReader reader = new StandardTocReader(file)) {
assertFalse(reader.isCompressed());
for (int i=0; i < 1024; i++) {
assertEquals(i * 1024, reader.getBlockOffset(i));
}
}
} finally {
file.delete();
}
}
/**
* Save to a stream as a Java class. Instantiating this class will
* reproduce a (virtually) identical DTD.
*/
void save(DataOutputStream out, String className) throws IOException {
out.writeInt(DTD.FILE_VERSION);
buildNamesTable();
int numNames = namesVector.size();
out.writeShort((short) (namesVector.size()));
for (int i = 0; i < namesVector.size(); i++) {
String nm = namesVector.elementAt(i);
out.writeUTF(nm);
}
saveEntities(out);
out.writeShort((short) (elements.size()));
for (Enumeration<Element> e = elements.elements() ; e.hasMoreElements() ; ) {
saveElement(out, e.nextElement());
}
if (namesVector.size() != numNames) {
System.err.println("!!! ERROR! Names were added to the list!");
Thread.dumpStack();
System.exit(1);
}
}
static void createInputOutPutFolder(Path inDir, Path outDir, int numMaps)
throws Exception {
FileSystem fs = FileSystem.get(conf);
if (fs.exists(outDir)) {
fs.delete(outDir, true);
}
if (!fs.exists(inDir)) {
fs.mkdirs(inDir);
}
String input = "The quick brown fox\n" + "has many silly\n"
+ "red fox sox\n";
for (int i = 0; i < numMaps; ++i) {
DataOutputStream file = fs.create(new Path(inDir, "part-" + i));
file.writeBytes(input);
file.close();
}
}
/**
* Save message to an open data output stream. Data saved as: 4 bytes:
* number of frames For every frame: 4 bytes: byte size of frame data + n
* bytes: frame byte data
* @param msg
* ZMsg to save
* @param file
* DataOutputStream
* @return True if saved OK, else false
*/
public static boolean save(ZMsg msg, DataOutputStream file)
{
if (msg == null)
return false;
try {
// Write number of frames
file.writeInt(msg.size());
if (msg.size() > 0) {
for (ZFrame f : msg) {
// Write byte size of frame
file.writeInt(f.size());
// Write frame byte data
file.write(f.getData());
}
}
return true;
}
catch (IOException e) {
return false;
}
}
protected void writeListing( DataOutputStream out, ListingDesign listing )
throws IOException
{
writeReportItem( out, listing );
boolean repeatHeader = listing.isRepeatHeader( );
int pageBreakInterval = listing.getPageBreakInterval( );
if ( repeatHeader == true )
{
IOUtil.writeShort( out, FIELD_REPEAT_HEADER );
IOUtil.writeBool( out, repeatHeader );
}
if ( pageBreakInterval != -1 )
{
IOUtil.writeShort( out, FIELD_PAGE_BREAK_INTERVAL );
IOUtil.writeInt( out, pageBreakInterval );
}
}
public TextIOJobBuilder writeInputs()
throws IOException {
if (fs.exists(outputPath)) {
fs.delete(outputPath, true);
}
if (fs.exists(inputPath)) {
fs.delete(inputPath, true);
}
fs.mkdirs(inputPath);
DataOutputStream stream = fs.create(new Path(inputPath, "part-0"));
IOUtils.writeLines(inputs, String.format("%n"), stream);
stream.close();
return this;
}
public void writeContent( DataOutputStream out ) throws IOException
{
if ( acl != null )
{
IOUtil.writeShort( out, FIELD_ACL );
IOUtil.writeObject( out, acl );
}
if ( userProperties != null && userProperties.size( ) > 0 )
{
IOUtil.writeShort( out, FIELD_USER_PROPERTIES );
IOUtil.writeMap( out, userProperties );
}
if ( extProperties != null && !extProperties.isEmpty( ) )
{
IOUtil.writeShort( out, FIELD_EXTENSIONS );
IOUtil.writeMap( out, extProperties );
}
}
private void writeProducerOptions(final DataOutputStream outputStream, final ShellArguments arguments,
final String topic) throws Exception {
if (!arguments.rangeString.isEmpty()) {
// If --rand-rate was specified, extract the bounds by splitting on
// the comma and parsing the resulting
// doubles.
final String[] splits = arguments.rangeString.split(",");
if (splits.length != 2) {
log.error("Argument to --rand-rate should be two comma-separated values");
return;
}
final double first = Double.parseDouble(splits[0]);
final double second = Double.parseDouble(splits[1]);
final double min = Math.min(first, second);
final double max = Math.max(first, second);
arguments.rate = random.nextDouble() * (max - min) + min;
}
outputStream.writeUTF(topic);
outputStream.writeInt(arguments.size);
outputStream.writeDouble(arguments.rate);
}
@EventHandler
public void on(final PlayerJoinEvent event)
{
final User user = UserManager.getUser(event.getPlayer().getUniqueId());
if (User.isUserInvalid(user, this.getModuleType())) {
return;
}
// Encoding the data
try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream))
{
dataOutputStream.writeByte(0);
for (final boolean b : disable) {
dataOutputStream.writeBoolean(b);
}
user.getPlayer().sendPluginMessage(AACAdditionPro.getInstance(),
SCHEMATICA_CHANNEL.getChannel(),
Objects.requireNonNull(byteArrayOutputStream.toByteArray(), "Schematica plugin message is null"));
} catch (final IOException e) {
AACAdditionPro.getInstance().getLogger().log(Level.SEVERE, "Could not write the Schematica packet.", e);
}
}
/**
* Generates a device- and invocation-specific seed to be mixed into the
* Linux PRNG.
*/
private static byte[] generateSeed() {
try {
ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
DataOutputStream seedBufferOut =
new DataOutputStream(seedBuffer);
seedBufferOut.writeLong(System.currentTimeMillis());
seedBufferOut.writeLong(System.nanoTime());
seedBufferOut.writeInt(Process.myPid());
seedBufferOut.writeInt(Process.myUid());
seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
seedBufferOut.close();
return seedBuffer.toByteArray();
} catch (IOException e) {
throw new SecurityException("Failed to generate seed", e);
}
}
private byte[] noReaderException() {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(AcrReader.VERSION);
dout.writeInt(AcrReader.STATUS_EXCEPTION);
dout.writeUTF("Reader not connected");
byte[] response = out.toByteArray();
Log.d(TAG, "Send exception response length " + response.length + ":" + ACRCommands.toHexString(response));
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Save to a stream as a Java class. Instantiating this class will
* reproduce a (virtually) identical DTD.
*/
void save(DataOutputStream out, String className) throws IOException {
out.writeInt(DTD.FILE_VERSION);
buildNamesTable();
int numNames = namesVector.size();
out.writeShort((short) (namesVector.size()));
for (int i = 0; i < namesVector.size(); i++) {
String nm = namesVector.elementAt(i);
out.writeUTF(nm);
}
saveEntities(out);
out.writeShort((short) (elements.size()));
for (Enumeration<Element> e = elements.elements() ; e.hasMoreElements() ; ) {
saveElement(out, e.nextElement());
}
if (namesVector.size() != numNames) {
System.err.println("!!! ERROR! Names were added to the list!");
Thread.dumpStack();
System.exit(1);
}
}
static void write(BinaryAttribute attributes, DataOutputStream out,
BinaryConstantPool cpool, Environment env) throws IOException {
// count the number of attributes
int attributeCount = 0;
for (BinaryAttribute att = attributes; att != null; att = att.next)
attributeCount++;
out.writeShort(attributeCount);
// write out each attribute
for (BinaryAttribute att = attributes; att != null; att = att.next) {
Identifier name = att.name;
byte data[] = att.data;
// write the identifier
out.writeShort(cpool.indexString(name.toString(), env));
// write the length
out.writeInt(data.length);
// write the data
out.write(data, 0, data.length);
}
}
static byte[] queryPacket(String serviceName, int qclass, int... qtypes) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(0);
dos.writeShort(qtypes.length); // questions
dos.writeShort(0); // answers
dos.writeShort(0); // nscount
dos.writeShort(0); // arcount
int fqdnPtr = -1;
for (int qtype : qtypes) {
if (fqdnPtr == -1) {
fqdnPtr = dos.size();
writeFQDN(serviceName, dos);
} else {
// packet compression, string is just a pointer to previous occurrence
dos.write(0xc0 | (fqdnPtr >> 8));
dos.write(fqdnPtr & 0xFF);
}
dos.writeShort(qtype);
dos.writeShort(qclass);
}
dos.close();
return bos.toByteArray();
}
@Override
public byte[] encodeResponse(ProxyEntityResponse r) throws MessageCodecException {
if (r == null) {
return new byte[0];
}
MessageType messageType = r.getMessageType();
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(byteOut);
try {
output.writeByte(messageType.ordinal());
output.writeByte(messageType == MessageType.ERROR ? 0 : getMessageTypeIdentifier(r));
output.write(codec.encode(r.getResponseType(), r.getResponse()));
output.close();
} catch (Exception e) {
throw new MessageCodecException("Error encoding ProxyEntityResponse", e);
}
return byteOut.toByteArray();
}
@Override
public void transferBlock(final ExtendedBlock blk,
final Token<BlockTokenIdentifier> blockToken,
final String clientName,
final DatanodeInfo[] targets,
final StorageType[] targetStorageTypes) throws IOException {
checkAccess(socketOut, true, blk, blockToken,
Op.TRANSFER_BLOCK, BlockTokenSecretManager.AccessMode.COPY);
previousOpClientName = clientName;
updateCurrentThreadName(Op.TRANSFER_BLOCK + " " + blk);
final DataOutputStream out = new DataOutputStream(
getOutputStream());
try {
datanode.transferReplicaForPipelineRecovery(blk, targets,
targetStorageTypes, clientName);
writeResponse(Status.SUCCESS, null, out);
} catch (IOException ioe) {
LOG.info("transferBlock " + blk + " received exception " + ioe);
incrDatanodeNetworkErrors();
throw ioe;
} finally {
IOUtils.closeStream(out);
}
}
/**
* Create a JDP packet, add mandatory magic and version headers
*
* @throws IOException
*/
public JdpPacketWriter()
throws IOException {
baos = new ByteArrayOutputStream();
pkt = new DataOutputStream(baos);
pkt.writeInt(JdpGenericPacket.getMagic());
pkt.writeShort(JdpGenericPacket.getVersion());
}
@Override
public ColumnValueEncoder getEncoder(int numElements) {
PDataType type = PVarbinary.INSTANCE;
int estimatedSize = PArrayDataType.estimateSize(numElements, type);
TrustedByteArrayOutputStream byteStream = new TrustedByteArrayOutputStream(estimatedSize);
DataOutputStream oStream = new DataOutputStream(byteStream);
return new PArrayDataTypeEncoder(byteStream, oStream, numElements, type, SortOrder.ASC, false, getSerializationVersion());
}
@Override
public void serialize(DataOutputStream outputStream) {
try {
outputStream.write(getSerializeId().ordinal());
outputStream.write(filterType.ordinal());
ReadWriteIOUtils.writeObject(value, outputStream);
} catch (IOException ignored) {
// ignored
}
}
@Override
public void encode(Short value, OutputStream outStream) throws IOException {
if (value == null) {
throw new CoderException("cannot encode a null Short");
}
new DataOutputStream(outStream).writeShort(value);
}
public Framer(InputStream input, OutputStream output) throws IOException {
mInput = new DataInputStream(input);
mMultiplexedOutputStream = new DataOutputStream(output);
mStdin = new FramingInputStream();
mStdout = new PrintStream(
new BufferedOutputStream(
new FramingOutputStream(STDOUT_FRAME_PREFIX)));
mStderr = new PrintStream(
new FramingOutputStream(STDERR_FRAME_PREFIX));
}
void saveCropping(final DataOutputStream out, final int tag, final int index, final RectF cropping)
throws IOException {
out.writeByte(tag);
out.writeShort(index);
out.writeFloat(cropping.left);
out.writeFloat(cropping.top);
out.writeFloat(cropping.right);
out.writeFloat(cropping.bottom);
}
@Override
public void saveScreenState(DataOutputStream dos) throws IOException {
dos.writeByte(selection == null ? 0 : selection.getName().length());
if (selection != null) {
dos.writeChars(selection.getName());
}
}
@Test
public void testUpdateBoolean() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
new DataOutputStream(out).writeBoolean(true);
long expected = getHashAndReset(out);
primitiveDataChecksum.updateBoolean(true);
Assert.assertEquals(expected, primitiveDataChecksum.getValue());
}
public void writeWire(final DataOutputStream out) throws IOException {
super.writeWire(out);
final ObjectOutputStream oos = new ObjectOutputStream(out);
try {
oos.writeObject(executable);
oos.flush();
} finally {
IOUtils.closeHard(oos);
}
}
private void doPost(String url, String content) throws IOException {
URL urlObj = new URL(url);
URLConnection conn = urlObj.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
conn.getInputStream().close();
}