Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

cover code to java

Posted on 2010-11-09
2
Medium Priority
?
586 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
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month14 days, 23 hours left to enroll

578 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