1 13 14 package se.anatom.ejbca.protocol; 15 16 import java.io.ByteArrayOutputStream ; 17 import java.io.IOException ; 18 import java.io.InputStream ; 19 import java.io.OutputStream ; 20 import java.net.HttpURLConnection ; 21 import java.net.URL ; 22 import java.net.URLEncoder ; 23 import java.rmi.RemoteException ; 24 import java.security.InvalidAlgorithmParameterException ; 25 import java.security.InvalidKeyException ; 26 import java.security.KeyPair ; 27 import java.security.NoSuchAlgorithmException ; 28 import java.security.NoSuchProviderException ; 29 import java.security.PrivateKey ; 30 import java.security.PublicKey ; 31 import java.security.Signature ; 32 import java.security.SignatureException ; 33 import java.security.cert.CRLException ; 34 import java.security.cert.CertStore ; 35 import java.security.cert.CertStoreException ; 36 import java.security.cert.CertificateEncodingException ; 37 import java.security.cert.CertificateException ; 38 import java.security.cert.X509CRL ; 39 import java.security.cert.X509Certificate ; 40 import java.util.Collection ; 41 import java.util.Iterator ; 42 43 import javax.ejb.DuplicateKeyException ; 44 import javax.ejb.FinderException ; 45 import javax.naming.Context ; 46 import javax.naming.NamingException ; 47 48 import junit.framework.TestCase; 49 import junit.framework.TestSuite; 50 51 import org.apache.commons.lang.StringUtils; 52 import org.apache.log4j.Logger; 53 import org.bouncycastle.asn1.ASN1OctetString; 54 import org.bouncycastle.asn1.ASN1Set; 55 import org.bouncycastle.asn1.DERObjectIdentifier; 56 import org.bouncycastle.asn1.DERPrintableString; 57 import org.bouncycastle.asn1.DERString; 58 import org.bouncycastle.asn1.cms.Attribute; 59 import org.bouncycastle.asn1.cms.AttributeTable; 60 import org.bouncycastle.cms.CMSEnvelopedData; 61 import org.bouncycastle.cms.CMSException; 62 import org.bouncycastle.cms.CMSProcessable; 63 import org.bouncycastle.cms.CMSSignedData; 64 import org.bouncycastle.cms.CMSSignedGenerator; 65 import org.bouncycastle.cms.RecipientInformation; 66 import org.bouncycastle.cms.RecipientInformationStore; 67 import org.bouncycastle.cms.SignerId; 68 import org.bouncycastle.cms.SignerInformation; 69 import org.bouncycastle.cms.SignerInformationStore; 70 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome; 71 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote; 72 import org.ejbca.core.ejb.ra.IUserAdminSessionHome; 73 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote; 74 import org.ejbca.core.model.SecConst; 75 import org.ejbca.core.model.approval.ApprovalException; 76 import org.ejbca.core.model.approval.WaitingForApprovalException; 77 import org.ejbca.core.model.authorization.AuthorizationDeniedException; 78 import org.ejbca.core.model.ca.caadmin.CAInfo; 79 import org.ejbca.core.model.ca.catoken.CATokenConstants; 80 import org.ejbca.core.model.log.Admin; 81 import org.ejbca.core.model.ra.UserDataConstants; 82 import org.ejbca.core.model.ra.raadmin.UserDoesntFullfillEndEntityProfile; 83 import org.ejbca.core.protocol.ResponseStatus; 84 import org.ejbca.core.protocol.ScepRequestMessage; 85 import org.ejbca.util.Base64; 86 import org.ejbca.util.CertTools; 87 import org.ejbca.util.KeyTools; 88 89 import com.meterware.httpunit.GetMethodWebRequest; 90 import com.meterware.httpunit.HttpUnitOptions; 91 import com.meterware.httpunit.WebConversation; 92 import com.meterware.httpunit.WebRequest; 93 import com.meterware.httpunit.WebResponse; 94 95 97 public class ProtocolScepHttpTest extends TestCase { 98 private static Logger log = Logger.getLogger(ProtocolScepHttpTest.class); 99 100 private static final String httpReqPath = "http://127.0.0.1:8080/ejbca"; 101 private static final String resourceScep = "publicweb/apply/scep/pkiclient.exe"; 102 private static final String resourceScepNoCA = "publicweb/apply/scep/noca/pkiclient.exe"; 103 104 static byte[] openscep = Base64.decode(("MIIGqwYJKoZIhvcNAQcCoIIGnDCCBpgCAQExDjAMBggqhkiG9w0CBQUAMIICuwYJ" + 105 "KoZIhvcNAQcBoIICrASCAqgwggKkBgkqhkiG9w0BBwOgggKVMIICkQIBADGB1TCB" + 106 "0gIBADA7MC8xDzANBgNVBAMTBlRlc3RDQTEPMA0GA1UEChMGQW5hVG9tMQswCQYD" + 107 "VQQGEwJTRQII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QfdtK4B4lzCTuNxWRT853dW" + 138 "dRDzXBCGEArlG8ef+vDD/HP9SX3MQ0NJWym48VI9bTpP/mJlUKSsfgDYHohvUlVI" + 139 "E5QFC6ILVLUmuWPGchUEAb8t30DDnmeXs8QxdqHfbQ==").getBytes()); 140 141 private static Context ctx; 142 private static IUserAdminSessionRemote usersession; 143 private static int caid = 0; 144 private static Admin admin; 145 private static X509Certificate cacert = null; 146 private static KeyPair keys = null; 147 private static String caname = null; 148 private String transId = null; 149 private String senderNonce = null; 150 151 public static void main(String args[]) { 152 junit.textui.TestRunner.run(suite()); 153 } 154 155 156 public static TestSuite suite() { 157 return new TestSuite(ProtocolScepHttpTest.class); 158 } 159 160 161 public ProtocolScepHttpTest(String name) throws Exception { 162 super(name); 163 CertTools.installBCProvider(); 165 166 HttpUnitOptions.setExceptionsThrownOnErrorStatus(false); 168 169 admin = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER); 170 171 ctx = getInitialContext(); 172 Object obj = ctx.lookup("CAAdminSession"); 173 ICAAdminSessionHome cahome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, ICAAdminSessionHome.class); 174 ICAAdminSessionRemote casession = cahome.create(); 175 Collection caids = casession.getAvailableCAs(admin); 176 Iterator iter = caids.iterator(); 177 if (iter.hasNext()) { 178 caid = ((Integer ) iter.next()).intValue(); 179 } else { 180 assertTrue("No active CA! Must have at least one active CA to run tests!", false); 181 } 182 CAInfo cainfo = casession.getCAInfo(admin, caid); 183 caname = cainfo.getName(); 184 Collection certs = cainfo.getCertificateChain(); 185 if (certs.size() > 0) { 186 Iterator certiter = certs.iterator(); 187 X509Certificate cert = (X509Certificate ) certiter.next(); 188 String subject = CertTools.getSubjectDN(cert); 189 if (StringUtils.equals(subject, cainfo.getSubjectDN())) { 190 cacert = CertTools.getCertfromByteArray(cert.getEncoded()); 192 } 193 } else { 194 log.error("NO CACERT for caid " + caid); 195 } 196 obj = ctx.lookup("UserAdminSession"); 197 IUserAdminSessionHome userhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(obj, IUserAdminSessionHome.class); 198 usersession = userhome.create(); 199 200 if (keys == null) { 201 keys = KeyTools.genKeys("512", CATokenConstants.KEYALGORITHM_RSA); 203 } 204 } 205 206 protected void setUp() throws Exception { 207 } 208 209 protected void tearDown() throws Exception { 210 } 211 212 private Context getInitialContext() throws NamingException { 213 Context ctx = new javax.naming.InitialContext (); 214 return ctx; 215 } 216 217 public void test01Access() throws Exception { 218 WebConversation wc = new WebConversation(); 219 WebRequest request = new GetMethodWebRequest(httpReqPath + '/' + resourceScep); 221 WebResponse response = wc.getResponse(request); 222 assertEquals("Response code", 400, response.getResponseCode()); 223 } 224 225 228 public void test02OpenScep() throws Exception { 229 log.debug(">test02OpenScep()"); 230 WebConversation wc = new WebConversation(); 232 WebRequest request = new GetMethodWebRequest(httpReqPath + '/' + resourceScep); 233 request.setParameter("operation", "PKIOperation"); 234 request.setParameter("message", new String (Base64.encode(openscep))); 235 WebResponse response = wc.getResponse(request); 236 assertEquals("Response code", 404, response.getResponseCode()); 240 log.debug("<test02OpenScep()"); 241 } 242 243 public void test03ScepRequestOKSHA1() throws Exception { 244 log.debug(">test03ScepRequestOKSHA1()"); 245 248 createScepUser(); 250 251 byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_SHA1); 252 byte[] retMsg = sendScep(false, msgBytes, false); 254 assertNotNull(retMsg); 255 checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_SHA1, false); 256 log.debug("<test03ScepRequestOKSHA1()"); 257 } 258 259 public void test04ScepRequestOKMD5() throws Exception { 260 log.debug(">test04ScepRequestOKMD5()"); 261 264 createScepUser(); 266 267 byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_MD5); 268 byte[] retMsg = sendScep(false, msgBytes, false); 270 assertNotNull(retMsg); 271 checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_MD5, false); 272 log.debug("<test04ScepRequestOKMD5()"); 273 } 274 275 public void test05ScepRequestPostOK() throws Exception { 276 log.debug(">test05ScepRequestPostOK()"); 277 280 createScepUser(); 281 282 byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_SHA1); 283 byte[] retMsg = sendScep(true, msgBytes, false); 285 assertNotNull(retMsg); 286 checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_SHA1, false); 287 log.debug(">test05ScepRequestPostOK()"); 288 } 289 290 public void test06ScepRequestPostOKNoCA() throws Exception { 291 log.debug(">test06ScepRequestPostOKNoCA()"); 292 295 createScepUser(); 296 297 byte[] msgBytes = genScepRequest(false, CMSSignedGenerator.DIGEST_SHA1); 298 byte[] retMsg = sendScep(true, msgBytes, true); 300 assertNotNull(retMsg); 301 checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, false, CMSSignedGenerator.DIGEST_SHA1, true); 302 log.debug(">test06ScepRequestPostOKNoCA()"); 303 } 304 305 public void test07ScepGetCACert() throws Exception { 306 log.debug(">test07ScepGetCACert()"); 307 String reqUrl = httpReqPath + '/' + resourceScep+"?operation=GetCACert&message="+URLEncoder.encode(caname, "UTF-8"); 308 URL url = new URL (reqUrl); 309 HttpURLConnection con = (HttpURLConnection )url.openConnection(); 310 con.setRequestMethod("GET"); 311 con.getDoOutput(); 312 con.connect(); 313 assertEquals("Response code", 200, con.getResponseCode()); 314 assertEquals("Content-Type", "application/x-x509-ca-cert", con.getContentType()); 315 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 316 InputStream in = con.getInputStream(); 318 int b = in.read(); 319 while (b != -1) { 320 baos.write(b); 321 b = in.read(); 322 } 323 baos.flush(); 324 in.close(); 325 byte[] respBytes = baos.toByteArray(); 326 assertNotNull("Response can not be null.", respBytes); 327 assertTrue(respBytes.length > 0); 328 X509Certificate cert = CertTools.getCertfromByteArray(respBytes); 329 assertEquals(cacert.getSubjectDN().getName(), cert.getSubjectDN().getName()); 331 log.debug(">test07ScepGetCACert()"); 332 } 333 334 public void test08ScepGetCrl() throws Exception { 335 log.debug(">test08ScepGetCrl()"); 336 byte[] msgBytes = genScepRequest(true, CMSSignedGenerator.DIGEST_SHA1); 337 byte[] retMsg = sendScep(false, msgBytes, false); 339 assertNotNull(retMsg); 340 checkScepResponse(retMsg, "C=SE,O=PrimeKey,CN=sceptest", senderNonce, transId, true, CMSSignedGenerator.DIGEST_SHA1, false); 341 log.debug(">test08ScepGetCrl()"); 342 } 343 public void test09ScepGetCACaps() throws Exception { 344 log.debug(">test09ScepGetCACaps()"); 345 String reqUrl = httpReqPath + '/' + resourceScep+"?operation=GetCACaps&message="+URLEncoder.encode(caname, "UTF-8"); 346 URL url = new URL (reqUrl); 347 HttpURLConnection con = (HttpURLConnection )url.openConnection(); 348 con.setRequestMethod("GET"); 349 con.getDoOutput(); 350 con.connect(); 351 assertEquals("Response code", 200, con.getResponseCode()); 352 assertEquals("Content-Type", "text/plain", con.getContentType()); 353 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 354 InputStream in = con.getInputStream(); 356 int b = in.read(); 357 while (b != -1) { 358 baos.write(b); 359 b = in.read(); 360 } 361 baos.flush(); 362 in.close(); 363 byte[] respBytes = baos.toByteArray(); 364 assertNotNull("Response can not be null.", respBytes); 365 assertTrue(respBytes.length > 0); 366 assertEquals(new String (respBytes), "POSTPKIOperation\nSHA-1"); 367 log.debug(">test09ScepGetCACaps()"); 368 } 369 public void test99CleanUp() throws Exception { 370 usersession.deleteUser(admin,"sceptest"); 372 log.debug("deleted user: sceptest"); 373 } 374 375 private void createScepUser() throws RemoteException , AuthorizationDeniedException, FinderException , UserDoesntFullfillEndEntityProfile, ApprovalException, WaitingForApprovalException { 379 boolean userExists = false; 381 try { 382 usersession.addUser(admin,"sceptest","foo123","C=SE,O=PrimeKey,CN=sceptest",null,"ocsptest@anatom.se",false,SecConst.EMPTY_ENDENTITYPROFILE,SecConst.CERTPROFILE_FIXED_ENDUSER,SecConst.USER_ENDUSER,SecConst.TOKEN_SOFT_PEM,0,caid); 383 log.debug("created user: sceptest, foo123, C=SE, O=PrimeKey, CN=sceptest"); 384 } catch (RemoteException re) { 385 if (re.detail instanceof DuplicateKeyException ) { 386 userExists = true; 387 } 388 } catch (DuplicateKeyException dke) { 389 userExists = true; 390 } 391 392 if (userExists) { 393 log.debug("User sceptest already exists."); 394 usersession.setUserStatus(admin,"sceptest",UserDataConstants.STATUS_NEW); 395 log.debug("Reset status to NEW"); 396 } 397 398 } 399 400 private byte[] genScepRequest(boolean makeCrlReq, String digestoid) throws InvalidKeyException , NoSuchAlgorithmException , NoSuchProviderException , SignatureException , InvalidAlgorithmParameterException , CertStoreException , IOException , CMSException, CertificateEncodingException , IllegalStateException { 401 ScepRequestGenerator gen = new ScepRequestGenerator(); 402 gen.setKeys(keys); 403 gen.setDigestOid(digestoid); 404 byte[] msgBytes = null; 405 if (makeCrlReq) { 406 msgBytes = gen.generateCrlReq("C=SE, O=PrimeKey, CN=sceptest", cacert); 407 } else { 408 msgBytes = gen.generateCertReq("C=SE, O=PrimeKey, CN=sceptest", "foo123", cacert); 409 } 410 assertNotNull(msgBytes); 411 transId = gen.getTransactionId(); 412 assertNotNull(transId); 413 byte[] idBytes = Base64.decode(transId.getBytes()); 414 assertTrue(idBytes.length == 16); 415 senderNonce = gen.getSenderNonce(); 416 byte[] nonceBytes = Base64.decode(senderNonce.getBytes()); 417 assertTrue(nonceBytes.length == 16); 418 return msgBytes; 419 } 420 421 private void checkScepResponse(byte[] retMsg, String userDN, String senderNonce, String transId, boolean crlRep, String digestOid, boolean noca) throws CMSException, NoSuchProviderException , NoSuchAlgorithmException , CertStoreException , InvalidKeyException , CertificateException , SignatureException , CRLException { 422 CMSSignedData s = new CMSSignedData(retMsg); 426 SignerInformationStore signers = s.getSignerInfos(); 428 Collection col = signers.getSigners(); 429 assertTrue(col.size() > 0); 430 Iterator iter = col.iterator(); 431 SignerInformation signerInfo = (SignerInformation)iter.next(); 432 assertEquals(signerInfo.getDigestAlgOID(), digestOid); 434 SignerId sinfo = signerInfo.getSID(); 435 assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()), CertTools.stringToBCDNString(sinfo.getIssuerAsString())); 437 boolean ret = signerInfo.verify(cacert.getPublicKey(), "BC"); 439 assertTrue(ret); 440 AttributeTable tab = signerInfo.getSignedAttributes(); 442 Attribute attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_failInfo)); 444 assertNull(attr); 446 attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_messageType)); 448 assertNotNull(attr); 449 ASN1Set values = attr.getAttrValues(); 450 assertEquals(values.size(), 1); 451 DERString str = DERPrintableString.getInstance((values.getObjectAt(0))); 452 String messageType = str.getString(); 453 assertEquals("3", messageType); 454 attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_pkiStatus)); 456 assertNotNull(attr); 457 values = attr.getAttrValues(); 458 assertEquals(values.size(), 1); 459 str = DERPrintableString.getInstance((values.getObjectAt(0))); 460 assertEquals(ResponseStatus.SUCCESS.getValue(), str.getString()); 461 attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_senderNonce)); 463 assertNotNull(attr); 464 values = attr.getAttrValues(); 465 assertEquals(values.size(), 1); 466 ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); 467 assertTrue(octstr.getOctets().length == 16); 469 attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_recipientNonce)); 471 assertNotNull(attr); 472 values = attr.getAttrValues(); 473 assertEquals(values.size(), 1); 474 octstr = ASN1OctetString.getInstance(values.getObjectAt(0)); 475 assertEquals(senderNonce, new String (Base64.encode(octstr.getOctets()))); 477 attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_transId)); 479 assertNotNull(attr); 480 values = attr.getAttrValues(); 481 assertEquals(values.size(), 1); 482 str = DERPrintableString.getInstance((values.getObjectAt(0))); 483 assertEquals(transId, str.getString()); 485 486 if (messageType.equals("3")) { 490 CMSProcessable sp = s.getSignedContent(); 493 byte[] content = (byte[])sp.getContent(); 494 CMSEnvelopedData ed = new CMSEnvelopedData(content); 495 RecipientInformationStore recipients = ed.getRecipientInfos(); 496 Collection c = recipients.getRecipients(); 497 assertEquals(c.size(), 1); 498 Iterator it = c.iterator(); 499 byte[] decBytes = null; 500 RecipientInformation recipient = (RecipientInformation) it.next(); 501 decBytes = recipient.getContent(keys.getPrivate(), "BC"); 502 CMSSignedData sd = new CMSSignedData(decBytes); 504 CertStore certstore = sd.getCertificatesAndCRLs("Collection","BC"); 506 if (crlRep) { 507 Collection crls = certstore.getCRLs(null); 509 assertEquals(crls.size(), 1); 510 it = crls.iterator(); 511 X509CRL retCrl = null; 512 retCrl = (X509CRL )it.next(); 514 System.out.println("Got CRL with DN: "+ retCrl.getIssuerDN().getName()); 515 assertEquals(cacert.getSubjectDN().getName(), retCrl.getIssuerDN().getName()); 522 retCrl.verify(cacert.getPublicKey()); 523 } else { 524 Collection certs = certstore.getCertificates(null); 526 if (noca) { 528 assertEquals(certs.size(), 1); 529 } else { 530 assertEquals(certs.size(), 2); 531 } 532 it = certs.iterator(); 533 boolean verified = false; 535 boolean gotcacert = false; 536 String mysubjectdn = CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"); 537 while (it.hasNext()) { 538 X509Certificate retcert = (X509Certificate )it.next(); 539 System.out.println("Got cert with DN: "+ retcert.getSubjectDN().getName()); 540 546 String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName()); 548 if (mysubjectdn.equals(subjectdn)) { 549 assertEquals(CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"), subjectdn); 551 assertEquals(cacert.getSubjectDN().getName(), retcert.getIssuerDN().getName()); 552 retcert.verify(cacert.getPublicKey()); 553 assertTrue(checkKeys(keys.getPrivate(), retcert.getPublicKey())); 554 verified = true; 555 } else { 556 assertEquals(cacert.getSubjectDN().getName(), retcert.getSubjectDN().getName()); 558 gotcacert = true; 559 } 560 } 561 assertTrue(verified); 562 if (noca) { 563 assertFalse(gotcacert); 564 } else { 565 assertTrue(gotcacert); 566 } 567 } 568 } 569 570 } 571 574 private boolean checkKeys(PrivateKey priv, PublicKey pub) throws SignatureException , NoSuchAlgorithmException , InvalidKeyException { 575 Signature signer = Signature.getInstance("SHA1WithRSA"); 576 signer.initSign(priv); 577 signer.update("PrimeKey".getBytes()); 578 byte[] signature = signer.sign(); 579 580 Signature signer2 = Signature.getInstance("SHA1WithRSA"); 581 signer2.initVerify(pub); 582 signer2.update("PrimeKey".getBytes()); 583 return signer2.verify(signature); 584 } 585 private byte[] sendScep(boolean post, byte[] scepPackage, boolean noca) throws IOException , NoSuchProviderException { 586 String resource = resourceScep; 589 if (noca) { 590 resource = resourceScepNoCA; 591 } 592 String urlString = httpReqPath + '/' + resource+"?operation=PKIOperation"; 593 log.debug("UrlString =" + urlString); 594 HttpURLConnection con = null; 595 if (post) { 596 URL url = new URL (urlString); 597 con = (HttpURLConnection )url.openConnection(); 598 con.setDoOutput(true); 599 con.setRequestMethod("POST"); 600 con.connect(); 601 OutputStream os = con.getOutputStream(); 603 os.write(scepPackage); 604 os.close(); 605 } else { 606 String reqUrl = urlString + "&message=" + URLEncoder.encode(new String (Base64.encode(scepPackage)),"UTF-8"); 607 URL url = new URL (reqUrl); 608 con = (HttpURLConnection )url.openConnection(); 609 con.setRequestMethod("GET"); 610 con.getDoOutput(); 611 con.connect(); 612 } 613 614 assertEquals("Response code", 200, con.getResponseCode()); 615 assertEquals("Content-Type", "application/x-pki-message", con.getContentType()); 616 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 617 InputStream in = con.getInputStream(); 619 int b = in.read(); 620 while (b != -1) { 621 baos.write(b); 622 b = in.read(); 623 } 624 baos.flush(); 625 in.close(); 626 byte[] respBytes = baos.toByteArray(); 627 assertNotNull("Response can not be null.", respBytes); 628 assertTrue(respBytes.length > 0); 629 return respBytes; 630 } 631 632 } 633 | Popular Tags |