Solved

cover code to java

Posted on 2010-11-09
2
574 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 500 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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

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

This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

695 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