001 /*
002 * Copyright (C) 2012 eXo Platform SAS.
003 *
004 * This is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU Lesser General Public License as
006 * published by the Free Software Foundation; either version 2.1 of
007 * the License, or (at your option) any later version.
008 *
009 * This software is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * You should have received a copy of the GNU Lesser General Public
015 * License along with this software; if not, write to the Free
016 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018 */
019 package org.crsh.util;
020
021 import javax.naming.Context;
022 import javax.naming.NamingException;
023 import java.io.Closeable;
024 import java.io.IOException;
025 import java.net.Socket;
026 import java.sql.Connection;
027 import java.sql.ResultSet;
028 import java.sql.SQLException;
029 import java.sql.Statement;
030
031 public class Safe {
032
033 public static void close(Socket socket) {
034 if (socket != null) {
035 try {
036 socket.close();
037 }
038 catch (IOException ignore) {
039 }
040 }
041 }
042
043 public static void close(Closeable closeable) {
044 if (closeable != null) {
045 try {
046 closeable.close();
047 }
048 catch (IOException ignore) {
049 }
050 }
051 }
052
053 public static void close(Connection connection) {
054 if (connection != null) {
055 try {
056 connection.close();
057 }
058 catch (SQLException ignore) {
059 }
060 }
061 }
062
063 public static void close(Statement statement) {
064 if (statement != null) {
065 try {
066 statement.close();
067 }
068 catch (SQLException ignore) {
069 }
070 }
071 }
072
073 public static void close(ResultSet rs) {
074 if (rs != null) {
075 try {
076 rs.close();
077 }
078 catch (SQLException ignore) {
079 }
080 }
081 }
082
083 public static void close(Context rs) {
084 if (rs != null) {
085 try {
086 rs.close();
087 }
088 catch (NamingException ignore) {
089 }
090 }
091 }
092
093 public static <T extends Throwable> void rethrow(Class<T> throwableClass, Throwable cause) throws T {
094 T throwable;
095
096 //
097 try {
098 throwable = throwableClass.newInstance();
099 }
100 catch (Exception e) {
101 throw new AssertionError(e);
102 }
103
104 //
105 throwable.initCause(cause);
106
107 //
108 throw throwable;
109 }
110
111 public static boolean equals(Object o1, Object o2) {
112 return o1 == null ? o2 == null : (o2 != null && o1.equals(o2));
113 }
114
115 public static boolean notEquals(Object o1, Object o2) {
116 return !equals(o1, o2);
117 }
118 }