?
Solved

cover code to java

Posted on 2010-11-09
2
Medium Priority
?
576 Views
Last Modified: 2012-06-21
Hi

can you help me convert this code to java. i think this code is in c sharp

public void PingServer()
        {
            byte[] bytes = null;
            HttpWebRequest request = null;
            Stream ReceiveStream = null;
            string url = emailServer +  "/Microsoft-Server-ActiveSync?Cmd=PING&User=srosario&DeviceID=123456789&DeviceType=PocketPc";
 
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/vnd.ms-sync.wbxml";
            request.Accept = "*/*";
            request.Headers.Add("MS-ASProtocolVersion", "2.5");
            request.Headers.Add("Accept-Language", "en-us");
            request.UserAgent = "MSFT-PPC/0.0.0";
            request.Credentials = userCred;
            request.KeepAlive = true;
         
            //string Body = "<Ping><LifeTime>900</LifeTime><Folders><Folder>Inbox</Folder></Folders></Ping>";
            //string Body = "<Ping><HeartbeatInterval>480</HeartbeatInterval></Ping>";
            //string Body = "<?xml version='1.0'?><Ping><HeartbeatInterval>480</HeartbeatInterval><LifeTime>900</LifeTime><Folders><Folder>Inbox</Folder></Folders></Ping>";
            string Body = "";// "<?xml version='1.0' encoding='utf-8'?><Ping xmlns='Ping'><HeartbeatInterval>1800</HeartbeatInterval></Ping>";
            //string Body = "<Ping xmlns='Ping'><HeartbeatInterval>1800</HeartbeatInterval></Ping>";
 
            bytes = Encoding.UTF8.GetBytes((string)Body);
            request.ContentLength = bytes.Length;
 
            Stream newStream = request.GetRequestStream();
            newStream.Write(bytes, 0, bytes.Length);
            newStream.Close();
 
            string StandardResponse = "{0} Poll ID# {1} Returned {2}";
 
            try
            {
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                string xml;
                HttpWebResponse result;
 
                using (result = (HttpWebResponse)request.GetResponse())
                {
                    ReceiveStream = result.GetResponseStream();
                    StreamReader sr = new StreamReader(ReceiveStream, encode);
                    xml = sr.ReadToEnd();
                    result.Close();
                }
 
                if (xml.IndexOf("204 No Content") > 0)
                {
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "\"No Content\": Nothing has changed"));
                    return;
                }
 
                if (xml.IndexOf("412 Precondition Failed") > 0)  // means the subscriptionID is not longer valid
                {
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "412 - Invalid Subscription ID"));
                    SubscriptionID = null;
                    // could do Subscribe and then call Poll again... but might end up in loop.
                    // probably should send event to the event log so user knows that their
                    // poll interval is too short.  A Poll should reset the timeout.
                }
 
                if (xml.IndexOf("500 Internal Server Error") > 0)
                {
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "500 Internal Server Error"));
                    throw new ApplicationException("An internal server error occured, unable to complete request.");
                }
 
                if (result.StatusCode == HttpStatusCode.OK)
                {
                    // This means that something has changed.  So, must now reinit the subscription stuff.
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "200 OK: Something Changed."));
                    HasFolderChanged = true;
                }
            }
            catch (Exception ex)
            {
#if(DEBUG)
                System.Diagnostics.Debugger.Break();
                System.Diagnostics.Debug.WriteLine(ex.Message);
#endif
                throw;
            }
        }

0
Comment
Question by:Vlearns
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 

Author Comment

by:Vlearns
ID: 34099210
code
public void PingServer()
        {
            byte[] bytes = null;
            HttpWebRequest request = null;
            Stream ReceiveStream = null;
            string url = emailServer +  "/Microsoft-Server-ActiveSync?Cmd=PING&User=srosario&DeviceID=123456789&DeviceType=PocketPc";
 
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/vnd.ms-sync.wbxml";
            request.Accept = "*/*";
            request.Headers.Add("MS-ASProtocolVersion", "2.5");
            request.Headers.Add("Accept-Language", "en-us");
            request.UserAgent = "MSFT-PPC/0.0.0";
            request.Credentials = userCred;
            request.KeepAlive = true;
         
            //string Body = "<Ping><LifeTime>900</LifeTime><Folders><Folder>Inbox</Folder></Folders></Ping>";
            //string Body = "<Ping><HeartbeatInterval>480</HeartbeatInterval></Ping>";
            //string Body = "<?xml version='1.0'?><Ping><HeartbeatInterval>480</HeartbeatInterval><LifeTime>900</LifeTime><Folders><Folder>Inbox</Folder></Folders></Ping>";
            string Body = "";// "<?xml version='1.0' encoding='utf-8'?><Ping xmlns='Ping'><HeartbeatInterval>1800</HeartbeatInterval></Ping>";
            //string Body = "<Ping xmlns='Ping'><HeartbeatInterval>1800</HeartbeatInterval></Ping>";
 
            bytes = Encoding.UTF8.GetBytes((string)Body);
            request.ContentLength = bytes.Length;
 
            Stream newStream = request.GetRequestStream();
            newStream.Write(bytes, 0, bytes.Length);
            newStream.Close();
 
            string StandardResponse = "{0} Poll ID# {1} Returned {2}";
 
            try
            {
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                string xml;
                HttpWebResponse result;
 
                using (result = (HttpWebResponse)request.GetResponse())
                {
                    ReceiveStream = result.GetResponseStream();
                    StreamReader sr = new StreamReader(ReceiveStream, encode);
                    xml = sr.ReadToEnd();
                    result.Close();
                }
 
                if (xml.IndexOf("204 No Content") > 0)
                {
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "\"No Content\": Nothing has changed"));
                    return;
                }
 
                if (xml.IndexOf("412 Precondition Failed") > 0)  // means the subscriptionID is not longer valid
                {
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "412 - Invalid Subscription ID"));
                    SubscriptionID = null;
                    // could do Subscribe and then call Poll again... but might end up in loop.
                    // probably should send event to the event log so user knows that their 
                    // poll interval is too short.  A Poll should reset the timeout.
                }
 
                if (xml.IndexOf("500 Internal Server Error") > 0)
                {
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "500 Internal Server Error"));
                    throw new ApplicationException("An internal server error occured, unable to complete request.");
                }
 
                if (result.StatusCode == HttpStatusCode.OK)
                {
                    // This means that something has changed.  So, must now reinit the subscription stuff.
                    Console.WriteLine(string.Format(StandardResponse, this.emailServer, this.SubscriptionID, "200 OK: Something Changed."));
                    HasFolderChanged = true;
                }
            }
            catch (Exception ex)
            {
#if(DEBUG)
                System.Diagnostics.Debugger.Break();
                System.Diagnostics.Debug.WriteLine(ex.Message);
#endif
                throw;
            }
        }

Open in new window

0
 
LVL 3

Accepted Solution

by:
prakash_parvath earned 2000 total points
ID: 34099995
Attached in PingServer.java

share your thoughts :)

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author PoornaPrakash_P
 */
public class PingServer {
public void PingServer()throws IOException
        {
            byte[] bytes = null;
            HttpURLConnection request = null;
            InputStream ReceiveStream = null;
            String emailServer = "emailServerLocation"; //Fill with emailServer path
            URL url = new URL(emailServer +  "/Microsoft-Server-ActiveSync?Cmd=PING&User=srosario&DeviceID=123456789&DeviceType=PocketPc");
            
            request = (HttpURLConnection)url.openConnection();
            
            request.setRequestMethod("POST");
            request.setRequestProperty("Content-Type","application/vnd.ms-sync.wbxml");
            
            request.setRequestProperty("Content-Language", "en-US");  
			
            request.setUseCaches (false);
            request.setDoInput(true);
            request.setDoOutput(true);
           
            request.addRequestProperty("MS-ASProtocolVersion", "2.5");
            request.addRequestProperty("Accept-Language", "en-us");
            request.setRequestProperty ( "User-agent","MSFT-PPC/0.0.0");
         
            String body = "";
            
 
            bytes = body.getBytes();
            request.setRequestProperty("Content-Length",""+bytes.length);
 
            //Send request
              OutputStream newStream = request.getOutputStream ();
              newStream.write (bytes);
              newStream.flush ();
              newStream.close ();
           
 
            String StandardResponse = "{0} Poll ID# {1} Returned {2}";
 
            try
            {
                
                String xml;
                String SubscriptionID =""; //Not sure what this is
                InputStream is = request.getInputStream();
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                byte[] buffer = new byte[4096];
                int ret=0;
                boolean hasFolderChanged = false;
               while ((ret = is.read(buffer)) > 0)
               {
                    buf.write(buffer, 0, ret);
                    
                }
                xml = buf.toString();
                if (xml.indexOf("204 No Content") > 0)
                {
                    System.out.println(emailServer+" Poll ID# "+ SubscriptionID+ "Returned "+ "\"No Content\": Nothing has changed");
                    return;
                }
 
                if (xml.indexOf("412 Precondition Failed") > 0)  // means the subscriptionID is not longer valid
                {
                    System.out.println(emailServer+" Poll ID# "+ SubscriptionID+ "Returned "+ "412 - Invalid Subscription ID");
                    SubscriptionID = null;
                    // could do Subscribe and then call Poll again... but might end up in loop.
                    // probably should send event to the event log so user knows that their 
                    // poll interval is too short.  A Poll should reset the timeout.
                }
 
                if (xml.indexOf("500 Internal Server Error") > 0)
                {
                    System.out.println(emailServer+" Poll ID# "+ SubscriptionID+ "Returned "+ "500 Internal Server Error");
                    throw new Exception("An internal server error occured, unable to complete request.");
                    // needs to define an ApplicationException
                }
 
                if (request.getResponseCode() == HttpURLConnection.HTTP_OK)
                {
                    // This means that something has changed.  So, must now reinit the subscription stuff.
                    System.out.println(emailServer+" Poll ID# "+ SubscriptionID+ "Returned "+ "200 OK: Something Changed.");
                    hasFolderChanged = true;
                }
            }
            catch (Exception ex)
            {
       // un-comment below 3 lines if you have a Log4j logger          
       //     if(logger.isDebug()){
       //         logger.debug(ex.getMessage());
       //     }
                
               
            }
        }

}

Open in new window

0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that undeā€¦
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month12 days, 23 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question