Solved

VB Code from Java

Posted on 2013-06-11
9
332 Views
Last Modified: 2013-06-17
I'm working in a test Console project

I used a tool to convert some Java code to VB.

In the course of the conversion I got 3 puzzling lines.

    Private inputStream As InputStream
    Protected Friend outputStream As OutputStream
    Protected Friend reader As BufferedReader

Are these not needed and how would I hadle things that reference them?

Example...I saw a page with this for handling the Buffered Reader
Console.[In].ReadLine()
0
Comment
Question by:lrbrister
  • 4
  • 3
  • 2
9 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39238775
These are basically stream classes and a stream reader. Are there any references to the variables?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 39241193
can u post the code?
0
 

Author Comment

by:lrbrister
ID: 39241316
Her you go guys...
All the public declarations
Public Const urlBase As String = "/bobl/bobl"
Public Const ENCODING As String = "ISO-8859-1"
Public Shared ReadOnly DELIMITER As String = vbCrLf
Protected Friend url As URL
Private inputStream As InputStream
Protected Friend outputStream As OutputStream
Protected Friend socket As Socket
Protected Friend reader As BufferedReader
Private bProcessedHeaders As Boolean

Protected Friend resp As String = Nothing
Protected Friend errorMessage As String = Nothing

Open in new window



The part using the inputstream

        Protected Friend Overridable Sub initConnection(ByVal server As String)
            url = New URL(server & urlBase)
            Dim port As Integer = url.Port
            If server.StartsWith("https") Then
                If port = -1 Then
                    port = 443
                Else
                    If port = 80 OrElse port = -1 Then
                        port = 8080
                    End If
                End If
            End If

            If server.StartsWith("https") = False Then
                socket = New Socket(url.Host, port)
            Else
                Dim ignoreCerts As Boolean = True
                Dim socketFactory As SocketFactory

                If ignoreCerts Then
                    ' this is for ignoring the certificate 

                    ' Create a trust manager that does not validate certificate chains
				Dim trustAllCerts() As TrustManager = { New X509TrustManager() { public java.security.cert.X509Certificate() AcceptedIssuers { Return Nothing; } @Override public void checkClientTrusted(java.security.cert.X509Certificate() certs, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate() certs, String authType) { } } }

                    Dim sc As SSLContext = Nothing
                    Try
                        ' Install the all-trusting trust manager and create the socket
                        sc = SSLContext.getInstance("SSL")
                        sc.init(Nothing, trustAllCerts, New java.security.SecureRandom())
                    Catch e As NoSuchAlgorithmException
                    Catch e As KeyManagementException
                    End Try
                    socketFactory = sc.SocketFactory
                Else
                    socketFactory = SSLSocketFactory.Default
                End If
                socket = socketFactory.createSocket(url.Host, port)
            End If

            socket.SoTimeout = 0
            socket.KeepAlive = True
            socket.setSoLinger(False, 0)
            inputStream = socket.InputStream
            outputStream = socket.OutputStream
            reader = New BufferedReader(New InputStreamReader(inputStream))
        End Sub

Open in new window

0
 
LVL 42

Expert Comment

by:sedgwick
ID: 39241330
can u post the java code?
i can't see anything that uses the BufferedReader.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:lrbrister
ID: 39241402
Here is the Java code I did the convert from (Used a Java to VB tool from http://www.tangiblesoftwaresolutions.com/Product_Details/VB_to_Java_Converter_Details.html


package org.m5.sdk;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * This class is used to connect to M5 API servers and send
 * commands and receive responses as XML fragments using HTTP1.1
 * chunked encoding.
 */
public class M5Connection
{
	public static final String urlBase = "/bobl/bobl";
	public static final String ENCODING = "ISO-8859-1";
	public static final String DELIMITER = "\r\n";
	protected URL url;
	private InputStream inputStream;
	protected OutputStream outputStream;
	protected Socket socket;
	protected BufferedReader reader;
	private boolean bProcessedHeaders;

	protected String resp = null;
	protected String errorMessage = null;
	
	/**
	 * Run a command by sending it in the form of an XML fragment and waiting for the response.
	 * @param server the URL to send the command to. 
	 * @param xml a string containing an XML document fragment
	 * @param commandId the is that is contained in the command XML
	 * @param timeoutSeconds how long to wait for a response
	 * @return an error message on failure, else null
	 */
	public String runCommand(final String server, final String xml, final long commandId, final int timeoutSeconds)
	{
		try
		{
			Thread thread = new Thread()
			{			
				@Override
				public void run()
				{
					for (int ii = 0; resp == null && ii < timeoutSeconds; ii++)
					{
						try { Thread.sleep(1000); } catch (Exception e) {}
					}
					if (resp != null && resp.contains("<ErrorCount>0</ErrorCount>"))
					{
						//System.out.println("OK");						
						return;
					}

					if (resp == null)
					{
						errorMessage = "Timeout, command id=" + commandId;
					}
					else
					{
						errorMessage = "Error: " + resp;
					}
				}
			};
			thread.start();
			
			// new connection to the server
			initHttpsConnection(server);
			send(xml);

			resp = getRawResponse();
			thread.join();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			errorMessage = "running command with id " + commandId + " " + e.getMessage();
		}
		return errorMessage;
	}
	
	
	/**
	 * Start a new connection to the server.
	 * @param server server name:port to connect to
	 * @throws IOException
	 */
	protected void initConnection(String server) throws IOException
	{
		url = new URL(server + urlBase);
		int port = url.getPort();
		if (server.startsWith("https"))
		{
			if (port == -1) port = 443;
			else
				if (port == 80 || port == -1)port = 8080;
		}

		if (server.startsWith("https") == false)
		{
			socket = new Socket(url.getHost(), port);
		}
		else
		{
			boolean ignoreCerts = true;
			SocketFactory socketFactory;

			if (ignoreCerts)
			{
				/* this is for ignoring the certificate */

				// Create a trust manager that does not validate certificate chains
				TrustManager[] trustAllCerts = new TrustManager[]{
						new X509TrustManager() {
							@Override
							public java.security.cert.X509Certificate[] getAcceptedIssuers() {
								return null;
							}
							@Override
							public void checkClientTrusted(
									java.security.cert.X509Certificate[] certs, String authType) {
							}
							@Override
							public void checkServerTrusted(
									java.security.cert.X509Certificate[] certs, String authType) {
							}
						}
				};

				SSLContext sc = null;
				try
				{
					// Install the all-trusting trust manager and create the socket
					sc = SSLContext.getInstance("SSL");
					sc.init(null, trustAllCerts, new java.security.SecureRandom());
				} catch (NoSuchAlgorithmException e){
				}catch (KeyManagementException e) {}
				socketFactory = sc.getSocketFactory();
			}
			else
			{
				socketFactory = SSLSocketFactory.getDefault();
			}
			socket = socketFactory.createSocket(url.getHost(), port);
		}

		socket.setSoTimeout(0);
		socket.setKeepAlive(true);
		socket.setSoLinger(false, 0);
		inputStream = socket.getInputStream();
		outputStream = socket.getOutputStream();
		reader = new BufferedReader(new InputStreamReader(inputStream));
	}
	
	public void initHttpsConnection(String server) throws IOException
	{
		initConnection(server);
		sendHeaders();
		bProcessedHeaders = false;
	}

	private void sendHeaders() throws IOException {
		String path = url.getPath();
		StringBuffer outputBuffer = new StringBuffer();
		outputBuffer.append("POST " + path + " HTTP/1.1" + DELIMITER);
		outputBuffer.append("Host: " + url.getHost() + DELIMITER);
		outputBuffer.append("User-Agent: CometTest" + DELIMITER);
		outputBuffer.append("Connection: keep-alive" + DELIMITER);
		outputBuffer.append("Content-Type: text/plain" + DELIMITER);
		outputBuffer.append("Transfer-Encoding: chunked" + DELIMITER);
		outputBuffer.append(DELIMITER);
		byte[] outputBytes = outputBuffer.toString().getBytes(ENCODING);
		outputStream.write(outputBytes);
		outputStream.flush();
	}

	/** Send some data to the server, HTTP/1.1 chunked style. */
	public void send(String chunkData) throws IOException {
		byte[] chunkBytes = chunkData.getBytes(ENCODING);
		String hexChunkLength = Integer.toHexString(chunkBytes.length);
		StringBuffer outputBuffer = new StringBuffer();
		outputBuffer.append(hexChunkLength);
		outputBuffer.append(DELIMITER);
		outputBuffer.append(chunkData);
		outputBuffer.append(DELIMITER);
		byte[] outputBytes = outputBuffer.toString().getBytes(ENCODING);
		outputStream.write(outputBytes);
		outputStream.flush();
	}
	
	/**
	 * Wait for a response from the server.
	 * @return the string that the server returned.
	 * @throws IOException
	 */
	public String getRawResponse() throws IOException
	{
		String s;
		
		// just after we connect we expect to see the HTTP headers. Read and discard
		if (!bProcessedHeaders) {
			while (true){
				String line = reader.readLine();
				//System.out.println("HEADER: " + line);
				if (line == null || line.equals("\r\n") || line.equals(""))
					break;
			}
			bProcessedHeaders = true;
		}

		while (true)
		{		
			s = getChunk();		

			if (s == null)
				return null;
			
			if (s.equals("")) {
				continue;
			}

			// server will not emit XML if it is having real troubles
			if (s.charAt(0) != '<' || s.startsWith("<html>")) {
				System.out.println("Server says: " + s);
				continue;
			}
			return s;
		}
	}	

	/**
	 * Expect chunked excoding back from the server. Read and return a chunk.
	 * @return a string containing the HTTP chunk
	 * @throws IOException
	 */
	private String getChunk() throws IOException
	{
		StringBuffer buf = new StringBuffer();
		while (true)
		{
		// HTTP chunked mode, expect to see a line with the length in hex of the chunk that follows
			String s = reader.readLine();			
			
			if (s == null)
				throw new IOException();
			if (s.length() == 0)
				continue;

			int toread;
			try {
				toread = Integer.parseInt(s, 16);
			} catch (NumberFormatException e) {
				System.out.println("Number format error: " + s);
				return "";
			}
		
			if (toread == 0)
			{
				return null;
			}
			
			// read the chunk
			char[] data = new char[toread];
			int read = 0;
			while (read != toread)
			{
				read += reader.read(data, read, toread - read);
			}
			buf.append(data, 0, read);

			// for some reason tomcat only sends data in up to 8192 byte chunks
			if (toread != 8192)
				break;
		}
		return buf.toString();
	}	
	
	public void close()
	{
		try { socket.close(); } catch (IOException e) {}
	}
}

Open in new window

0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 250 total points
ID: 39242395
0
 
LVL 42

Assisted Solution

by:sedgwick
sedgwick earned 250 total points
ID: 39243614
the socket doesn't have InputStream/OutputStream properties.
you wanna use NetworkStream which uses socket as underlying connection:

            string url = "127.0.0.1";
            int port = 80;

            Socket listenSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            listenSock.Connect(new IPEndPoint(IPAddress.Parse(url), port));
            NetworkStream ns = new NetworkStream(listenSock);
            if (ns.CanRead && ns.DataAvailable)
            {
                //startreading
            }

Open in new window


since reading and writing are in separate functions, you can set NetworkStream ns as class member, initialize it when u first create the socket and use it to read.
the outputstream can be used as List<byte> replaces outputStream.Write.
0
 

Author Comment

by:lrbrister
ID: 39244197
Taking a look today guys
0
 

Author Closing Comment

by:lrbrister
ID: 39253848
Thanks folks
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

708 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

12 Experts available now in Live!

Get 1:1 Help Now