View Javadoc
1 /* 2 * $Header: /cvsroot/ebxmlrr/ebxmlrr/src/share/com/sun/ebxml/registry/util/Utility.java,v 1.25 2003/08/29 02:25:25 farrukh_najmi Exp $ 3 */ 4 package com.sun.ebxml.registry.util; 5 6 import java.util.*; 7 import java.text.SimpleDateFormat; 8 import java.io.*; 9 import java.net.*; 10 import java.security.*; 11 import java.security.cert.X509Certificate; 12 13 import javax.naming.*; 14 import javax.swing.*; 15 16 // java mail 17 import javax.mail.*; 18 import javax.mail.internet.*; 19 20 // jaxp 21 import org.xml.sax.InputSource; 22 23 // jaxm 24 import javax.xml.messaging.*; 25 import javax.xml.soap.*; 26 import javax.xml.soap.MessageFactory; 27 28 import com.sun.ebxml.registry.*; 29 import org.oasis.ebxml.registry.bindings.query.*; 30 import org.oasis.ebxml.registry.bindings.query.types.*; 31 import org.oasis.ebxml.registry.bindings.rs.*; 32 import org.oasis.ebxml.registry.bindings.rs.types.*; 33 import org.oasis.ebxml.registry.bindings.rim.*; 34 35 36 import java.nio.charset.Charset; 37 38 39 /*** 40 * Class Declaration. 41 * @see 42 * @author Farrukh S. Najmi 43 * @author Adrian Chong 44 * @version 1.2, 05/02/00 45 */ 46 public class Utility { 47 48 /*** 49 * Class Constructor. 50 * 51 * 52 * @see 53 */ 54 protected Utility() {} 55 56 /*** 57 @deprecated Do not use it. It may have problem in handling encoding. 58 */ 59 public StringBuffer getStringBufferFromInputStream(InputStream is) throws IOException { 60 int buflen = 1024; 61 char[] chars = new char[buflen+1]; 62 StringBuffer strBuf = new StringBuffer(); 63 64 BufferedReader br = new BufferedReader(new InputStreamReader(is)); 65 66 int charsRead = 0; 67 while((charsRead = br.read(chars, 0, buflen)) != -1) { 68 //System.err.println("chars[0] = '" + chars[0] + "' charsRead = " + charsRead); 69 strBuf.append(chars, 0, charsRead); 70 } 71 72 return strBuf; 73 } 74 75 /*** 76 Get the <?xml version="1.0"?> decalaration from XML bytes 77 */ 78 public String getXMLDeclaration(byte [] bytes) { 79 String str = new String(bytes); 80 return removeXMLDeclaration(new StringBuffer(str)); 81 } 82 83 /*** 84 * Removes the <?xml version="1.0"?> decalaration from XML bytes 85 @return the bytes of the XML document 86 */ 87 public byte[] removeXMLDeclaration(byte [] bytes) throws IOException { 88 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 89 int declEndIndex = 0; 90 91 // Get the end index of declaration 92 if (bytes[0] == '<') { 93 94 boolean hasDecl = false; 95 for (int i=1; i < bytes.length; i++) { 96 if (bytes[1]==' ') { 97 //Skip spaces after '<' 98 declEndIndex++; 99 } 100 else if (bytes[i]=='?') { 101 // It has declaration 102 hasDecl = true; 103 } 104 if (hasDecl) { 105 if (bytes[i] != '>') { 106 declEndIndex++; 107 } 108 else { 109 declEndIndex++; 110 break; 111 } 112 } 113 } 114 } 115 116 // skip all spaces after the xml declaration 117 for (int i=declEndIndex; i < bytes.length; i++) { 118 declEndIndex++; 119 if (bytes[i] != ' ') { 120 break; 121 } 122 } 123 124 // System.err.println(declEndIndex + "!!!!!"); 125 bos.write(bytes, declEndIndex, bytes.length - declEndIndex); 126 bos.flush(); 127 bos.close(); 128 //System.err.println(new String(bos.toByteArray())); 129 return bos.toByteArray(); 130 131 } 132 133 /*** 134 * Removes the <?xml version="1.0"?> decalaration from XML string 135 @return the XML declaration 136 */ 137 public String removeXMLDeclaration(StringBuffer str) { 138 139 String decl = ""; 140 int len = str.length(); 141 int startIndex = -1; //start of what we are removing 142 int endIndex = -1; //end of what we are removing 143 for (int i=0; i<len; i++) { 144 if (str.charAt(i) == '<') { 145 decl += "<"; 146 startIndex = i; 147 148 //Skip spaces after '<' 149 i++; 150 while (str.charAt(i) == ' ') { 151 decl += " "; 152 i++; 153 } 154 155 if (str.charAt(i) == '?') { 156 //We have an XML declaration to remove 157 //Skip forward and find matching '>' 158 while (str.charAt(i) != '>') { 159 decl += str.charAt(i); 160 i++; 161 } 162 decl += ">"; 163 endIndex = i; 164 break; 165 } 166 else { 167 //Not an XML declaration 168 startIndex = -1; 169 break; 170 } 171 172 } 173 } 174 175 if (startIndex != -1) { 176 str.delete(startIndex, endIndex+1); 177 } 178 179 return decl; 180 } 181 182 /*** 183 * Mimics javamail boundary id generator 184 */ 185 public static String getMimeBoundary() 186 { 187 Session session = null;//Session.getDefaultInstance(new Properties()); 188 189 String s = null; 190 InternetAddress internetaddress = InternetAddress.getLocalAddress(session); 191 if(internetaddress != null) 192 s = internetaddress.getAddress(); 193 else 194 s = "javamailuser@localhost"; 195 StringBuffer stringbuffer = new StringBuffer(); 196 stringbuffer.append(stringbuffer.hashCode()).append('.').append(System.currentTimeMillis()).append('.').append("ebxmlrr.").append(s); 197 return stringbuffer.toString(); 198 } 199 200 /* 201 public InputStream createSOAPStreamFromRequestStream(InputStream req) throws SOAPException, IOException, ParseException { 202 203 String soapNS = "http://schemas.xmlsoap.org/soap/envelope/"; 204 String soapEnv = "soap-env"; 205 String soapEnvPrefix = soapEnv + ":"; 206 207 StringBuffer reqStr = Utility.getInstance().getStringBufferFromInputStream(req); 208 String decl = removeXMLDeclaration(reqStr); 209 210 String boundary = getMimeBoundary(); 211 212 System.err.println(decl); 213 214 String msgStr = //"--" + boundary + 215 decl + 216 "\n<" + soapEnvPrefix + "Envelope" + 217 "\n\txmlns:soap-env=\"" + soapNS + "\"" + 218 "\n\txmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/2000-12\" soap-env:actor=\"some-uri\"" + 219 "\n\tsoap-env:mustUnderstand=\"1\">" + 220 221 //The SOAP Header 222 "\n\n\t<" + soapEnvPrefix + "Header>" + 223 224 //DSIG goes here 225 226 "\n\t</" + soapEnvPrefix + "Header>" + 227 228 //The SOAP Body 229 "\n\n\t<" + soapEnvPrefix + "Body SOAP-SEC:id=\"Body\">" + "\n" + 230 231 //The ebXML Registry request goes here 232 reqStr + 233 234 "\n\t</" + soapEnvPrefix + "Body>" + 235 236 "\n\n</" + soapEnvPrefix + "Envelope>" 237 //+ "\n--" + boundary + "--" 238 ; 239 240 //System.err.println(msgStr); 241 242 InputStream is = (InputStream) new StringBufferInputStream(msgStr); 243 244 245 MimeHeaders headers = new MimeHeaders(); 246 headers.addHeader("Content-Type", "text/xml"); 247 SOAPMessage message = MessageFactory.newInstance().createMessage(headers, is); 248 ByteArrayOutputStream out = new ByteArrayOutputStream(); 249 message.writeTo(out); 250 out.flush(); 251 ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); 252 253 return in; 254 } 255 */ 256 257 /*** 258 Get bytes array from InputStream 259 */ 260 public byte [] getBytesFromInputStream(InputStream is) throws IOException { 261 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 262 while(true) { 263 byte [] buffer = new byte[100]; 264 int noOfBytes = is.read(buffer); 265 if (noOfBytes == -1) { 266 break; 267 } 268 else { 269 bos.write(buffer, 0, noOfBytes); 270 } 271 } 272 bos.flush(); 273 bos.close(); 274 return bos.toByteArray(); 275 } 276 277 /*** 278 Create a SOAPMessage containing a registry request (e.g. SubmitObjectsRequest) 279 @param req the InputStream to the registry request 280 @return the InputStream to the the created SOAPMessage 281 */ 282 public InputStream createSOAPStreamFromRequestStream(InputStream req) throws SOAPException, IOException, ParseException { 283 284 String soapNS = "http://schemas.xmlsoap.org/soap/envelope/"; 285 String soapEnv = "soap-env"; 286 String soapEnvPrefix = soapEnv + ":"; 287 288 byte [] requestBytesWithDecl = getBytesFromInputStream(req); 289 String decl = getXMLDeclaration(requestBytesWithDecl); 290 byte [] requestBytes = removeXMLDeclaration(requestBytesWithDecl); 291 requestBytesWithDecl = null; 292 293 // System.err.println(decl); 294 295 String partBeforeRequestStr = //"--" + boundary + 296 decl + 297 "\n<" + soapEnvPrefix + "Envelope" + 298 "\n\txmlns:soap-env=\"" + soapNS + "\"" + 299 "\n\txmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/2000-12\" soap-env:actor=\"some-uri\"" + 300 "\n\tsoap-env:mustUnderstand=\"1\">" + 301 302 //The SOAP Header 303 "\n\n\t<" + soapEnvPrefix + "Header>" + 304 305 //DSIG goes here 306 307 "\n\t</" + soapEnvPrefix + "Header>" + 308 309 //The SOAP Body 310 "\n\n\t<" + soapEnvPrefix + "Body SOAP-SEC:id=\"Body\">" + "\n"; 311 312 //The ebXML Registry request goes here 313 314 315 String partAfterRequestStr = 316 "\n\t</" + soapEnvPrefix + "Body>" + 317 318 "\n\n</" + soapEnvPrefix + "Envelope>" 319 //+ "\n--" + boundary + "--" 320 ; 321 322 // We concatenate the three bytes array to a single big array 323 byte [] partBeforeRequestBytes = partBeforeRequestStr.getBytes("ISO-8859-1"); // The soap env does not have non ascii chars 324 byte [] partAfterRequestBytes = partAfterRequestStr.getBytes("ISO-8859-1"); // The soap env does not have non ascii chars 325 byte [] soapBytes = new byte[partBeforeRequestBytes.length + requestBytes.length + partAfterRequestBytes.length]; 326 327 int soapBytesIndex=0; 328 for(int a=0; a<partBeforeRequestBytes.length; a++) { 329 soapBytes[soapBytesIndex] = partBeforeRequestBytes[a]; 330 soapBytesIndex++; 331 } 332 for(int b=0; b<requestBytes.length; b++) { 333 soapBytes[soapBytesIndex] = requestBytes[b]; 334 soapBytesIndex++; 335 } 336 for(int c=0; c<partAfterRequestBytes.length; c++) { 337 soapBytes[soapBytesIndex] = partAfterRequestBytes[c]; 338 soapBytesIndex++; 339 } 340 // System.err.println("L343:" + new String(soapBytes)); 341 return new ByteArrayInputStream(soapBytes); 342 } 343 344 /*** 345 Create a SOAPMessage containing a registry request (e.g. SubmitObjectsRequest) 346 @param req the InputStream to the registry request 347 @return the created SOAPMessage 348 */ 349 public SOAPMessage createSOAPMessageFromRequestStream(InputStream reqStream) throws SOAPException, IOException, ParseException { 350 351 InputStream is = createSOAPStreamFromRequestStream(reqStream); 352 353 MimeHeaders mimeHeaders = new MimeHeaders(); 354 355 ContentType contentType = new ContentType("text/xml"); //"multipart/related"); 356 //contentType.setParameter("boundary", boundary); 357 //contentType.setParameter("type", "text/xml"); 358 String contentTypeStr = contentType.toString(); 359 //System.err.println("contentTypeStr = '" + contentTypeStr + "'"); 360 361 mimeHeaders.addHeader("Content-Type", contentTypeStr); 362 mimeHeaders.addHeader("Content-Id", "ebXML Registry SOAP request"); 363 364 MessageFactory factory = MessageFactory.newInstance(); 365 SOAPMessage msg = factory.createMessage(mimeHeaders, is); 366 367 msg.saveChanges(); 368 369 return msg; 370 } 371 372 /*** 373 Create a SOAPMessage object from a InputStream to a SOAPMessage 374 @param soapStream the InputStream to the SOAPMessage 375 @return the created SOAPMessage 376 */ 377 public SOAPMessage createSOAPMessageFromSOAPStream(InputStream soapStream) throws SOAPException, IOException, ParseException { 378 379 MimeHeaders mimeHeaders = new MimeHeaders(); 380 381 ContentType contentType = new ContentType("text/xml"); //"multipart/related"); 382 //contentType.setParameter("boundary", boundary); 383 //contentType.setParameter("type", "text/xml"); 384 String contentTypeStr = contentType.toString(); 385 //System.err.println("contentTypeStr = '" + contentTypeStr + "'"); 386 387 mimeHeaders.addHeader("Content-Type", contentTypeStr); 388 mimeHeaders.addHeader("Content-Id", "ebXML Registry SOAP request"); 389 390 MessageFactory factory = MessageFactory.newInstance(); 391 SOAPMessage msg = factory.createMessage(mimeHeaders, soapStream); 392 393 msg.saveChanges(); 394 395 return msg; 396 } 397 398 public RegistryResponse createRegistryResponseFromThrowable(Throwable t, String codeContext, String errCode) { 399 RegistryResponse resp = new RegistryResponse(); 400 resp.setStatus(StatusType.FAILURE); 401 RegistryErrorList el = new RegistryErrorList(); 402 RegistryError re = new RegistryError(); 403 el.addRegistryError(re); 404 resp.setRegistryErrorList(el); 405 406 String stackTrace = getStackTraceFromThrowable(t); 407 System.err.println(stackTrace); 408 409 String nestedStackTrace = null; 410 if (t instanceof com.sun.ebxml.registry.RegistryException) { 411 Exception nestedException = ((RegistryException)t).getException(); 412 nestedStackTrace = getStackTraceFromThrowable(nestedException); 413 } 414 415 stackTrace += "\n\nNested exception was:\n" + nestedStackTrace; 416 417 re.setContent(stackTrace); 418 re.setCodeContext(codeContext); 419 re.setErrorCode(errCode); 420 421 return resp; 422 } 423 424 public String getStackTraceFromThrowable(Throwable t) { 425 String trace = null; 426 if (t != null) { 427 StringWriter sw = new StringWriter(); 428 PrintWriter pw = new PrintWriter(sw); 429 t.printStackTrace(pw); 430 trace = sw.toString(); 431 } 432 433 return trace; 434 } 435 436 public String createTimestamp() { 437 // Get the time zone offset in +HH:mm format 438 439 TimeZone tz = TimeZone.getDefault(); 440 441 float rawOffset = tz.getRawOffset() / 1000 / 60 / 60.0f; 442 int offsetHr = (int) Math.abs(rawOffset); 443 int offsetMin = (int)(rawOffset - offsetHr) * 60; 444 445 String offset = rawOffset > 0 ? "+" : "-"; 446 offset += offsetHr < 10 ? "0" : ""; 447 offset += offsetHr; 448 offset += ":"; 449 offset += offsetMin < 10 ? "0" : ""; 450 offset += offsetMin; 451 452 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 453 return sdf.format(new Date()) + offset; 454 } 455 456 /*** 457 Return ArrayList of ExternalLink that points to unresolvable Http URLs. Any 458 non-Http URLs will not be checked. Any non-Http URLs and other types 459 of URIs will not be checked. If the http response code is smaller than 200 460 or bigger than 299, the http URL is considered invalid. 461 */ 462 463 public ArrayList validateURIs(ArrayList sourceRegistryObjects) throws 464 RegistryException { 465 ArrayList invalidURLROs = new ArrayList(); 466 Iterator iter = sourceRegistryObjects.iterator(); 467 while (iter.hasNext()) { 468 Object ro = iter.next(); 469 String uRI = null; 470 471 if (ro instanceof ExternalLink) { 472 uRI = ((ExternalLink)ro).getExternalURI(); 473 } 474 else if (ro instanceof ServiceBinding) { 475 uRI = ((ServiceBinding)ro).getAccessURI(); 476 } 477 else { 478 throw new RegistryException("Internal Error happens, unknown " 479 + "RegistryObjectType"); 480 } 481 482 if (!isValidURI(uRI)) { 483 invalidURLROs.add(ro); 484 } 485 } 486 return invalidURLROs; 487 } 488 489 /*** 490 Any non-Http URLs and other types of URIs will not be checked. If the http 491 response code is smaller than 200 or bigger than 299, the http URL is 492 considered invalid. 493 */ 494 public boolean isValidURI(String uRI) { 495 URL uRL = null; 496 try { 497 uRL = new URL(uRI); 498 } 499 catch(MalformedURLException e) { 500 // Not an URL, will not try to resolve 501 return true; 502 } 503 // Try to resolve the URLs here 504 if (uRL.getProtocol().equalsIgnoreCase("http")) { 505 try { 506 HttpURLConnection httpUrlConn = (HttpURLConnection)uRL 507 .openConnection(); 508 int responseCode = httpUrlConn.getResponseCode(); 509 if (responseCode < 200 || responseCode > 299) { 510 return false; 511 } 512 else { 513 return true; 514 } 515 } 516 catch (IOException e) { 517 return false; 518 } 519 } 520 else { 521 // Will not resolve non-http URL 522 return true; 523 } 524 } 525 526 527 //Based on code contributed by Bobby Bissett 528 public org.w3c.dom.Element getSignatureElement(SOAPMessage msg) 529 throws SOAPException, javax.xml.transform.TransformerException { 530 org.w3c.dom.Element sigElement = null; 531 532 javax.xml.transform.Transformer xFormer = 533 javax.xml.transform.TransformerFactory.newInstance().newTransformer(); 534 535 // grab info out of msg 536 SOAPPart msgPart = msg.getSOAPPart(); 537 javax.xml.transform.Source msgSource = msgPart.getContent(); 538 539 // transform 540 javax.xml.transform.dom.DOMResult domResult = 541 new javax.xml.transform.dom.DOMResult(); 542 xFormer.transform(msgSource, domResult); 543 544 //root node is the soap:Envelope 545 org.w3c.dom.Node envelopeNode = domResult.getNode(); 546 547 //now you have the node. the following code strips off the envelope of 548 //the soap message to get to the actual content 549 550 // Advance to envelope node in case of text nodes preceding it 551 while ((envelopeNode.getLocalName() == null) || 552 (!envelopeNode.getLocalName().equalsIgnoreCase("envelope"))) { 553 envelopeNode = envelopeNode.getFirstChild(); 554 } 555 556 // Advance to header within envelope node 557 org.w3c.dom.Node headerNode = envelopeNode.getFirstChild(); 558 while ((headerNode.getLocalName() == null) || 559 (!headerNode.getLocalName().equalsIgnoreCase("header"))) { 560 headerNode = headerNode.getNextSibling(); 561 } 562 563 //System.err.println("headerNode name is: " + headerNode.getLocalName()); 564 565 // Advance to signature node within header 566 org.w3c.dom.Node sigNode = headerNode.getFirstChild(); 567 568 if (sigNode == null) { 569 return null; 570 } 571 572 //System.err.println("sigNode: " + sigNode); 573 while ((sigNode.getLocalName() == null) || 574 (!sigNode.getLocalName().equalsIgnoreCase("signature"))) { 575 sigNode = sigNode.getNextSibling(); 576 if (sigNode == null) { 577 return null; 578 } 579 } 580 581 //Desired Signature element may be inside a SOAP-SEC signature element 582 if (!sigNode.getNamespaceURI().equals("http://www.w3.org/2000/09/xmldsig#")) { 583 sigNode = sigNode.getFirstChild(); 584 while ((sigNode.getLocalName() == null) || 585 (!sigNode.getLocalName().equalsIgnoreCase("signature"))) { 586 sigNode = sigNode.getNextSibling(); 587 } 588 } 589 590 if (sigNode.getNamespaceURI().equals("http://www.w3.org/2000/09/xmldsig#")) { 591 if (sigNode instanceof org.w3c.dom.Element) { 592 sigElement = (org.w3c.dom.Element)sigNode; 593 } 594 } 595 596 return sigElement; 597 } 598 599 600 /*** 601 * Strip urn:uuid: part from start of registry 602 * object id. If id is null or doesn't start with 603 * urn:uuid: then the id is returned without modification. 604 */ 605 public String stripId(String id) 606 { 607 if (id != null && 608 id.startsWith("urn:uuid:")) 609 { 610 id = id.substring(9).trim(); 611 } 612 613 return id; 614 } 615 616 617 /*** 618 Convert the apostrophes in a String field in a SQL statement to 2 619 consecutive apostrohes 620 */ 621 public static String escapeSQLChars(String stringField) { 622 StringBuffer result = new StringBuffer(); 623 for(int i = 0; i < stringField.length(); i++) { 624 char c = stringField.charAt(i); 625 result.append(c); 626 if (c == '\'') { 627 result.append(c); 628 } 629 } 630 return result.toString(); 631 } 632 633 634 635 /*** 636 * Method Declaration. 637 * 638 * 639 * @return 640 * 641 * @see 642 */ 643 public static Utility getInstance() { 644 if (instance == null) { 645 synchronized (Utility.class) { 646 if (instance == null) { 647 instance = new Utility(); 648 } 649 } 650 } 651 return instance; 652 } 653 654 /*** 655 * @link 656 * @shapeType PatternLink 657 * @pattern Singleton 658 * @supplierRole Singleton factory 659 */ 660 661 /* # private Utility _utility; */ 662 private static Utility instance = null; 663 private String ebxmlrrHome=null; 664 665 }

This page was automatically generated by Maven