Solved

cover code to java

Posted on 2010-11-09
2
567 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
2 Comments
 

Author Comment

by:Vlearns
Comment Utility
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 500 total points
Comment Utility
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

728 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now