The code i am using is simply for testing, here i test with gmail:
C# code:
private void button1_Click(object sender, EventArgs e)
{
string server = "smtp.gmail.com";
int port = 25;
client = new TcpClient();
client.Connect(server, port);
var stream = client.GetStream();
sslStream = new SslStream(stream);
sslStream.AuthenticateAsClient(server);
clearTextReader = new StreamReader(sslStream);
clearTextWriter = new StreamWriter(sslStream);
clearTextWriter.WriteLine("EHLO " + server);
clearTextWriter.Flush();
var response = clearTextReader.ReadLine();
Error(response);
}
But this errors with this error:
System.IO.IOException occurred
HResult=0x80131620
Message=The handshake failed due to an unexpected packet format.
Source=System
StackTrace:
at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation)
at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost)
When i try to do this on port 443, it works fine, however port 25, just errors all the time. I've tried everything but i can't find a solution. The certificate is valid, also when i try different servers it doesn't work.
Related
We're beginning to leverage MongoDB for search functionality in our application, to improve performance over how we used to do searches with SQL Server. Individual testing works fine, however now we've begun load testing with 40 concurrent "users" executing searches against MongoDB at once. Part way through each load test, many of the calls start erroring:
MongoDB.Driver.MongoConnectionException: An exception occurred while receiving a message from the server. ---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at MongoDB.Driver.Core.Misc.StreamExtensionMethods.ReadBytes(Stream stream, Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBuffer()
--- End of inner exception stack trace ---
at MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBuffer()
at MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveBuffer(Int32 responseTo, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Connections.BinaryConnection.ReceiveMessage(Int32 responseTo, IMessageEncoderSelector encoderSelector, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.AcquiredConnection.ReceiveMessage(Int32 responseTo, IMessageEncoderSelector encoderSelector, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocol[TResult](IWireProtocol`1 protocol, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Servers.Server.ServerChannel.Command[TResult](ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, IEnumerable`1 commandPayloads, IElementNameValidator commandValidator, BsonDocument additionalOptions, Action`1 postWriteAction, CommandResponseHandling responseHandling, IBsonSerializer`1 resultSerializer, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.CommandOperationBase`1.ExecuteProtocol(IChannelHandle channel, ICoreSessionHandle session, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.CommandOperationBase`1.ExecuteProtocol(IChannelSource channelSource, ICoreSessionHandle session, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.ReadCommandOperation`1.Execute(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.AggregateOperation`1.Execute(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.OperationExecutor.ExecuteReadOperation[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperation[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperation[TResult](IClientSessionHandle session, IReadOperation`1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.Aggregate[TResult](IClientSessionHandle session, PipelineDefinition`2 pipeline, AggregateOptions options, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass19_0`1.<Aggregate>b__0(IClientSessionHandle session)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.Aggregate[TResult](PipelineDefinition`2 pipeline, AggregateOptions options, CancellationToken cancellationToken)
at RealtorsPropertyResource.Rpr.MongoSearches.Model.QueryPropertiesForKeys[T](PerformanceMonitor performanceMonitor, PropertiesSearchCriteria criteria, RequiredDataResult requiredData)
at RealtorsPropertyResource.Rpr.MongoSearches.Model.SearchWithMongo(PropertiesSearchCriteria criteria, PerformanceMonitor performanceMonitor)
at RealtorsPropertyResource.Rpr.MongoSearches.Model.SearchForProperties(PropertiesSearchCriteria criteria, PerformanceMonitor performanceMonitor, Nullable`1 useMongo)
at RealtorsPropertyResource.Rpr.Websites.Main.AjaxService.ExecuteLoadTestSearch(AppPropertyMode appPropertyMode, SearchType searchType, String query) in C:\BuildAgents\RPR-Website\_work\4\s\Websites\Main\services\AjaxService.Search.cs:line 260
at SyncInvokeExecuteLoadTestSearch(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
We tested against two Mongo instances, one running on Windows and one running on Linux, and both are hitting this error. The searches that are completing successfully aren't slow, so I'm not confident this is a timeout issue, but perhaps maybe a max connection issue? I'm confused though because I thought the default connection limit for the MongoDB C# driver was 100 connections, and that limit for the MongoDB server itself was much higher than that.
Any suggestions of how to troubleshoot this error that only occurs while Mongo is under load?
In case it's relevant, here is how I'm instantiating a singleton MongoClient and IMongoDatabase:
public static class MongoContext
{
private static bool initialized = false;
private static string connectionString { get; set; }
private static IMongoDatabase database;
public static IMongoDatabase Database
{
get
{
if (database == null)
throw new InvalidOperationException("You must initialize the MongoContext first");
return database;
}
}
public static void Initialize()
{
if (!initialized)
{
initialized = true;
connectionString = RprConfigurationManager.GetConnectionString("MongoSearch");
Console.WriteLine("Connecting to MongoDB search database: " + connectionString);
var useSsl = connectionString.IndexOf("ssl=true", StringComparison.InvariantCultureIgnoreCase) >= 0;
var url = new MongoUrl(connectionString);
var clientSettings = MongoClientSettings.FromUrl(url);
clientSettings.SslSettings = new SslSettings();
clientSettings.SslSettings.CheckCertificateRevocation = false;
clientSettings.UseSsl = useSsl;
clientSettings.VerifySslCertificate = false;
var client = new MongoClient(clientSettings);
var lastSegment = connectionString.Split('/').Last();
var databaseSegments = lastSegment.Split('?');
var databaseName = databaseSegments.First();
databaseName = !String.IsNullOrEmpty(databaseName) ? databaseName : "rpr";
Console.WriteLine("Connecting to database: " + databaseName);
database = client.GetDatabase(databaseName);
SchemaInitializer.RegisterClassMaps();
}
}
}
Here are some mongod logs, in case it helps:
IXSCAN { CityPlaceId: 1, ForSaleGroupId: 1, DistressedGroupId: 1,
OffMarketGroupId: 1, ForLeaseGroupId: 1, ForSaleDistressedGroupId: 1,
OffMarketDistressedGroupId: 1, OrgId: 1, OrgSecurableId: 1,
OffMarketDate: 1, IsListingOnly: 1 } keysExamined:397707
docsExamined:332738 hasSortStage:1 cursorExhausted:1 numYields:20750
nreturned:1 reslen:1454 locks:{ Global: { acquireCount: { r: 21121 }
}, Database: { acquireCount: { r: 21121 } }, Collection: {
acquireCount: { r: 21121 } } } storage:{ data: { bytesRead:
7534883557, timeReadingMicros: 325960940 } } protocol:op_msg 356835ms
2019-08-19T19:43:08.856+0000 I NETWORK [conn285] Error sending
response to client: SocketException: An established connection was
aborted by the software in your host machine.. Ending connection from
172.27.129.209:65121 (connection id: 285) 2019-08-19T19:43:08.856+0000 I NETWORK [conn285] end connection 172.27.129.209:65121 (30
connections now open)
Here is mentioned that can be a problem with the driver, In our case we change the driver version from 2.5 to 2.10 and worked.
I'm writing a TCP Server and Client, in which the client will send the file and the server will save it. My send/save function is as following:
Server
public void saveFile2(Socket clientSocket) throws IOException
{
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
String fileName = dis.readUTF();
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int byteCount;
byte[] buffer = new byte[4096];
while ((byteCount = bis.read(buffer, 0, buffer.length)) > 0)
{
System.out.println("Test byteCount = "+byteCount);
bos.write(buffer, 0, byteCount);
break;
}
System.out.println("Saved file"+file.getName());
bos.close();
dis.close();
}
Client
public void sendFile2(String xmlpath) throws IOException, InterruptedException
{
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File file = new File(xmlpath);
System.out.println("Sending File : " + file.getName());
dos.writeUTF(file.getName());
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int bytesCount;
byte[] buffer = new byte[4096];
System.out.println("Sending file to server.");
while ((bytesCount = fis.read(buffer)) > 0 )
{
System.out.println(bytesCount);
bos.write(buffer, 0, bytesCount);
}
System.out.println("Finished sending.");
bis.close();
dos.flush();
}
Notice that I have added a break; command into the while loop of Server and the program work perfectly. But when I exclude it, I get this exception:
Test byteCount = 394
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at xml.xmlServer.saveFile2(xmlServer.java:72)
at xml.xmlServer.run(xmlServer.java:31)
This only occur when I include BufferedInputStream and BufferedOutputStream in my code. Can somebody help me explain what causes this exception ?
You're reading the filename but you aren't sending the filename. You're missing a writeUTF() call in the sender.
You also need to close the socket in the sender, or the DataOutputStream.
bos.write(buffer, 0, bytesCount);
Really this should be
dos.write(buffer, 0, bytesCount);
I'm trying to display data in a table format, by joining two tables 'Users' and 'Company' with Foreign key relation.
When I directly writes the code in controller with working fine
public ActionResult Index()
{
var model = new UserModel();
model.Users = db.Users
.OrderBy(o => o.CreatedBy)
.Include(c => c.Company).ToList();
return View(model);
}
but when i place the same code in WCF is throwing exception..
public List GetUsersList()
{
try
{
using (ProductionEntities db = new ProductionEntities())
{
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
IQueryable<User> _users = db.Users
.OrderBy(o => o.CreatedBy)
.Include(c => c.Company);
return _users.ToList();
}
}
catch (Exception ex)
{
ExceptionData exceptionData = new ExceptionData();
exceptionData.ErrorMessage = "Error in GetUsersList";
exceptionData.ErrorDetails = ex.ToString();
throw new FaultException<ExceptionData>(exceptionData, ex.Message);
}
}
The below is the Stack Trace Inner exception :
InnerException: System.Net.WebException
HResult=-2146233079
Message=The underlying connection was closed: An unexpected error occurred on a receive.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
Any idea???
Thank you,
That's due to the circular reference.
Check this link for Reference
also we need to set
ProductionEntities db = new ProductionEntities()
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
I used the following code to send my email with EnableSsl = true,the throw the following exception:
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
public static void SendEmailBySmtpServer(int currentSendCount)
{
try
{
var emailBodyJson = "Period Send Email From Service at -" + DateTime.Now +" Times="+currentSendCount;
emailBodyJson += " EnableSsl=" + ConfigurationManager.AppSettings["SmtpServer.EnableSsl"];
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string fromEmailAddress = appSettings["SmtpServer.FromEmailAddress"];
string toEmailAddress = appSettings["SmtpServer.UserFeedback.ToEmailAddress"];
string host = appSettings["SmtpServer.Host"];
var smtpClient = new SmtpClient(host);
var message = new MailMessage();
message.From = new MailAddress(fromEmailAddress);
message.To.Add(new MailAddress(toEmailAddress));
message.Subject = emailBodyJson;
message.IsBodyHtml = true;
message.Body = emailBodyJson;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = Convert.ToBoolean(appSettings["SmtpServer.EnableSsl"]);//if this changed to true then send failed
smtpClient.UseDefaultCredentials = true;
smtpClient.Send(message);
logger.Info("Send Email Count = "+currentSendCount);
}
catch (Exception ex)
{
logger.Error(ex);
}
To send an email you can use the following code, its working, But you have to use the appropriate .jar files.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "xxxx"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "xxxxx"; // GMail password
private static String RECIPIENT = "xxxxx#xxxx.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ..this is a test mail,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
// String host="localhost";
// props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.host", host);
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");//587
props.put("mail.smtp.auth", "true");
//System.out.println("success point 1");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
// System.out.println("success point 2");
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
//System.out.println("success point 3");
message.setSubject(subject);
message.setText(body);
// System.out.println("success point 4");
Transport transport = session.getTransport("smtp");
// System.out.println("success point 5");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
// System.out.println("success 6");
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
I have successfully displayed Pdf from Assets folder using Android Pdf Viewer library https://github.com/jblough/Android-Pdf-Viewer-Library. I am now trying to parse and display online pdf "http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf" but it is giving the following error:
<code>
04-19 03:17:04.995: W/System.err(27806): java.io.IOException: This may not be a PDF File
04-19 03:17:04.995: W/System.err(27806): at com.sun.pdfview.PDFFile.parseFile(PDFFile.java:1395)
04-19 03:17:04.995: W/System.err(27806): at com.sun.pdfview.PDFFile.<init>(PDFFile.java:140)
04-19 03:17:04.995: W/System.err(27806): at com.sun.pdfview.PDFFile.<init>(PDFFile.java:116)
04-19 03:17:04.995: W/System.err(27806): at net.sf.andpdf.pdfviewer.PdfViewerActivity.openFile(PdfViewerActivity.java:909)
04-19 03:17:04.995: W/System.err(27806): at net.sf.andpdf.pdfviewer.PdfViewerActivity$8.run(PdfViewerActivity.java:863)
04-19 03:17:04.995: W/System.err(27806): at java.lang.Thread.run(Thread.java:1027)
</code>
I am opening URL Connection connection as :
<code>
fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
byte[] bytes = new byte[is.available()];
is.read(bytes);
System.out.println("Byte Lenght: " + bytes.length);
ByteBuffer bb = ByteBuffer.NEW(bytes);
is.close();
openFile(bb, password);
</code>
Please help what can be the issue?
Thanks
The way you read the stream is not correct. You can use these utility classes (taken from DavidWebb):
/**
* Read an <code>InputStream</code> into <code>byte[]</code> until EOF.
* <br/>
* Does not close the InputStream!
*
* #param is the stream to read the bytes from
* #return all read bytes as an array
* #throws IOException
*/
public static byte[] readBytes(InputStream is) throws IOException {
if (is == null) {
return null;
}
byte[] responseBody;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
copyStream(is, baos);
baos.close();
responseBody = baos.toByteArray();
return responseBody;
}
/**
* Copy complete content of <code>InputStream</code> to <code>OutputStream</code> until EOF.
* <br/>
* Does not close the InputStream nor OutputStream!
*
* #param input the stream to read the bytes from
* #param output the stream to write the bytes to
* #throws IOException
*/
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int count;
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
}
}