Example usage for java.lang IllegalArgumentException initCause

List of usage examples for java.lang IllegalArgumentException initCause

Introduction

In this page you can find the example usage for java.lang IllegalArgumentException initCause.

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:Main.java

public static Document createDocument(Reader reader) throws IllegalArgumentException {
    // init DOM builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setCoalescing(true);/*w  w  w. j a  va2 s .co m*/
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setValidating(false);

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource inputSource = new InputSource(reader);
        Document doc = builder.parse(inputSource);
        return doc;
    } catch (Exception ex) {
        IllegalArgumentException iae = new IllegalArgumentException(ex.getMessage());
        iae.initCause(ex);
        throw iae;
    }
}

From source file:br.com.nordestefomento.jrimum.utilix.DateUtil.java

/**
 * <p>//from  w ww .j  ava2 s.  co  m
 * Converte um objeto <code>String</code> em um objeto
 * <code>java.util.Date</code> atravs do objeto
 * <code>java.text.DateFormat</code> especificado.
 * </p>
 * 
 * @param dateAsString
 *            - um valor de data em forma de <code>String</code>.
 * @param dateFormat
 *            - formatador para objetos <code>java.util.Date</code>.
 * @return Objeto <code>java.util.Date</code> convertido a partir do objeto
 *         <code>String</code>
 * 
 * @throws IllegalArgumentException
 *             caso o objeto <code>String</code> no seja um valor vlido de
 *             data suportado pelo formatador.
 * @since 0.2
 */
public static Date parse(String dateAsString, DateFormat dateFormat) {

    Date date = null;

    if (dateAsString == null) {
        throw new NullPointerException("A String a ser convertida no pode ter valor [null].");
    }

    if (dateFormat == null) {
        throw new NullPointerException("O formatador no pode ter valor [null].");
    }

    try {

        date = dateFormat.parse(dateAsString);

    } catch (ParseException e) {

        String msg = "A String [" + dateAsString + "] deve ser uma data vlida no formato";
        if (dateFormat instanceof SimpleDateFormat) {
            SimpleDateFormat sdf = (SimpleDateFormat) dateFormat;
            msg += " [" + sdf.toPattern() + "].";

        } else {
            msg += " especificado.";
        }

        IllegalArgumentException iae = new IllegalArgumentException(msg);
        iae.initCause(e);
        throw iae;
    }

    return date;
}

From source file:com.examples.with.different.packagename.concolic.MathRuntimeException.java

/**
 * Constructs a new <code>IllegalArgumentException</code> with specified nested
 * <code>Throwable</code> root cause.
 * @param rootCause the exception or error that caused this exception
 * to be thrown./*from  w w  w  .j av a  2 s.  c o m*/
 * @return built exception
 */
public static IllegalArgumentException createIllegalArgumentException(final Throwable rootCause) {
    IllegalArgumentException iae = new IllegalArgumentException(rootCause.getLocalizedMessage());
    iae.initCause(rootCause);
    return iae;
}

From source file:jcurl.sim.core.SlideStrategy.java

public static SlideStrategy newInstance(final Class clz) {
    final Class parent = SlideStrategy.class;
    if (!parent.isAssignableFrom(clz))
        throw new IllegalArgumentException(
                "Class [" + clz.getName() + "] is no descendant of [" + parent.getName() + "]");
    try {//ww w . j a  v a 2s  . c o  m
        return (SlideStrategy) clz.newInstance();
    } catch (InstantiationException e) {
        final IllegalArgumentException ex = new IllegalArgumentException();
        ex.initCause(e);
        throw ex;
    } catch (IllegalAccessException e) {
        final IllegalArgumentException ex = new IllegalArgumentException();
        ex.initCause(e);
        throw ex;
    } catch (SecurityException e) {
        final IllegalArgumentException ex = new IllegalArgumentException();
        ex.initCause(e);
        throw ex;
    }
}

From source file:com.jpeterson.littles3.S3ObjectRequest.java

/**
 * Create an <code>S3Object</code> based on the request supporting virtual
 * hosting of buckets.//from   w  w w  . ja va2 s.  com
 * 
 * @param req
 *            The original request.
 * @param baseHost
 *            The <code>baseHost</code> is the HTTP Host header that is
 *            "expected". This is used to help determine how the bucket name
 *            will be interpreted. This is used to implement the "Virtual
 *            Hosting of Buckets".
 * @param authenticator
 *            The authenticator to use to authenticate this request.
 * @return An object initialized from the request.
 * @throws IllegalArgumentException
 *             Invalid request.
 */
@SuppressWarnings("unchecked")
public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator)
        throws IllegalArgumentException, AuthenticatorException {
    S3ObjectRequest o = new S3ObjectRequest();
    String pathInfo = req.getPathInfo();
    String contextPath = req.getContextPath();
    String requestURI = req.getRequestURI();
    String undecodedPathPart = null;
    int pathInfoLength;
    String requestURL;
    String serviceEndpoint;
    String bucket = null;
    String key = null;
    String host;
    String value;
    String timestamp;

    baseHost = baseHost.toLowerCase();

    host = req.getHeader("Host");
    if (host != null) {
        host = host.toLowerCase();
    }

    try {
        requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        e.printStackTrace();
        IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8");
        t.initCause(e);
        throw t;
    }

    if (!requestURL.endsWith(pathInfo)) {
        String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]";
        throw new IllegalArgumentException(m);
    }

    pathInfoLength = pathInfo.length();

    serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength);

    if (debug) {
        System.out.println("---------------");
        System.out.println("requestURI: " + requestURI);
        System.out.println("serviceEndpoint: " + serviceEndpoint);
        System.out.println("---------------");
    }

    if ((host == null) || // http 1.0 form
            (host.equals(baseHost))) { // ordinary method
        // http 1.0 form
        // bucket first part of path info
        // key second part of path info
        if (pathInfoLength > 1) {
            int index = pathInfo.indexOf('/', 1);
            if (index > -1) {
                bucket = pathInfo.substring(1, index);

                if (pathInfoLength > (index + 1)) {
                    key = pathInfo.substring(index + 1);
                    undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(),
                            requestURI.length());
                }
            } else {
                bucket = pathInfo.substring(1);
            }
        }
    } else if (host.endsWith("." + baseHost)) {
        // bucket prefix of host
        // key is path info
        bucket = host.substring(0, host.length() - 1 - baseHost.length());
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    } else {
        // bucket is host
        // key is path info
        bucket = host;
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    }

    // timestamp
    timestamp = req.getHeader("Date");

    // CanonicalizedResource
    StringBuffer canonicalizedResource = new StringBuffer();

    canonicalizedResource.append('/');
    if (bucket != null) {
        canonicalizedResource.append(bucket);
    }
    if (undecodedPathPart != null) {
        canonicalizedResource.append(undecodedPathPart);
    }
    if (req.getParameter(PARAMETER_ACL) != null) {
        canonicalizedResource.append("?").append(PARAMETER_ACL);
    }

    // CanonicalizedAmzHeaders
    StringBuffer canonicalizedAmzHeaders = new StringBuffer();
    Map<String, String> headers = new TreeMap<String, String>();
    String headerName;
    String headerValue;

    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = ((String) headerNames.nextElement()).toLowerCase();

        if (headerName.startsWith("x-amz-")) {
            for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) {
                headerValue = (String) headerValues.nextElement();
                String currentValue = headers.get(headerValue);

                if (currentValue != null) {
                    // combine header fields with the same name
                    headers.put(headerName, currentValue + "," + headerValue);
                } else {
                    headers.put(headerName, headerValue);
                }

                if (headerName.equals("x-amz-date")) {
                    timestamp = headerValue;
                }
            }
        }
    }

    for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
        headerName = iter.next();
        headerValue = headers.get(headerName);
        canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n");
    }

    StringBuffer stringToSign = new StringBuffer();

    stringToSign.append(req.getMethod()).append("\n");
    value = req.getHeader("Content-MD5");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Content-Type");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Date");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    stringToSign.append(canonicalizedAmzHeaders);
    stringToSign.append(canonicalizedResource);

    if (debug) {
        System.out.println(":v:v:v:v:");
        System.out.println("undecodedPathPart: " + undecodedPathPart);
        System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders);
        System.out.println("canonicalizedResource: " + canonicalizedResource);
        System.out.println("stringToSign: " + stringToSign);
        System.out.println(":^:^:^:^:");
    }

    o.setServiceEndpoint(serviceEndpoint);
    o.setBucket(bucket);
    o.setKey(key);
    try {
        if (timestamp == null) {
            o.setTimestamp(null);
        } else {
            o.setTimestamp(DateUtil.parseDate(timestamp));
        }
    } catch (DateParseException e) {
        o.setTimestamp(null);
    }
    o.setStringToSign(stringToSign.toString());
    o.setRequestor(authenticate(req, o));

    return o;
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * Returns a new {@link URI} containing only the scheme, user info, host,
 * and port of the given {@link URI}.//  w  ww  .j a va2  s  .c  o  m
 *
 * @param uri
 *        the {@link URI} to remove the path and query parts from (must not
 *        be <code>null</code>)
 * @return a new {@link URI} containing only the scheme, user info, host,
 *         and port of the given {@link URI}
 */
public static URI removePathAndQueryParts(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    try {
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
    } catch (final URISyntaxException e) {
        final IllegalArgumentException e2 = new IllegalArgumentException(
                MessageFormat.format(Messages.getString("URIUtils.IllegalURIFormat"), uri)); //$NON-NLS-1$
        e2.initCause(e);
        throw e2;
    }
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * Returns a new {@link URI} containing only the scheme, user info, host,
 * port, and path of the given {@link URI}.
 *
 * @param uri//w w w  . j  a va 2  s .c o m
 *        the {@link URI} to remove the query parts from (must not be
 *        <code>null</code>)
 * @return a new {@link URI} containing only the scheme, user info, host,
 *         port, and path of the given {@link URI}
 */
public static URI removeQueryParts(final URI uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    try {
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), null,
                null);
    } catch (final URISyntaxException e) {
        final IllegalArgumentException e2 = new IllegalArgumentException(
                MessageFormat.format(Messages.getString("URIUtils.IllegalURIFormat"), uri)); //$NON-NLS-1$
        e2.initCause(e);
        throw e2;
    }
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * <p>//from   w w  w. j  av  a  2 s  .c  o m
 * Constructs a new {@link URI} from a string representation of the URI. Any
 * characters in the string that are illegal for URIs will be quoted. This
 * method is an alternative to the single-argument {@link URI} constructor,
 * which requires that all illegal characters must already be quoted.
 * </p>
 *
 * <p>
 * For example, the following code fails with a {@link URISyntaxException}
 * because the path component contains a space character, which is illegal:
 *
 * <pre>
 * URI uri = new URI(&quot;http://example.com/path/a file.txt&quot;);
 * </pre>
 *
 * Instead, do this:
 *
 * <pre>
 * URI uri = URIUtils.newURI(&quot;http://example.com/path/a file.txt&quot;);
 * </pre>
 *
 * </p>
 *
 * @param uri
 *        the {@link String} representation of the {@link URI} (must not be
 *        <code>null</code>)
 * @return a new {@link URI} (never <code>null</code>)
 */
public static URI newURI(final String uri) {
    Check.notNull(uri, "uri"); //$NON-NLS-1$

    /*
     * The URI string could be already encoded. Let's try first just to
     * create an URI object from it.
     */
    try {
        return new URI(uri);
    } catch (final URISyntaxException e) {
        /*
         * Ignore an error, it could be because the URI string either is not
         * encoded or malformed. Try to encode the string, and create a URI
         * object again.
         */
    }

    /*
     * While encoding the URI string, we should take in account that it
     * might contain many parts with their specific encoding rules.
     *
     * Let's use our own elaborated URI class from the HTTP client for that.
     */
    final com.microsoft.tfs.core.httpclient.URI encodedUri;
    try {
        encodedUri = new com.microsoft.tfs.core.httpclient.URI(uri, false);
    } catch (final URIException e) {
        final IllegalArgumentException e2 = new IllegalArgumentException(
                MessageFormat.format(Messages.getString("URIUtils.IllegalURIFormat"), uri)); //$NON-NLS-1$
        e2.initCause(e);
        throw e2;
    }

    /*
     * Now we have correctly encoded URI, but still its syntax could be
     * wrong.
     */
    try {
        return new URI(encodedUri.getEscapedURIReference());
    } catch (final URISyntaxException e) {
        final IllegalArgumentException e2 = new IllegalArgumentException(
                MessageFormat.format(Messages.getString("URIUtils.IllegalURIFormat"), uri)); //$NON-NLS-1$
        e2.initCause(e);
        throw e2;
    }
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * Combine two partial URI paths to create a single path. The second part of
 * the path might already be encoded, or partially encoded. The method
 * encodes all characters that would normally need encoded in a path
 * <b>except</b> for the percent sign (which is left alone).
 *
 * @param path1/*w ww  .  ja  v a  2  s.c  om*/
 *        The path prefix
 *
 * @param path2
 *        A relative path.
 *
 * @return The concatenated string with leading slashes or tildes removed
 *         from the second string.
 */
public static String combinePartiallyEncodedPaths(final String path1, String path2) {
    if (path2 != null) {
        try {
            path2 = URIUtil.encode(path2, ALLOWED_PATH_CHARS_WITH_PERCENT);
        } catch (final URIException e) {
            final IllegalArgumentException e2 = new IllegalArgumentException(
                    MessageFormat.format(Messages.getString("URIUtils.IllegalURIPathFormat"), //$NON-NLS-1$
                            path2));
            e2.initCause(e);
            throw e2;
        }
    }

    return combinePaths(path1, path2);
}

From source file:com.microsoft.tfs.core.util.URIUtils.java

/**
 * Combine two partial URI paths to create a single path.
 *
 * @param path1/*from ww  w .  j av  a2  s . c o  m*/
 *        The path prefix
 *
 * @param path2
 *        A relative path.
 *
 * @param encodeRelativePath
 *        If true, URI-encode the relative path (path2) before appending
 *
 * @return The concatenated string with and leading slashes or tildes
 *         removed from the second string.
 */
public static String combinePaths(final String path1, String path2, final boolean encodeRelativePath) {
    if (encodeRelativePath && path2 != null) {
        try {
            path2 = URIUtil.encodePath(path2);
        } catch (final URIException e) {
            final IllegalArgumentException e2 = new IllegalArgumentException(
                    MessageFormat.format(Messages.getString("URIUtils.IllegalURIPathFormat"), //$NON-NLS-1$
                            path2));
            e2.initCause(e);
            throw e2;
        }
    }

    if (path1 == null || path1.length() == 0) {
        return path2;
    }

    if (path2 == null || path2.length() == 0) {
        return path1;
    }

    final char separator = (path1.indexOf("/") >= 0) ? '/' : '\\'; //$NON-NLS-1$

    final char[] trimChars = new char[] { '\\', '/' };

    return StringUtil.trimEnd(path1, trimChars) + separator + StringUtil.trimBegin(path2, trimChars);
}