Example usage for java.lang IllegalArgumentException getMessage

List of usage examples for java.lang IllegalArgumentException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.baasbox.controllers.File.java

@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class })
public static Result grantOrRevokeToUser(String id, String username, String action, boolean grant) {
    try {/*from   w w w.j a  v a 2  s.c o  m*/
        Permissions permission = PermissionsHelper.permissionsFromString.get(action.toLowerCase());
        if (grant)
            FileService.grantPermissionToUser(id, permission, username);
        else
            FileService.revokePermissionToUser(id, permission, username);
    } catch (IllegalArgumentException e) {
        return badRequest(e.getMessage());
    } catch (RoleNotFoundException e) {
        return notFound("user " + username + " not found");
    } catch (OSecurityAccessException e) {
        return Results.forbidden();
    } catch (OSecurityException e) {
        return Results.forbidden();
    } catch (Throwable e) {
        return internalServerError(e.getMessage());
    }
    return ok();
}

From source file:net.sf.joost.trax.TrAXHelper.java

/**
* Converts a supplied <code>Source</code> to a <code>SAXSource</code>.
* @param source The supplied input source
* @param errorListener an ErrorListener object
* @return a <code>SAXSource</code>
*///  w  ww. j  av  a2 s . c  o m
public static SAXSource getSAXSource(Source source, ErrorListener errorListener) throws TransformerException {

    if (DEBUG)
        log.debug("getting a SAXSource from a Source");
    //SAXSource
    if (source instanceof SAXSource) {
        if (DEBUG)
            log.debug("source is an instance of SAXSource, so simple return");
        return (SAXSource) source;
    }
    //DOMSource
    if (source instanceof DOMSource) {
        if (DEBUG)
            log.debug("source is an instance of DOMSource");
        InputSource is = new InputSource();
        Node startNode = ((DOMSource) source).getNode();
        Document doc;
        if (startNode instanceof Document) {
            doc = (Document) startNode;
        } else {
            doc = startNode.getOwnerDocument();
        }
        if (DEBUG)
            log.debug("using DOMDriver");
        DOMDriver driver = new DOMDriver();
        driver.setDocument(doc);
        is.setSystemId(source.getSystemId());
        driver.setSystemId(source.getSystemId());
        return new SAXSource(driver, is);
    }
    //StreamSource
    if (source instanceof StreamSource) {
        if (DEBUG)
            log.debug("source is an instance of StreamSource");
        InputSource isource = getInputSourceForStreamSources(source, errorListener);
        return new SAXSource(isource);
    } else {
        String errMsg = "Unknown type of source";
        if (log != null)
            log.error(errMsg);
        IllegalArgumentException iE = new IllegalArgumentException(errMsg);
        TransformerConfigurationException tE = new TransformerConfigurationException(iE.getMessage(), iE);
        if (errorListener != null)
            errorListener.error(tE);
        else
            throw tE;
        return null;
    }
}

From source file:edu.lternet.pasta.common.EmlUtility.java

/**
 * Parses and returns the packageId of the provided EML document. The
 * provided document must contain the attribute {@code //@packageId},
 * with values for the full tuple (scope, identifier, revision); otherwise
 * an {@link IllegalEmlPackageIdException} will be thrown.
 *
 * @param emlDocument//from  w w w  .j a v a  2s .c om
 *            an EML document.
 *
 * @return the packageId of the provided EML document.
 *
 * @throws IllegalEmlPackageIdException
 *             if the packageId does not exist, cannot be parsed, or does
 *             contain all of the required values.
 */
public static EmlPackageId getEmlPackageId(Document emlDocument) {

    String packageId = getRawEmlPackageId(emlDocument);

    EmlPackageIdFormat formatter = new EmlPackageIdFormat(Delimiter.DOT);

    EmlPackageId epi = null;

    try {
        epi = formatter.parse(packageId);
    } catch (IllegalArgumentException e) {
        String s = "The EML packageId attribute '" + packageId
                + "' could not be parsed. The parser reported the " + "following error: " + e.getMessage();
        throw new IllegalEmlPackageIdException(s, packageId, e);
    }

    if (epi.getRevision() == null) {
        String s = "The EML packageId attribute '" + packageId + "' is missing a revision.";
        throw new IllegalEmlPackageIdException(s, packageId);
    }

    if (epi.getIdentifier() == null) {
        String s = "The EML packageId attribute '" + packageId
                + "' is missing both an identifier and a revision.";
        throw new IllegalEmlPackageIdException(s, packageId);
    }

    if (epi.getScope() == null) {
        String s = "A value was not specified for the EML packageId " + "attribute.";
        throw new IllegalEmlPackageIdException(s, packageId);
    }

    return epi;
}

From source file:com.acrutiapps.browser.ui.components.CustomWebView.java

private static void setWebSettingsProperty(WebSettings settings, String key, String value) {
    if (sWebSettingsSetProperty != null) {
        try {/*from  w  w  w.ja v  a 2s. c om*/
            sWebSettingsSetProperty.invoke(settings, key, value);
        } catch (IllegalArgumentException e) {
            Log.e("CustomWebView", "setWebSettingsProperty(): " + e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e("CustomWebView", "setWebSettingsProperty(): " + e.getMessage());
        } catch (InvocationTargetException e) {
            Log.e("CustomWebView", "setWebSettingsProperty(): " + e.getMessage());
        }
    }
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

public static Object invoke(Method method, Object obj, Object[] args) {
    Object result = null;/*from w  w w  .  j  a  v a2 s .co m*/
    try {
        method.setAccessible(true);
        result = method.invoke(obj, args);
    } catch (IllegalArgumentException e) {
        if (e.getMessage().equals(IAE_MESSAGE)) {
            MappingUtils.throwMappingException(prepareExceptionMessage(method, args), e);
        }
        MappingUtils.throwMappingException(e);
    } catch (IllegalAccessException e) {
        MappingUtils.throwMappingException(e);
    } catch (InvocationTargetException e) {
        MappingUtils.throwMappingException(e);
    }
    return result;
}

From source file:com.evolveum.midpoint.prism.util.JavaTypeConverter.java

private static XMLGregorianCalendar magicDateTimeParse(String stringDate) {
    try {//from   w w w . ja va  2 s  .co m
        return XmlTypeConverter.createXMLGregorianCalendar(stringDate);
    } catch (IllegalArgumentException e) {
        // No XML format. This is still quite OK. It we will try other formats ...
    }
    Date date;
    try {
        date = DateUtils.parseDate(stringDate, DATE_FORMATS);
    } catch (ParseException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
    return XmlTypeConverter.createXMLGregorianCalendar(date);
}

From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java

public static JSONObject CallFunction(String url, String[] paramNames, String[] paramVals, Context context) {
    JSONObject json = new JSONObject();

    SchemeRegistry supportedSchemes = new SchemeRegistry();

    SSLSocketFactory sf = getSocketFactory(DEBUG);

    // TODO we make assumptions about ports.
    supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    supportedSchemes.register(new Scheme("https", sf, 443));

    HttpParams http_params = new BasicHttpParams();
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(http_params, supportedSchemes);

    // HttpParams http_params = httpclient.getParams();
    http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpConnectionParams.setConnectionTimeout(http_params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(http_params, CONNECTION_TIMEOUT);

    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, http_params);

    if (paramNames == null) {
        paramNames = new String[0];
    }//from   ww w . j a va 2  s. com
    if (paramVals == null) {
        paramVals = new String[0];
    }

    if (paramNames.length != paramVals.length) {
        Log.w(TAG, "Incompatible number of param names and values, bailing on upload!");
        return null;
    }

    SortedMap<String, String> sig_params = new TreeMap<String, String>();

    HttpResponse response = null;
    HttpPost httppost = null;
    Log.d(TAG, "HTTP POST URL: " + url);
    try {
        httppost = new HttpPost(url);
    } catch (IllegalArgumentException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return json;
    }

    try {
        File file = null;
        // If this is a POST call, then it is a file upload. Check to see if
        // a
        // filename is given, and if so, open that file.
        // Get the title of the photo being uploaded so we can pass it into
        // the
        // MultipartEntityMonitored class to be broadcast for progress
        // updates.
        String title = "";
        for (int i = 0; i < paramNames.length; ++i) {
            if (paramNames[i].equals("title")) {
                title = paramVals[i];
            } else if (paramNames[i].equals("filename")) {
                file = new File(paramVals[i]);
                continue;
            }
            sig_params.put(paramNames[i], paramVals[i]);
        }

        MultipartEntityMonitored mp_entity = new MultipartEntityMonitored(context, title);
        if (file != null) {
            mp_entity.addPart("userfile", new FileBody(file));
        }
        for (Map.Entry<String, String> entry : sig_params.entrySet()) {
            mp_entity.addPart(entry.getKey(), new StringBody(entry.getValue()));
        }
        httppost.setEntity(mp_entity);

        response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            String content = convertStreamToString(resEntity.getContent());
            if (response.getStatusLine().getStatusCode() == 200) {
                try {
                    json = new JSONObject(content.toString());
                } catch (JSONException e1) {
                    Log.w(TAG, "Response 200 received but invalid JSON.");
                    json.put("fail", e1.getMessage());
                    if (DEBUG)
                        Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
                }
            } else {
                Log.w(TAG, "File upload failed with response code:" + response.getStatusLine().getStatusCode());
                json.put("fail", response.getStatusLine().getReasonPhrase());
                if (DEBUG)
                    Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
            }
        } else {
            Log.w(TAG, "Response does not contain a valid HTTP entity.");
            if (DEBUG)
                Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine());
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (IllegalStateException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        try {
            json.put("fail", e.getMessage());
        } catch (JSONException e1) {
        }
        e.printStackTrace();
    } catch (JSONException e) {
    }

    httpclient.getConnectionManager().shutdown();

    return json;

}

From source file:airportApp.Query.java

/**
 * This method suggests the closest matching word and country code.
 * //from w w w. j  a  va  2s  .co  m
 * The matching is done based on the Levenshtein distance: the minimum number 
 * of single-character edits (i.e. insertions, deletions or substitutions) 
 * required to change one word into the other. A disadvantage of the Levenshtein 
 * distance is that any change (edit) has an equal influence on the matching 
 * distance, whereas an algorithm that penalizes the different errors in a 
 * different degree (i.e. insertions penalty = 1; deletions penalty = 2; 
 * substitutions penalty = 3) can produce more accurate results in some cases.
 * 
 * To demonstrate the above statement, let us consider the input "Zimb" compared 
 * to the two strings "Zimbabwe" and "Fiji".
 * The Levenshtein distance between "Zimb" and "Zimbabwe" is 4; while between 
 * "Zimb" and "Fiji" it is 3. Therefore, "Fiji" is the closest match. However, 
 * if the input is "Zimbab", the distance between "Zimbab" and "Zimbabwe" is 
 * 2; while between "Zimbab" and "Fiji" is 5. Therefore, "Zimbabwe" is the 
 * closest match.
 * 
 * The Levenshtein distance is not necessarily a bad similarity test. It all 
 * depends on our preferences of how we would like to do the comparisons. In 
 * other cases than the one mentioned above, the Levenshtein distance can 
 * produce more accurate results. There are also many other similarity matching 
 * algorithms (some based on longest common subsequence).
 * 
 * Attention! This method uses a third-party library from commons.apache.org. 
 * Make sure that the library is added to the compilation libraries of your 
 * IDE. The library's Levenshtein algorithm is updated with a newer version 
 * (by Chas Emerick) that avoids OutOfMemory errors that can occur for very 
 * large Strings. The library also contains implementations for finding the 
 * longest common prefix, the Jaro-Winkler distance and another Fuzzy distance. 
 * So they are all alternatives, if one is not satisfied with the Levenshtein's 
 * one, and can also possibly be combined in different ways. Assuming the user 
 * does not misspell the beginning of the country, an algorithm counting the 
 * length of the longest common prefix towards the length of the larger 
 * sequence (a check larger or equal to 25% ) can precede a check for the 
 * Levenshtein's distance.
 * 
 * @param country User input for which a match will be returned.
 * @return Returns a Suggestion object (the closest match to the input 
 * argument and its associated country code) or null , if the match fails 
 * for any reason.
 */
private static Suggestion suggestCountry(String country) {

    Suggestion suggestion = null;
    String suggestionMatch = "";
    String suggestionCode = "";
    int suggestionDistance = -1;

    try {
        countriesReader = new BufferedReader(new FileReader("resources/countries.csv"));

        String line; // pointer (line reader) used with the countries

        countriesReader.readLine(); // skip first line (column names)

        while ((line = countriesReader.readLine()) != null) {

            Country c = Utils.readCountry(line);

            // use the smaller distance of code name and country name
            int codeDistance = StringUtils.getLevenshteinDistance(country, c.getCode());
            int nameDistance = StringUtils.getLevenshteinDistance(country, c.getName());
            int distance = ((codeDistance < nameDistance) ? codeDistance : nameDistance);

            // keep track of the associated match
            String match = ((codeDistance < nameDistance) ? c.getCode() : c.getName());

            // keep track of the associated country code
            String code = c.getCode();

            // for the first country just overwrite global values
            if (suggestionDistance == -1) {

                suggestionDistance = distance;
                suggestionMatch = match;
                suggestionCode = code;
            } else { // for the rest use the global comaprison

                if (distance < suggestionDistance) {

                    suggestionDistance = distance;
                    suggestionMatch = match;
                    suggestionCode = code;
                }
            }

            suggestion = new Suggestion(suggestionMatch, suggestionCode);

        }

    } catch (IllegalArgumentException ex) {
        System.err.println("Error: " + ex.getMessage());
    } catch (FileNotFoundException ex) {
        System.err.println("Error: " + ex.getMessage());
    } catch (IOException ex) {
        System.err.println("Error: " + ex.getMessage());
    }

    return suggestion;
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Decode and decrypt a password and return the result.
 *
 * @param encryptedPassword/*from ww w . java  2  s  .co  m*/
 * @return the original (decoded/decrypted) password
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 * @throws InvalidKeyException
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws IllegalArgumentException
 *             if the argument is empty or null.
 */
public static String decodeDecrypt(final String encryptedPassword) throws IllegalBlockSizeException,
        BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException, DecoderException {
    if (encryptedPassword == null || (encryptedPassword.length() == 0)) {
        throw new IllegalArgumentException("The password to decrypt is empty or null");
    }
    logger.debug("decodeDecrypt(): encryptedPassword: '" + encryptedPassword + "'");
    final byte[] encryptedPasswordAsciiBytes = encryptedPassword.getBytes(UTF8); // convert
    // from
    // String
    // to
    // byte
    // array

    byte[] encryptedPasswordBinary;
    try {
        encryptedPasswordBinary = Ascii85Encoder.decode(encryptedPasswordAsciiBytes); // decode ascii back
        // to binary
    } catch (final IllegalArgumentException e) {
        throw new IllegalArgumentException("Invalid encrypted password: " + e.getMessage());
    }

    final String reconstitutedString = decryptBinaryToString(encryptedPasswordBinary);
    return reconstitutedString;
}

From source file:airportApp.Query.java

/**
 * This method suggests the closest matching word and country code.
 * //from w  w  w.jav a 2  s. c  om
 * The matching is done based on the longest common prefix. The method will 
 * work acceptably, if the user does not misspell the beginning of the 
 * country (i.e. it will work well with "zimb" = "Zimbabwe").
 * 
 * @param country User input for which a match will be returned.
 * @return Returns a Suggestion object (the closest match to the input 
 * argument and its associated country code) or null , if the match fails 
 * for any reason.
 */
private static Suggestion simpleSuggestCountry(String country) {

    Suggestion suggestion = null;
    String suggestionMatch = "";
    String suggestionCode = "";
    int longestCommonPrefix = -1;

    try {
        countriesReader = new BufferedReader(new FileReader("resources/countries.csv"));

        String line; // pointer (line reader) used with the countries

        countriesReader.readLine(); // skip first line (column names)

        while ((line = countriesReader.readLine()) != null) {

            Country c = Utils.readCountry(line);

            // use the longest common prefix of code name and country name
            int codePrefix = StringUtils
                    .getCommonPrefix(new String[] { country.toLowerCase(), c.getCode().toLowerCase() })
                    .length();
            int namePrefix = StringUtils
                    .getCommonPrefix(new String[] { country.toLowerCase(), c.getName().toLowerCase() })
                    .length();
            int lcp = ((codePrefix > namePrefix) ? codePrefix : namePrefix);

            // keep track of the associated match
            String match = ((codePrefix > namePrefix) ? c.getCode() : c.getName());

            // keep track of the associated country code
            String code = c.getCode();

            // for the first country just overwrite global values
            if (longestCommonPrefix == -1) {

                longestCommonPrefix = lcp;
                suggestionMatch = match;
                suggestionCode = code;
            } else { // for the rest use the global comaprison

                if (lcp > longestCommonPrefix) {

                    longestCommonPrefix = lcp;
                    suggestionMatch = match;
                    suggestionCode = code;
                }
            }

            suggestion = new Suggestion(suggestionMatch, suggestionCode);

        }

    } catch (IllegalArgumentException ex) {
        System.err.println("Error: " + ex.getMessage());
    } catch (FileNotFoundException ex) {
        System.err.println("Error: " + ex.getMessage());
    } catch (IOException ex) {
        System.err.println("Error: " + ex.getMessage());
    }

    return suggestion;
}