Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Large String Constants in Java

Tags:

java

string

What is the best way to handle large string constants in Java?

Imagine that I have a test fixture for SOAP and I want to send the following string:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
       <QuoteRequest xmlns="https://www.bcponline.co.uk">
            <header>
                <SourceCode>BN325</SourceCode>
                <MessageSource>B2B3</MessageSource>
                <Profile>B08A</Profile>
                <Password>AP3U86V</Password>
                <OperatorID>flightline</OperatorID>
                <ShowWebOptions>0</ShowWebOptions>
            </header>
            <serviceSelection>
                <ServiceProviderCode></ServiceProviderCode>
                <ProductCode>CarParking</ProductCode>
                <IATACode>lgw</IATACode>
            </serviceSelection>
            <quoteDetails>
                <DepartureDate>21-Jun-2005</DepartureDate>
                <DepartureTime>07:00</DepartureTime>
                <ReturnDate>28-Jun-2005</ReturnDate>
                <ReturnTime>07:00</ReturnTime>
                <QuoteReference></QuoteReference>
                <NoPax>1</NoPax>
            </quoteDetails>
            <sPostCode></sPostCode>
        </QuoteRequest>
    </soap:Body>
</soap:Envelope>

I'd rather not put quotes and pluses around every line. If I put it in a file it's extra code and it would be somewhat hard to put several strings in the same file. XML has problems escaping text (I have to use CDATA ugliness). Is there an easier way?

like image 491
User1 Avatar asked Nov 06 '22 03:11

User1


1 Answers

If the strings are unrelated, you could put them in separate files even if it's a lot of files (what is the problem with that?).

If you insist on one file, you could come up with a unique delimiter, but you would be paying a price when attempting to randomly access a specific entry.

Data files should almost always be externalized (likely in a separate directory) and read when needed, rather than hardcoded into the code. It's cleaner, reduces code size, reduces need for compilation, and allows you to use the same data file for multiple test. Most test fixtures as well as build and integration tools support external files.

Or, you could write code or a builder that builds SOAP from arguments, making this all a lot more concise (if you're willing to pay the runtime cost). (Correction: I see you changed your sample, this would be nasty to auto-generate).

like image 116
Uri Avatar answered Nov 14 '22 00:11

Uri