Avatar of jhughes4
jhughes4

asked on 

Adding StringBuffer to an Array

In the following, I'm trying to add a StringBuffer to an Array.  It compiles fine, but at runtime it doesn't make it past where the buffer is being added.  Thanks in advance.

       


String[] strA = new String[1];
strA[1] = strBuf.toString();
	                			    out.println("doesn't make it here");
 
						       		HttpAccept sendMsg = new HttpAccept();
					       			sendMsg.doit(strA);
	           					    sendMsg.testEnvelope(strA);
	           					    out.println("MADE IT HERE")

Open in new window

Java EEJava

Avatar of undefined
Last Comment
CEHJ
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You should check for exceptions that stop it reaching that line in your logs
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

e.g. a null StringBuffer will throw an NPE, preventing running to that line
Avatar of TrekkyLeaper
TrekkyLeaper
Flag of United States of America image

You are also creating a String array of size 1 and trying to access index 1 when only index 0 is valid.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Yes - i missed that ;-)
Avatar of jhughes4
jhughes4

ASKER

OK, so even if I do the following it throws the exception.  


                                              String[] strA = new String[0];

                                              strA[0] = strBuf.toString();

The code below is where I'm adding to the buffer.  Sorry for the noob question, Java 1.0 '97 was the last time I even looked at Java.  thanks again
   Enumeration e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String values[] = request.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
         //out.println("NAME---" + name + "----NAME:" + " (" + i + "): " + values[i] + "THIS ONE");
         strBuf.append(name + values[i]);
 
        }
      }
}

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

>                                               String[] strA = new String[0];

that creates an array with 0 elements, should be (at least) 1

>                                               strA[0] = strBuf.toString();

first index is at 0.

Avatar of jhughes4
jhughes4

ASKER

I'm getting an arrayindexoutofbounds error .  Could the problem be related to the message I'm receiving?  The entire message is the StringBuffer that I'm trying to cram into the array so that I can wrap a SOAP envelope around it.


MESSAGE RECEIVED=========  <?xml version"1.0" ?> - HRXMLEMPLID25097t
o be selected by client3/21/2008 13:12:11 PM1SETFIR
STDATA_CANDIDATE<![CDATA[ <?xml version="1.0" e
ncoding="UTF-8"?>1011REQ001JOB001STAT00101-Jun-2008Yes4Promotion030758NWarrenFirst Namecandidate Las
t NameMichael NameMiddle ameMiddle InitialName Suffixsuffix OFFR<
/SuffixOFFR>11-Oct-1965MaleFMasters365-65-8432987654321234435678USAUSA123 6th StOm
ahaNE
68135DouglasUSAwtmichael@yahoo.com402-222-5453WhiteCorporate005019050034
1110B13000027SVP FDC Properties030498Richard Pohl
402-222-5454RegularYesFull-Time40Salary05USD<
/Currency>175,350.00Bi-Week
ly%.50<
Commission3>]]>

the exception:  java.lang.ArrayIndexOutOfBoundsException:  . .


Avatar of Mick Barry
Mick Barry
Flag of Australia image

what code are you currently using?

Avatar of jhughes4
jhughes4

ASKER

The following
----CODE ACCEPTING THE POST------------
 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.utils.Options;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Vector;
import java.util.Enumeration;
 
 
 
public class HttpAccept extends HttpServlet {
 
public String doit(String[] args) throws Exception {
 
        Options opts = new Options(args);
        opts.setDefaultURL("http://e2gx1139.fdc.1dc.com:7777/orabpel/tams/COMP_CandidateToHR");
 
        Service  service = new Service();
        Call     call    = (Call) service.createCall();
 
        call.setTargetEndpointAddress( new URL(opts.getURL()) );
        SOAPBodyElement[] input = new SOAPBodyElement[3];
 
        input[0] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
                                                                "e1", "Hello"));
        input[1] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
                                                                "e1", "World"));
 
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc            = builder.newDocument();
        Element cdataElem       = doc.createElementNS("urn:foo", "e3");
        CDATASection cdata      = doc.createCDATASection("Text with\n\tImportant  <b>  whitespace </b> and tags! ");
        cdataElem.appendChild(cdata);
 
        input[2] = new SOAPBodyElement(cdataElem);
 
        Vector          elems = (Vector) call.invoke( input );
        SOAPBodyElement elem  = null ;
        Element         e     = null ;
 
        elem = (SOAPBodyElement) elems.get(0);
        e    = elem.getAsDOM();
 
        String str = "Res elem[0]=" + XMLUtils.ElementToString(e);
 
        elem = (SOAPBodyElement) elems.get(1);
        e    = elem.getAsDOM();
        str = str + "Res elem[1]=" + XMLUtils.ElementToString(e);
 
        elem = (SOAPBodyElement) elems.get(2);
        e    = elem.getAsDOM();
        str = str + "Res elem[2]=" + XMLUtils.ElementToString(e);
 
        return( str );
 
 
 
    }
public void testEnvelope(String[] args) throws Exception {
 
            String xmlString = args.toString();
 
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage smsg =
                mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
        SOAPPart sp = smsg.getSOAPPart();
        SOAPEnvelope se = (SOAPEnvelope)sp.getEnvelope();
 
        SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
        //SOAPMessage response = conn.call(smsg, "http://localhost:8080/axis/services/MessageService2");
        SOAPMessage response = conn.call(smsg, "http://localhost:8080");
    }
 
 
 
 
 
 
 
 
 
       public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
            throws IOException, ServletException {
				try {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        StringBuffer strBuf = new StringBuffer();
 
 
 
            //  out.println("Header information;  " + request.getHeaderNames());
 
 
 
 
 
 
 
 
    Enumeration e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String values[] = request.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
         //out.println("NAME---" + name + "----NAME:" + " (" + i + "): " + values[i] + "THIS ONE");
         strBuf.append(name + values[i]);
 
 
        }
      }
}
									out.println("MESSAGE RECEIVED=========  " + strBuf.toString());
 
									out.println("STEP 1");
 
 
 
 
			String[] strA = new String[0];
			strA[0] = strBuf.toString();
			//----------------DOESN'T MAKE IT HERE-----------------------//
 
						       		HttpAccept sendMsg = new HttpAccept();
					       			sendMsg.doit(strA);
	           					    sendMsg.testEnvelope(strA);
 
}
 
catch (Exception e) {
	        PrintWriter out = response.getWriter();
 
	out.println("the exception:  " + e.toString());
}
 
 
    }
}
 
 
-----CODE DOING THE POST--------------
import java.net.*;
import java.io.*;
 
class HttpPost
{
public static void main(String args[])
 
{
 
 
try
{
// Construct Date
String data = URLEncoder.encode("method", "UTF-8") + "=" + URLEncoder.encode("Relay_On", "UTF-8");
 
 
String msg = "<?xml version=\"1.0\" ?> - <Envelope version=\"01.00\"><Sender><Id>HRXMLEMPLID</Id><Credential>25097</Credential></Sender><Recipient><Id>to be selected by client</Id></Recipient><TransactInfo transactType=\"data\"><TransactId /><TimeStamp>3/21/2008 13:12:11 PM</TimeStamp></TransactInfo><Packet><PacketInfo packetType=\"data\"><PacketId>1</PacketId><Action>SET</Action><Manifest>candidate</Manifest></PacketInfo><Payload><![CDATA[ <?xml version=\"1.0\" encoding=\"UTF-8\"?><CANDIDATE><CANDIDATEID>10</CANDIDATEID><REQUISITIONNUMBER>11</REQUISITIONNUMBER><BRREQNUMBER>REQ001</BRREQNUMBER><JOBCODE>JOB001</JOBCODE><STATUS>STAT001</STATUS><StartDate17>01-Jun-2008</StartDate17><PriorFDEmployee>Yes</PriorFDEmployee><HireType>4</HireType><TransferType>Promotion</TransferType><EmplID>030758</EmplID><IfRehire_Prev>N</IfRehire_Prev><CandidateFirstN0>Warren</CandidateFirstN0><FirstName0>First Name</FirstName0><CandidateLastNa1>candidate Last Name</CandidateLastNa1><LastName1>Michael Name</LastName1><CandidateMiddleName>Middle ame</CandidateMiddleName><MiddleInitial24>Middle Initial</MiddleInitial24><CandidateNameSuffix>Name Suffix</CandidateNameSuffix><SuffixOFFR>suffix OFFR</SuffixOFFR><DOB>11-Oct-1965</DOB><DateOfBirth3></DateOfBirth3><Gender>Male</Gender><Sex37>F</Sex37><HighestEdLevel>Masters</HighestEdLevel><SSN>365-65-8432</SSN><CandidateSSNNat2>987654321</CandidateSSNNat2><SocialSecurityN9>234435678</SocialSecurityN9><CntryCandNatID>USA</CntryCandNatID><CntryNatID>USA</CntryNatID><Address1BGR></Address1BGR>123 6th St<Addressline14></Addressline14><StreetAddress6></StreetAddress6><Address2BGR></Address2BGR><Address2></Address2><AptSuiteLot25></AptSuiteLot25><Address3BGR></Address3BGR><Address3PCI></Address3PCI><Address4BGR></Address4BGR><Address4PCI></Address4PCI><CountyBGR></CountyBGR><CityBGR>Omaha</CityBGR><City5></City5><City7></City7><StateRegProvBGR>NE</StateRegProvBGR><StateRegionProv6></StateRegionProv6><StateProvince8></StateProvince8><ZipcodeBGR>68135</ZipcodeBGR><ZipPostCode7></ZipPostCode7><ZipCode10></ZipCode10><CountryBGR>Douglas</CountryBGR><Country39>USA</Country39><Country9></Country9><emailAddress12>wtmichael@yahoo.com</emailAddress12><HomePhoneNumber11>402-222-5453</HomePhoneNumber11><CandidateMobilePhone></CandidateMobilePhone><CellPhone23></CellPhone23><OtherPhoneBGR></OtherPhoneBGR><OtherPhone20></OtherPhone20><hispanic_latino></hispanic_latino><Race>White</Race><Bus_segment>Corporate</Bus_segment><Business_Unit>005</Business_Unit><Department>019050034</Department><EEOWorkLocation>1110</EEOWorkLocation><Paygroup>B13</Paygroup><Job_Code>000027</Job_Code><Title_Advertise>SVP FDC Properties</Title_Advertise><HiringManagerEmplID>030498</HiringManagerEmplID><SupervisorName>Richard Pohl</SupervisorName><HiringManagerPhone>402-222-5454</HiringManagerPhone><Empl_status>Regular</Empl_status><Benefits_Elig>Yes</Benefits_Elig><full_time_status>Full-Time</full_time_status><MultLangDiffAmt1></MultLangDiffAmt1><MultLangDiffPerc></MultLangDiffPerc><StdHrsPerWk>40</StdHrsPerWk><pay_status>Salary</pay_status><pay_grade>05</pay_grade><Currency>USD</Currency><StartingSalaryW19>175,350.00</StartingSalaryW19><PayFrequency>Bi-Weekly</PayFrequency><AnnTargetBonusPerc>%25.50</AnnTargetBonusPerc><SignOnBonus27></SignOnBonus27><SignOnBonusTerms></SignOnBonusTerms><CarAllowance28></CarAllowance28><NonRecoverableD29></NonRecoverableD29><NonRecoverableNoMos></NonRecoverableNoMos><ReloAssistAmount></ReloAssistAmount><AdditionalCompe2></AdditionalCompe2><Commission3></Commission3><ShiftDifferenti4></ShiftDifferenti4><ShiftDiffPerc></ShiftDiffPerc><RequisitionID27></RequisitionID27><RecruiterEmplID></RecruiterEmplID><RecruiterPhone></RecruiterPhone><RecruiterEmail></RecruiterEmail></CANDIDATE>]]> </Payload></Packet></Envelope>";
String xmlHeader = "<?xml version=\"1.0\"> ";
//System.out.println("XML HEADER: " + xmlHeader);
 
data = msg;
int dataLength = data.length();
URL url = new URL("http://host-2:8889/j2ee/servlet/HttpAccept");
 
 
 
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
 
System.out.println("Writing the message:");
// Send Data
 
wr.write(msg);
 
wr.flush();
 
// Get the reponse
BufferedReader rd =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
}
catch (MalformedURLException e)
{ System.err.println(e.toString()); }
catch (IOException e)
{ System.err.println(e.toString()); }
}
}

Open in new window

Avatar of Mick Barry
Mick Barry
Flag of Australia image

>                         String[] strA = new String[0];

as I mentioned above that should be:

                        String[] strA = new String[1];


>             String xmlString = args.toString();

and that should be:

xmlString = args[0];

though from what you've posted args could just be a string (instead of an array)

Avatar of jhughes4
jhughes4

ASKER

OK, sorry that I'm being dense.  I did change to 1 and the xmlString, but I'm still getting the indexoutofbounds error when it tries to add the buffer to one.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.utils.Options;
import org.apache.axis.utils.XMLUtils;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Vector;
import java.util.Enumeration;
 
 
 
public class HttpAccept extends HttpServlet {
 
public String doit(String[] args) throws Exception {
 
        Options opts = new Options(args);
        opts.setDefaultURL("http://e2gx1139.fdc.1dc.com:7777/orabpel/tams/COMP_CandidateToHR");
 
        Service  service = new Service();
        Call     call    = (Call) service.createCall();
 
        call.setTargetEndpointAddress( new URL(opts.getURL()) );
        SOAPBodyElement[] input = new SOAPBodyElement[3];
 
        input[0] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
                                                                "e1", "Hello"));
        input[1] = new SOAPBodyElement(XMLUtils.StringToElement("urn:foo",
                                                                "e1", "World"));
 
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc            = builder.newDocument();
        Element cdataElem       = doc.createElementNS("urn:foo", "e3");
        CDATASection cdata      = doc.createCDATASection("Text with\n\tImportant  <b>  whitespace </b> and tags! ");
        cdataElem.appendChild(cdata);
 
        input[2] = new SOAPBodyElement(cdataElem);
 
        Vector          elems = (Vector) call.invoke( input );
        SOAPBodyElement elem  = null ;
        Element         e     = null ;
 
        elem = (SOAPBodyElement) elems.get(0);
        e    = elem.getAsDOM();
 
        String str = "Res elem[0]=" + XMLUtils.ElementToString(e);
 
        elem = (SOAPBodyElement) elems.get(1);
        e    = elem.getAsDOM();
        str = str + "Res elem[1]=" + XMLUtils.ElementToString(e);
 
        elem = (SOAPBodyElement) elems.get(2);
        e    = elem.getAsDOM();
        str = str + "Res elem[2]=" + XMLUtils.ElementToString(e);
 
        return( str );
 
 
 
    }
public void testEnvelope(String[] args) throws Exception {
 
            //String xmlString = args.toString();
            String xmlString = args[0];
 
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage smsg =
                mf.createMessage(new MimeHeaders(), new ByteArrayInputStream(xmlString.getBytes()));
        SOAPPart sp = smsg.getSOAPPart();
        SOAPEnvelope se = (SOAPEnvelope)sp.getEnvelope();
 
        SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
        //SOAPMessage response = conn.call(smsg, "http://localhost:8080/axis/services/MessageService2");
        SOAPMessage response = conn.call(smsg, "http://localhost:8080");
    }
 
 
 
 
 
 
 
 
 
       public void doPost(HttpServletRequest request,
                      HttpServletResponse response)
            throws IOException, ServletException {
				try {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        StringBuffer strBuf = new StringBuffer();
 
 
 
            //  out.println("Header information;  " + request.getHeaderNames());
 
 
 
 
 
 
 
 
    Enumeration e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String values[] = request.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
         //out.println("NAME---" + name + "----NAME:" + " (" + i + "): " + values[i] + "THIS ONE");
         strBuf.append(name + values[i]);
 
 
        }
      }
}
									out.println("MESSAGE RECEIVED=========  " + strBuf.toString());
 
									out.println("STEP 1");
 
 
 
 
			String[] strA = new String[1];
			out.println("STEP2");
						//----------------DOESN'T MAKE IT HERE-----------------------//
 
			strA[1] = strBuf.toString();
						out.println("STEP3");
 
 
						       		HttpAccept sendMsg = new HttpAccept();
					       			sendMsg.doit(strA);
	           					    sendMsg.testEnvelope(strA);
 
}
 
catch (Exception e) {
	        PrintWriter out = response.getWriter();
 
	out.println("the exception:  " + e.toString());
}
 
 
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of jhughes4
jhughes4

ASKER

That resolved the issue thanks.  I'm not getting a different error regarding the webserver saying that the Options class is missing.  NoClassDefFoundError: Missing class: org.apache.axis.utils.Options.  Thanks again!
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

jhughes4, where's the credit for TrekkyLeaper (who answered the question)?
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo