public static string RunRootCmd(string command, char split) { Process process = null; var result = "false"; try { process = Runtime.GetRuntime().Exec("su"); var outputStream = process.OutputStream; var dataOutputStream = new DataOutputStream(outputStream); var cmds = command.Split(split); var temp = cmds.Aggregate("", (current, t) => current + (t + "\n")); dataOutputStream.WriteBytes(temp); dataOutputStream.Flush(); dataOutputStream.WriteBytes("exit\n"); dataOutputStream.Flush(); process.WaitFor(); result = InputStreamToString(new InputStreamAdapter(process.InputStream)); } catch { return(result); } finally { process?.Destroy(); } return(result); }
/// <summary> /// Writes controller data from the smartphone to the Raspberry /// or to the drone. /// </summary> /// <param name="args">Controller parameter (throttle, yaw, pitch, roll)</param> public void Write(params Int16[] args) { byte[] bytes = ConvertToByte(args); try { mDataOutputStream.Write(bytes); mDataOutputStream.Flush(); } catch (Exception ex) { Log.Debug("BTSocketWriter", "Error while sending data"); } }
/// <summary> /// Writes the Manifest to the specified OutputStream. /// Attributes.Name.MANIFEST_VERSION must be set in /// MainAttributes prior to invoking this method. /// </summary> /// <param name="out"> the output stream </param> /// <exception cref="IOException"> if an I/O error has occurred </exception> /// <seealso cref= #getMainAttributes </seealso> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void write(java.io.OutputStream out) throws java.io.IOException public virtual void Write(OutputStream @out) { DataOutputStream dos = new DataOutputStream(@out); // Write out the main attributes for the manifest Attr.WriteMain(dos); // Now write out the pre-entry attributes IEnumerator <java.util.Map_Entry <String, Attributes> > it = Entries_Renamed.GetEnumerator(); while (it.MoveNext()) { java.util.Map_Entry <String, Attributes> e = it.Current; StringBuffer buffer = new StringBuffer("Name: "); String value = e.Key; if (value != null) { sbyte[] vb = value.GetBytes("UTF8"); value = StringHelperClass.NewString(vb, 0, 0, vb.Length); } buffer.Append(value); buffer.Append("\r\n"); Make72Safe(buffer); dos.WriteBytes(buffer.ToString()); e.Value.Write(dos); } dos.Flush(); }
/// <summary>Writes the Manifest to the specified OutputStream.</summary> /// <remarks> /// Writes the Manifest to the specified OutputStream. /// Attributes.Name.MANIFEST_VERSION must be set in /// MainAttributes prior to invoking this method. /// </remarks> /// <param name="out">the output stream</param> /// <exception> /// IOException /// if an I/O error has occurred /// </exception> /// <seealso cref="GetMainAttributes()"/> /// <exception cref="IOException"/> public virtual void Write(OutputStream @out) { DataOutputStream dos = new DataOutputStream(@out); // Write out the main attributes for the manifest attr.WriteMain(dos); // Now write out the pre-entry attributes IEnumerator <KeyValuePair <string, Attributes> > it = entries.GetEnumerator(); while (it.MoveNext()) { KeyValuePair <string, Attributes> e = it.Current; StringBuilder buffer = new StringBuilder("Name: "); string value = e.Key; if (value != null) { byte[] vb = Sharpen.Runtime.GetBytesForString(value, "UTF8"); value = Encoding.UTF8.GetString(vb); } buffer.Append(value); buffer.Append("\r\n"); Make72Safe(buffer); dos.WriteBytes(buffer.ToString()); e.Value.Write(dos); } dos.Flush(); }
public byte[] toByteArray() { short datalen = 0; byte[] data = null; byte[] bytes = null; byte[] byteNew = null; try { if (dos != null) { dos.Flush(); data = ms.ToArray(); datalen = (short)data.Length; dos.Close(); } MemoryStream bos1 = new MemoryStream(datalen + 3); DataOutputStream dos1 = new DataOutputStream(new BinaryWriterIns(bos1)); dos1.WriteByteNew(command); dos1.WriteShort(datalen); if (datalen > 0) { dos1.Write(data); } bytes = bos1.ToArray(); byteNew = new byte[bytes.Length - 3]; int n = byteNew.Length; Array.Copy(bytes, 3, byteNew, 0, n); byteNew[0] = (byte)command; dos1.Close(); } catch (IOException e) { Debug.Log(e.ToString()); } return(byteNew); }
/// <summary> /// 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限) /// @param command 命令:String apkRoot = "chmod 777 " + getPackageCodePath(); RootCommand(apkRoot); /// @return 应用程序是/否获取Root权限 /// </summary> public static bool RootCommand(string command) { Process process = null; try { process = Runtime.GetRuntime().Exec("su"); using (var os = new DataOutputStream(process.OutputStream)) { os.WriteBytes(command + "\n"); os.WriteBytes("exit\n"); os.Flush(); } process.WaitFor(); } catch (Exception e) { return(false); } finally { if (process != null) { process.Destroy(); } } return(true); }
public byte[] ToByteArray() { MemoryStream byteArrayOutputStream = new MemoryStream(); DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream); outputStream.Write(RtpHeader.ToByteArray()); byte midiCommandHeader1 = 0; midiCommandHeader1 |= (byte)((B ? 1 : 0) << 7); midiCommandHeader1 |= (byte)((J ? 1 : 0) << 6); midiCommandHeader1 |= (byte)((Z ? 1 : 0) << 5); midiCommandHeader1 |= (byte)((P ? 1 : 0) << 4); if (B) { midiCommandHeader1 |= (byte)((Length & 0x0F00) >> 8); outputStream.WriteByte(midiCommandHeader1); outputStream.WriteByte(Length & 0x00FF); } else { midiCommandHeader1 |= (byte)Length; outputStream.WriteByte(midiCommandHeader1); } outputStream.Flush(); return(byteArrayOutputStream.ToArray()); }
/* * Replace block */ /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Net.Sockets.SocketException"/> private bool ReplaceBlock(ExtendedBlock block, DatanodeInfo source, DatanodeInfo sourceProxy, DatanodeInfo destination, StorageType targetStorageType) { Socket sock = new Socket(); try { sock.Connect(NetUtils.CreateSocketAddr(destination.GetXferAddr()), HdfsServerConstants .ReadTimeout); sock.SetKeepAlive(true); // sendRequest DataOutputStream @out = new DataOutputStream(sock.GetOutputStream()); new Sender(@out).ReplaceBlock(block, targetStorageType, BlockTokenSecretManager.DummyToken , source.GetDatanodeUuid(), sourceProxy); @out.Flush(); // receiveResponse DataInputStream reply = new DataInputStream(sock.GetInputStream()); DataTransferProtos.BlockOpResponseProto proto = DataTransferProtos.BlockOpResponseProto .ParseDelimitedFrom(reply); while (proto.GetStatus() == DataTransferProtos.Status.InProgress) { proto = DataTransferProtos.BlockOpResponseProto.ParseDelimitedFrom(reply); } return(proto.GetStatus() == DataTransferProtos.Status.Success); } finally { sock.Close(); } }
public byte[] ToByteArray() { MemoryStream byteArrayOutputStream = new MemoryStream(12); DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream); byte header1 = 0; header1 |= (byte)(Version << 6); header1 |= (byte)((PaddingFlag ? 1 : 0) << 5); header1 |= (byte)((ExtensionFlag ? 1 : 0) << 4); header1 |= ContributingSourceIdentifiersCount; outputStream.WriteByte(header1); byte header2 = 0; header2 |= (byte)((MarkerFlag ? 1 : 0) << 7); header2 |= PayloadType; outputStream.WriteByte(header2); outputStream.WriteShort(SequenceNumber); outputStream.WriteInt(Timestamp); outputStream.WriteInt(Ssrc); outputStream.Flush(); return(byteArrayOutputStream.ToArray()); }
/// <exception cref="System.IO.IOException"/> private static void Send(DataOutputStream @out, OP opcode, Message proto) { if (Log.IsTraceEnabled()) { Log.Trace("Sending DataTransferOp " + proto.GetType().Name + ": " + proto); } Op(@out, opcode); proto.WriteDelimitedTo(@out); @out.Flush(); }
public virtual void TestReplicationError() { // create a file of replication factor of 1 Path fileName = new Path("/test.txt"); int fileLen = 1; DFSTestUtil.CreateFile(fs, fileName, 1, (short)1, 1L); DFSTestUtil.WaitReplication(fs, fileName, (short)1); // get the block belonged to the created file LocatedBlocks blocks = NameNodeAdapter.GetBlockLocations(cluster.GetNameNode(), fileName .ToString(), 0, (long)fileLen); NUnit.Framework.Assert.AreEqual("Should only find 1 block", blocks.LocatedBlockCount (), 1); LocatedBlock block = blocks.Get(0); // bring up a second datanode cluster.StartDataNodes(conf, 1, true, null, null); cluster.WaitActive(); int sndNode = 1; DataNode datanode = cluster.GetDataNodes()[sndNode]; // replicate the block to the second datanode IPEndPoint target = datanode.GetXferAddress(); Socket s = Sharpen.Extensions.CreateSocket(target.Address, target.Port); // write the header. DataOutputStream @out = new DataOutputStream(s.GetOutputStream()); DataChecksum checksum = DataChecksum.NewDataChecksum(DataChecksum.Type.Crc32, 512 ); new Sender(@out).WriteBlock(block.GetBlock(), StorageType.Default, BlockTokenSecretManager .DummyToken, string.Empty, new DatanodeInfo[0], new StorageType[0], null, BlockConstructionStage .PipelineSetupCreate, 1, 0L, 0L, 0L, checksum, CachingStrategy.NewDefaultStrategy (), false, false, null); @out.Flush(); // close the connection before sending the content of the block @out.Close(); // the temporary block & meta files should be deleted string bpid = cluster.GetNamesystem().GetBlockPoolId(); FilePath storageDir = cluster.GetInstanceStorageDir(sndNode, 0); FilePath dir1 = MiniDFSCluster.GetRbwDir(storageDir, bpid); storageDir = cluster.GetInstanceStorageDir(sndNode, 1); FilePath dir2 = MiniDFSCluster.GetRbwDir(storageDir, bpid); while (dir1.ListFiles().Length != 0 || dir2.ListFiles().Length != 0) { Sharpen.Thread.Sleep(100); } // then increase the file's replication factor fs.SetReplication(fileName, (short)2); // replication should succeed DFSTestUtil.WaitReplication(fs, fileName, (short)1); // clean up the file fs.Delete(fileName, false); }
public void Write(params byte[] bytes) { try { mDataOutputStream.Write(bytes); mDataOutputStream.Flush(); }catch (Exception ex) { Log.Debug("BTSocketWriter", "Error while sending data"); } }
/// <summary> /// <see cref="AsyncTask.DoInBackground(Java.Lang.Object[])"/> /// </summary> protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params) { ServerSocket serverSocket = new ServerSocket(m_Port); Socket clientSocket = serverSocket.Accept(); DataOutputStream outputStream = new DataOutputStream(clientSocket.OutputStream); outputStream.WriteUTF("Coucou"); outputStream.Flush(); return(null); }
public virtual void TestCompressorDecopressorLogicWithCompressionStreams() { DataOutputStream deflateOut = null; DataInputStream inflateIn = null; int ByteSize = 1024 * 100; byte[] bytes = Generate(ByteSize); int bufferSize = 262144; int compressionOverhead = (bufferSize / 6) + 32; try { DataOutputBuffer compressedDataBuffer = new DataOutputBuffer(); CompressionOutputStream deflateFilter = new BlockCompressorStream(compressedDataBuffer , new Lz4Compressor(bufferSize), bufferSize, compressionOverhead); deflateOut = new DataOutputStream(new BufferedOutputStream(deflateFilter)); deflateOut.Write(bytes, 0, bytes.Length); deflateOut.Flush(); deflateFilter.Finish(); DataInputBuffer deCompressedDataBuffer = new DataInputBuffer(); deCompressedDataBuffer.Reset(compressedDataBuffer.GetData(), 0, compressedDataBuffer .GetLength()); CompressionInputStream inflateFilter = new BlockDecompressorStream(deCompressedDataBuffer , new Lz4Decompressor(bufferSize), bufferSize); inflateIn = new DataInputStream(new BufferedInputStream(inflateFilter)); byte[] result = new byte[ByteSize]; inflateIn.Read(result); Assert.AssertArrayEquals("original array not equals compress/decompressed array", result, bytes); } catch (IOException) { NUnit.Framework.Assert.Fail("testLz4CompressorDecopressorLogicWithCompressionStreams ex error !!!" ); } finally { try { if (deflateOut != null) { deflateOut.Close(); } if (inflateIn != null) { inflateIn.Close(); } } catch (Exception) { } } }
public void Write(params byte[] bytes) { try { mOutputStream.Write(bytes); mOutputStream.Flush(); } catch (Java.Lang.Exception ex) { Log.Debug("WifiSocketWriter", "Error while sending data"); } }
/// <exception cref="System.IO.IOException"/> private void SendSaslMessage(DataOutputStream @out, RpcHeaderProtos.RpcSaslProto message) { if (Log.IsDebugEnabled()) { Log.Debug("Sending sasl message " + message); } ProtobufRpcEngine.RpcRequestMessageWrapper request = new ProtobufRpcEngine.RpcRequestMessageWrapper (saslHeader, message); @out.WriteInt(request.GetLength()); request.Write(@out); @out.Flush(); }
/// <exception cref="System.IO.IOException"/> private byte[] PrepareFakePacket(byte[] data, byte[] sums) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); int packetLen = data.Length + sums.Length + Ints.Bytes; PacketHeader header = new PacketHeader(packetLen, OffsetInBlock, Seqno, false, data .Length, false); header.Write(dos); dos.Write(sums); dos.Write(data); dos.Flush(); return(baos.ToByteArray()); }
/// <exception cref="System.IO.IOException"/> protected internal virtual void WriteObject(Writable obj, DataOutputStream stream ) { // For Text and BytesWritable, encode them directly, so that they end up // in C++ as the natural translations. DataOutputBuffer buffer = new DataOutputBuffer(); if (obj is Text) { Text t = (Text)obj; int len = t.GetLength(); WritableUtils.WriteVLong(stream, len); stream.Flush(); stream.Write(t.GetBytes(), 0, len); stream.Flush(); } else { if (obj is BytesWritable) { BytesWritable b = (BytesWritable)obj; int len = b.GetLength(); WritableUtils.WriteVLong(stream, len); stream.Write(b.GetBytes(), 0, len); } else { buffer.Reset(); obj.Write(buffer); int length = buffer.GetLength(); WritableUtils.WriteVInt(stream, length); stream.Write(buffer.GetData(), 0, length); } } stream.Flush(); }
public byte[] ToByteArray() { MemoryStream outputStream = new MemoryStream(); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.Write(MIDI_COMMAND_HEADER1); dataOutputStream.Write(MIDI_COMMAND_HEADER2); dataOutputStream.Write(System.Text.Encoding.UTF8.GetBytes(CommandWord.ToString())); dataOutputStream.WriteInt(Ssrc); dataOutputStream.WriteByte(Count); dataOutputStream.Write(new byte[3]); dataOutputStream.WriteLong(Timestamp1); dataOutputStream.WriteLong(Timestamp2); dataOutputStream.WriteLong(Timestamp3); dataOutputStream.Flush(); return(outputStream.ToArray()); }
/// <summary> /// Writes controller data from the smartphone to the Raspberry or to the drone /// through the socket connection. /// Closes the socket if writing fails. /// </summary> /// <param name="args">Controller parameter (throttle, yaw, pitch, roll)</param> public void Write(params Int16[] args) { mLogData += mStartMillis + "," + args[0] + "," + args[1] + "," + args[2] + "," + args[3] + "," + (0) + "\n"; Log.Debug(TAG, mLogData); mStartMillis += 10; byte[] bytes = ConvertToByte(args); try { mDataOutputStream.Write(bytes, 0, bytes.Length); mDataOutputStream.Flush(); } catch (Java.Lang.Exception ex) { Log.Debug(TAG, "Error while sending data (" + ex.Message + ")"); Cancel(); } }
private void OnSendData(object sender, EventArgs e) { Java.Lang.String text = new Java.Lang.String(etInput.Text); byte[] byteText = text.GetBytes(); try { mOutputStream.Write(byteText, 0, byteText.Length); mOutputStream.Flush(); } catch (System.Exception ex) { Cancel(); System.Console.WriteLine(ex.Message); } etInput.Text = ""; }
public byte[] ToByteArray() { MemoryStream byteArrayOutputStream = new MemoryStream(); DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream); outputStream.Write(MidiCommandHeader.ToByteArray()); bool first = true; foreach (MidiTimestampPair message in Messages) { if (first && !MidiCommandHeader.Z) { first = false; } else { int timestamp = message.Timestamp; if (timestamp > 0x0FFFFFFF) { throw new IllegalArgumentException("Timestamp too big: " + timestamp); } if (timestamp > 0) { int numberOfSeptets = (int)System.Math.Ceiling(Integer.BitCount(Integer.HighestOneBit(timestamp) * 2 - 1) / 7.0); while (numberOfSeptets > 0) { outputStream.WriteByte( (numberOfSeptets > 1 ? 0x80 : 0) | ((timestamp >> ((numberOfSeptets - 1) * 7)) & 0x7F)); numberOfSeptets--; } } else { outputStream.WriteByte(0); } } outputStream.Write(message.MidiMessage.Data); } outputStream.Flush(); return(byteArrayOutputStream.ToArray()); }
public override byte[] ToByteArray() { try { MemoryStream outputStream = new MemoryStream(); DataOutputStream dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.Write(MIDI_COMMAND_HEADER1); dataOutputStream.Write(MIDI_COMMAND_HEADER2); dataOutputStream.Write(System.Text.Encoding.UTF8.GetBytes(CommandWord.ToString())); dataOutputStream.WriteInt(ProtocolVersion); dataOutputStream.WriteInt(InitiatorToken); dataOutputStream.WriteInt(Ssrc); dataOutputStream.Flush(); return(outputStream.ToArray()); } catch (Exception e) { throw new System.IO.IOException(e.Message); } }
protected override string RunInBackground(params string[] @params) { for (int i = 0; i <= 2; i++) { try { String sourceFileUri = MainActivity.rec_video_uri[i]; Java.Net.HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (sourceFile.IsFile) { try { String upLoadServerUri = "http://140.114.28.134/VideoUpload/uploads/upload.php"; // Ppen a URL connection to the Server FileInputStream fileInputStream = new FileInputStream( sourceFile); Java.Net.URL url = new Java.Net.URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (Java.Net.HttpURLConnection)url.OpenConnection(); conn.DoInput = true; // Allow Inputs conn.DoOutput = true; // Allow Outputs conn.UseCaches = false; // Don't use a Cached Copy conn.RequestMethod = "POST"; conn.SetRequestProperty("Connection", "Keep-Alive"); conn.SetRequestProperty("ENCTYPE", "multipart/form-data"); conn.SetRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.SetRequestProperty("upload_name", sourceFileUri); dos = new DataOutputStream(conn.OutputStream); dos.WriteBytes(twoHyphens + boundary + lineEnd); dos.WriteBytes("Content-Disposition: form-data; name=\"upload_name\";filename=\"" + sourceFileUri + "\"" + lineEnd); dos.WriteBytes(lineEnd); // Create a buffer of maximum size bytesAvailable = fileInputStream.Available(); bufferSize = Math.Min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file and write bytesRead = fileInputStream.Read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.Write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.Available(); bufferSize = Math .Min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.Read(buffer, 0, bufferSize); } // Send multipart form data necesssary after file dos.WriteBytes(lineEnd); dos.WriteBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.ResponseCode; String serverResponseMessage = conn .ResponseMessage; // Close the streams fileInputStream.Close(); dos.Flush(); dos.Close(); } catch (Exception e) { System.Console.WriteLine(e.ToString()); } } // End if-else block } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } } progressDialog.Dismiss(); return("Finished"); }
public virtual void TestDataTransferProtocol() { Random random = new Random(); int oneMil = 1024 * 1024; Path file = new Path("dataprotocol.dat"); int numDataNodes = 1; Configuration conf = new HdfsConfiguration(); conf.SetInt(DFSConfigKeys.DfsReplicationKey, numDataNodes); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).NumDataNodes(numDataNodes ).Build(); try { cluster.WaitActive(); datanode = cluster.GetFileSystem().GetDataNodeStats(HdfsConstants.DatanodeReportType .Live)[0]; dnAddr = NetUtils.CreateSocketAddr(datanode.GetXferAddr()); FileSystem fileSys = cluster.GetFileSystem(); int fileLen = Math.Min(conf.GetInt(DFSConfigKeys.DfsBlockSizeKey, 4096), 4096); CreateFile(fileSys, file, fileLen); // get the first blockid for the file ExtendedBlock firstBlock = DFSTestUtil.GetFirstBlock(fileSys, file); string poolId = firstBlock.GetBlockPoolId(); long newBlockId = firstBlock.GetBlockId() + 1; recvBuf.Reset(); sendBuf.Reset(); // bad version recvOut.WriteShort((short)(DataTransferProtocol.DataTransferVersion - 1)); sendOut.WriteShort((short)(DataTransferProtocol.DataTransferVersion - 1)); SendRecvData("Wrong Version", true); // bad ops sendBuf.Reset(); sendOut.WriteShort((short)DataTransferProtocol.DataTransferVersion); sendOut.WriteByte(OP.WriteBlock.code - 1); SendRecvData("Wrong Op Code", true); /* Test OP_WRITE_BLOCK */ sendBuf.Reset(); DataChecksum badChecksum = Org.Mockito.Mockito.Spy(DefaultChecksum); Org.Mockito.Mockito.DoReturn(-1).When(badChecksum).GetBytesPerChecksum(); WriteBlock(poolId, newBlockId, badChecksum); recvBuf.Reset(); SendResponse(DataTransferProtos.Status.Error, null, null, recvOut); SendRecvData("wrong bytesPerChecksum while writing", true); sendBuf.Reset(); recvBuf.Reset(); WriteBlock(poolId, ++newBlockId, DefaultChecksum); PacketHeader hdr = new PacketHeader(4, 0, 100, false, -1 - random.Next(oneMil), false ); // size of packet // offset in block, // seqno // last packet // bad datalen hdr.Write(sendOut); SendResponse(DataTransferProtos.Status.Success, string.Empty, null, recvOut); new PipelineAck(100, new int[] { PipelineAck.CombineHeader(PipelineAck.ECN.Disabled , DataTransferProtos.Status.Error) }).Write(recvOut); SendRecvData("negative DATA_CHUNK len while writing block " + newBlockId, true); // test for writing a valid zero size block sendBuf.Reset(); recvBuf.Reset(); WriteBlock(poolId, ++newBlockId, DefaultChecksum); hdr = new PacketHeader(8, 0, 100, true, 0, false); // size of packet // OffsetInBlock // sequencenumber // lastPacketInBlock // chunk length hdr.Write(sendOut); sendOut.WriteInt(0); // zero checksum sendOut.Flush(); //ok finally write a block with 0 len SendResponse(DataTransferProtos.Status.Success, string.Empty, null, recvOut); new PipelineAck(100, new int[] { PipelineAck.CombineHeader(PipelineAck.ECN.Disabled , DataTransferProtos.Status.Success) }).Write(recvOut); SendRecvData("Writing a zero len block blockid " + newBlockId, false); /* Test OP_READ_BLOCK */ string bpid = cluster.GetNamesystem().GetBlockPoolId(); ExtendedBlock blk = new ExtendedBlock(bpid, firstBlock.GetLocalBlock()); long blkid = blk.GetBlockId(); // bad block id sendBuf.Reset(); recvBuf.Reset(); blk.SetBlockId(blkid - 1); sender.ReadBlock(blk, BlockTokenSecretManager.DummyToken, "cl", 0L, fileLen, true , CachingStrategy.NewDefaultStrategy()); SendRecvData("Wrong block ID " + newBlockId + " for read", false); // negative block start offset -1L sendBuf.Reset(); blk.SetBlockId(blkid); sender.ReadBlock(blk, BlockTokenSecretManager.DummyToken, "cl", -1L, fileLen, true , CachingStrategy.NewDefaultStrategy()); SendRecvData("Negative start-offset for read for block " + firstBlock.GetBlockId( ), false); // bad block start offset sendBuf.Reset(); sender.ReadBlock(blk, BlockTokenSecretManager.DummyToken, "cl", fileLen, fileLen, true, CachingStrategy.NewDefaultStrategy()); SendRecvData("Wrong start-offset for reading block " + firstBlock.GetBlockId(), false ); // negative length is ok. Datanode assumes we want to read the whole block. recvBuf.Reset(); ((DataTransferProtos.BlockOpResponseProto)DataTransferProtos.BlockOpResponseProto .NewBuilder().SetStatus(DataTransferProtos.Status.Success).SetReadOpChecksumInfo (DataTransferProtos.ReadOpChecksumInfoProto.NewBuilder().SetChecksum(DataTransferProtoUtil .ToProto(DefaultChecksum)).SetChunkOffset(0L)).Build()).WriteDelimitedTo(recvOut ); sendBuf.Reset(); sender.ReadBlock(blk, BlockTokenSecretManager.DummyToken, "cl", 0L, -1L - random. Next(oneMil), true, CachingStrategy.NewDefaultStrategy()); SendRecvData("Negative length for reading block " + firstBlock.GetBlockId(), false ); // length is more than size of block. recvBuf.Reset(); SendResponse(DataTransferProtos.Status.Error, null, "opReadBlock " + firstBlock + " received exception java.io.IOException: " + "Offset 0 and length 4097 don't match block " + firstBlock + " ( blockLen 4096 )", recvOut); sendBuf.Reset(); sender.ReadBlock(blk, BlockTokenSecretManager.DummyToken, "cl", 0L, fileLen + 1, true, CachingStrategy.NewDefaultStrategy()); SendRecvData("Wrong length for reading block " + firstBlock.GetBlockId(), false); //At the end of all this, read the file to make sure that succeeds finally. sendBuf.Reset(); sender.ReadBlock(blk, BlockTokenSecretManager.DummyToken, "cl", 0L, fileLen, true , CachingStrategy.NewDefaultStrategy()); ReadFile(fileSys, file, fileLen); } finally { cluster.Shutdown(); } }
private bool SendFile(File file, out string response) { var result = false; response = ""; try { // https://stackoverflow.com/questions/25398200/uploading-file-in-php-server-from-android-device/37953351 HttpURLConnection conn = null; DataOutputStream dos = null; string lineEnd = "\r\n"; string twoHyphens = "--"; string boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(UpLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection)url.OpenConnection(); conn.DoInput = true; // Allow Inputs conn.DoOutput = true; // Allow Outputs conn.UseCaches = false; // Don't use a Cached Copy conn.RequestMethod = "POST"; conn.AddRequestProperty("Connection", "Keep-Alive"); conn.AddRequestProperty("ENCTYPE", "multipart/form-data"); conn.AddRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.AddRequestProperty("file", file.AbsolutePath); dos = new DataOutputStream(conn.OutputStream); //getOutputStream()); dos.WriteBytes(twoHyphens + boundary + lineEnd); dos.WriteBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + file.AbsolutePath + "\"" + lineEnd); dos.WriteBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.Available(); bufferSize = Math.Min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.Read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.Write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.Available(); bufferSize = Math.Min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.Read(buffer, 0, bufferSize); } // send multipart form data necesssary after file // data... dos.WriteBytes(lineEnd); dos.WriteBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) var serverResponseCode = conn.ResponseCode; if (serverResponseCode == HttpStatus.Ok) { Log += "serverResponseCode = OK\r\n"; result = true; var rd = new BufferedReader(new InputStreamReader(conn.InputStream)); var sb = new StringBuilder(); string line; while ((line = rd.ReadLine()) != null) { sb.Append(line + '\r'); } rd.Close(); response = sb.ToString(); } // close the streams fileInputStream.Close(); dos.Flush(); dos.Close(); } catch (Exception e) { Log += "1 error " + e.StackTrace + "\r\n"; e.PrintStackTrace(); } } catch (Exception ex) { Log += "2 error " + ex.StackTrace + "\r\n"; ex.PrintStackTrace(); } return(result); }
/// <summary>Computes and returns the value of SVUID.</summary> /// <returns>the serial version UID.</returns> /// <exception cref="IOException">if an I/O error occurs.</exception> protected internal virtual long ComputeSVUID() { // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). long svuid = 0; using (var byteArrayOutputStream = new MemoryStream()) { using (var dataOutputStream = new DataOutputStream(byteArrayOutputStream.ToOutputStream() )) { // 1. The class name written using UTF encoding. dataOutputStream.WriteUTF(name.Replace('/', '.')); // 2. The class modifiers written as a 32-bit integer. var mods = access; if (mods.HasFlagFast(AccessFlags.Interface)) { mods = svuidMethods.Count == 0 ? mods & ~AccessFlags.Abstract : mods | AccessFlags.Abstract; } dataOutputStream.WriteInt((int)(mods & (AccessFlags.Public | AccessFlags.Final | AccessFlags.Interface | AccessFlags.Abstract))); // 3. The name of each interface sorted by name written using UTF encoding. Array.Sort(interfaces); foreach (var interfaceName in interfaces) { dataOutputStream.WriteUTF(interfaceName.Replace('/', '.')); } // 4. For each field of the class sorted by field name (except private static and private // transient fields): // 1. The name of the field in UTF encoding. // 2. The modifiers of the field written as a 32-bit integer. // 3. The descriptor of the field in UTF encoding. // Note that field signatures are not dot separated. Method and constructor signatures are dot // separated. Go figure... WriteItems(svuidFields, dataOutputStream, false); // 5. If a class initializer exists, write out the following: // 1. The name of the method, <clinit>, in UTF encoding. // 2. The modifier of the method, ACC_STATIC, written as a 32-bit integer. // 3. The descriptor of the method, ()V, in UTF encoding. if (hasStaticInitializer) { dataOutputStream.WriteUTF(Clinit); dataOutputStream.WriteInt((int)AccessFlags.Static); dataOutputStream.WriteUTF("()V"); } // 6. For each non-private constructor sorted by method name and signature: // 1. The name of the method, <init>, in UTF encoding. // 2. The modifiers of the method written as a 32-bit integer. // 3. The descriptor of the method in UTF encoding. WriteItems(svuidConstructors, dataOutputStream, true); // 7. For each non-private method sorted by method name and signature: // 1. The name of the method in UTF encoding. // 2. The modifiers of the method written as a 32-bit integer. // 3. The descriptor of the method in UTF encoding. WriteItems(svuidMethods, dataOutputStream, true); dataOutputStream.Flush(); // 8. The SHA-1 algorithm is executed on the stream of bytes produced by DataOutputStream and // produces five 32-bit values sha[0..4]. var hashBytes = ComputeSHAdigest(byteArrayOutputStream.ToArray()); // 9. The hash value is assembled from the first and second 32-bit values of the SHA-1 message // digest. If the result of the message digest, the five 32-bit words H0 H1 H2 H3 H4, is in an // array of five int values named sha, the hash value would be computed as follows: for (var i = Math.Min(hashBytes.Length, 8) - 1; i >= 0; i--) { svuid = (svuid << 8) | (hashBytes[i] & 0xFF); } } } return(svuid); }
/// <exception cref="System.IO.IOException"/> private static void CodecTest(Configuration conf, int seed, int count, string codecClass ) { // Create the codec CompressionCodec codec = null; try { codec = (CompressionCodec)ReflectionUtils.NewInstance(conf.GetClassByName(codecClass ), conf); } catch (TypeLoadException) { throw new IOException("Illegal codec!"); } Log.Info("Created a Codec object of type: " + codecClass); // Generate data DataOutputBuffer data = new DataOutputBuffer(); RandomDatum.Generator generator = new RandomDatum.Generator(seed); for (int i = 0; i < count; ++i) { generator.Next(); RandomDatum key = generator.GetKey(); RandomDatum value = generator.GetValue(); key.Write(data); value.Write(data); } Log.Info("Generated " + count + " records"); // Compress data DataOutputBuffer compressedDataBuffer = new DataOutputBuffer(); CompressionOutputStream deflateFilter = codec.CreateOutputStream(compressedDataBuffer ); DataOutputStream deflateOut = new DataOutputStream(new BufferedOutputStream(deflateFilter )); deflateOut.Write(data.GetData(), 0, data.GetLength()); deflateOut.Flush(); deflateFilter.Finish(); Log.Info("Finished compressing data"); // De-compress data DataInputBuffer deCompressedDataBuffer = new DataInputBuffer(); deCompressedDataBuffer.Reset(compressedDataBuffer.GetData(), 0, compressedDataBuffer .GetLength()); CompressionInputStream inflateFilter = codec.CreateInputStream(deCompressedDataBuffer ); DataInputStream inflateIn = new DataInputStream(new BufferedInputStream(inflateFilter )); // Check DataInputBuffer originalData = new DataInputBuffer(); originalData.Reset(data.GetData(), 0, data.GetLength()); DataInputStream originalIn = new DataInputStream(new BufferedInputStream(originalData )); for (int i_1 = 0; i_1 < count; ++i_1) { RandomDatum k1 = new RandomDatum(); RandomDatum v1 = new RandomDatum(); k1.ReadFields(originalIn); v1.ReadFields(originalIn); RandomDatum k2 = new RandomDatum(); RandomDatum v2 = new RandomDatum(); k2.ReadFields(inflateIn); v2.ReadFields(inflateIn); Assert.True("original and compressed-then-decompressed-output not equal" , k1.Equals(k2) && v1.Equals(v2)); // original and compressed-then-decompressed-output have the same hashCode IDictionary <RandomDatum, string> m = new Dictionary <RandomDatum, string>(); m[k1] = k1.ToString(); m[v1] = v1.ToString(); string result = m[k2]; Assert.Equal("k1 and k2 hashcode not equal", result, k1.ToString ()); result = m[v2]; Assert.Equal("v1 and v2 hashcode not equal", result, v1.ToString ()); } // De-compress data byte-at-a-time originalData.Reset(data.GetData(), 0, data.GetLength()); deCompressedDataBuffer.Reset(compressedDataBuffer.GetData(), 0, compressedDataBuffer .GetLength()); inflateFilter = codec.CreateInputStream(deCompressedDataBuffer); // Check originalIn = new DataInputStream(new BufferedInputStream(originalData)); int expected; do { expected = originalIn.Read(); Assert.Equal("Inflated stream read by byte does not match", expected , inflateFilter.Read()); }while (expected != -1); Log.Info("SUCCESS! Completed checking " + count + " records"); }
/// <summary> /// 心跳请求 /// </summary> public void HeartBeat() { try { // 创建HTTP连接 using (HttpURLConnection httpConn = Settings.url.OpenConnection() as HttpURLConnection) { httpConn.RequestMethod = "POST"; // 启用POST方式 httpConn.UseCaches = false; // 不启用缓存 httpConn.DoOutput = true; // 启用输出流 httpConn.DoInput = true; // 启用输入流 httpConn.InstanceFollowRedirects = true; // 启用HTTP重定向 //httpConn.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置请求类型 httpConn.SetRequestProperty("Content-Type", "application/json"); // 设置请求类型 httpConn.ConnectTimeout = 10000; // 设置超时时间 // 获取输出流 using (DataOutputStream outStream = new DataOutputStream(httpConn.OutputStream)) { // 格式化心跳参数 if (!Settings.HeartBeatParams.Has("action")) { Settings.HeartBeatParams.Put("action", "AdSubAppHeartBeat"); } if (!Settings.HeartBeatParams.Has("cpuId")) { //Settings.HeartBeatParams.Put("cpuId", Settings.CpuId); Settings.HeartBeatParams.Put("cpuId", "666999"); } if (!Settings.HeartBeatParams.Has("version")) { Settings.HeartBeatParams.Put("version", Settings.Version); } outStream.WriteBytes(Settings.HeartBeatParams.ToString().Replace("\r", "").Replace("\n", "").Replace(" ", "")); // 将数据写入输出流 Settings.HeartBeatParams.Remove("lastCmd"); Settings.HeartBeatParams.Remove("errMsg"); outStream.Flush(); // 立刻输出缓存数据 } // 判断是否响应成功 if (httpConn.ResponseCode == HttpStatus.Ok) { using (InputStreamReader inStream = new InputStreamReader(httpConn.InputStream)) // 获取输入流 using (BufferedReader buffer = new BufferedReader(inStream)) // 获取输入流读取器 { string inputLine = null, heartBeatResult = null; while ((inputLine = buffer.ReadLine()) != null) { heartBeatResult += inputLine + "\n"; } // 解析心跳返回数据 ParseHeartBeatResult(heartBeatResult); } } else { long Code = (long)httpConn.ResponseCode; // HTTP error RunOnUiThread(() => { Toast.MakeText(this, "心跳线程: HTTP error code " + Code, ToastLength.Long).Show(); }); } httpConn.Disconnect(); // 断开HTTP连接 } } catch (Exception e) { System.Console.WriteLine("HeartBeat Exception: " + e.Message); } }
private async void Backup(int requestCode, Intent intent, bool confirmNoPassword = false) { var password = _passwordDialog.Password; if (!confirmNoPassword && password == "") { ShowNoPasswordDialog(requestCode, intent); return; } var backup = new Backup { Authenticators = await _connection.QueryAsync <Authenticator>("SELECT * FROM authenticator"), Categories = await _connection.QueryAsync <Category>("SELECT * FROM category"), AuthenticatorCategories = await _connection.QueryAsync <AuthenticatorCategory>("SELECT * FROM authenticatorcategory") }; var json = JsonConvert.SerializeObject(backup); byte[] dataToWrite; if (password != "") { var sha256 = SHA256.Create(); var keyMaterial = sha256.ComputeHash(Encoding.UTF8.GetBytes(password)); var data = Encoding.UTF8.GetBytes(json); var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); var key = provider.CreateSymmetricKey(keyMaterial); dataToWrite = WinRTCrypto.CryptographicEngine.Encrypt(key, data); } else { dataToWrite = Encoding.UTF8.GetBytes(json); } switch (requestCode) { case DeviceStorageCode: var filename = intent.GetStringExtra("filename") + ".authpro"; var path = Path.Combine(intent.GetStringExtra("path"), filename); await File.WriteAllBytesAsync(path, dataToWrite); break; case StorageAccessFrameworkCode: var output = ContentResolver.OpenOutputStream(intent.Data); // Use Java streams, because a bug in Xamarin creates 0 byte files //var writer = new BufferedWriter(new OutputStreamWriter(output)); var dataStream = new DataOutputStream(output); foreach (var b in dataToWrite) { dataStream.Write(b); } dataStream.Flush(); dataStream.Close(); break; } Toast.MakeText(this, GetString(Resource.String.saveSuccess), ToastLength.Long).Show(); Finish(); }