This project has retired. For details please refer to its Attic page.
ExceptionHelper xref

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.chemistry.opencmis.server.shared;
20  
21  import java.io.PrintWriter;
22  import java.io.StringWriter;
23  
24  import javax.xml.parsers.DocumentBuilder;
25  import javax.xml.parsers.DocumentBuilderFactory;
26  
27  import org.w3c.dom.Document;
28  import org.w3c.dom.Element;
29  import org.w3c.dom.Node;
30  
31  public class ExceptionHelper {
32  
33      public static final String STACK_TRACE_PROPERTY = "org.apache.chemistry.opencmis.stacktrace.disable";
34  
35      private static final boolean sendStackTrace;
36  
37      static {
38          sendStackTrace = System.getProperty(STACK_TRACE_PROPERTY) == null;
39      }
40  
41      private ExceptionHelper() {
42      }
43  
44      /**
45       * Returns the stack trace as string.
46       */
47      public static String getStacktraceAsString(Throwable t) {
48          if (!sendStackTrace || t == null) {
49              return null;
50          }
51  
52          StringWriter sw = new StringWriter();
53          PrintWriter pw = new PrintWriter(sw);
54  
55          t.printStackTrace(pw);
56  
57          return sw.toString();
58      }
59  
60      /**
61       * Returns the stack trace as DOM node.
62       */
63      public static Node getStacktraceAsNode(Throwable t) {
64          try {
65              String st = getStacktraceAsString(t);
66              if (st != null) {
67                  DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
68                  DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
69                  Document doc = docBuilder.newDocument();
70  
71                  Element node = doc.createElementNS("http://chemistry.apache.org/opencmis/exception", "stacktrace");
72                  doc.appendChild(node);
73  
74                  node.appendChild(doc.createTextNode(st));
75  
76                  return node;
77              }
78          } catch (Exception e) {
79          }
80  
81          return null;
82      }
83  }