Example usage for java.io UnsupportedEncodingException getMessage

List of usage examples for java.io UnsupportedEncodingException getMessage

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.redhat.rhn.frontend.xmlrpc.configchannel.XmlRpcConfigChannelHelper.java

/**
 * Creates a NEW path(file/directory) with the given path or updates an existing path
 * with the given contents in a given channel.
 * @param loggedInUser logged in user//from w  ww . ja  v a2 s . c  o  m
 * @param channel  the config channel who holds the file.
 * @param path the path of the given text file.
 * @param type the config file type
 * @param data a map containing properties pertaining to the given path..
 * for directory paths - 'data' will hold values for ->
 *  owner, group, permissions, revision, selinux_ctx
 * for file paths -  'data' will hold values for->
 *  contents, owner, group, permissions, selinux_ctx
 *      macro-start-delimiter, macro-end-delimiter, revision
 * for symlinks paths -  'data' will hold values for->
 *  target_path, revision, selinux_ctx
 * @return returns the new created or updated config revision..
 */

public ConfigRevision createOrUpdatePath(User loggedInUser, ConfigChannel channel, String path,
        ConfigFileType type, Map<String, Object> data) {
    ConfigFileData form;

    if (ConfigFileType.file().equals(type)) {
        try {
            if (BooleanUtils.isTrue((Boolean) data.get(ConfigRevisionSerializer.BINARY))) {
                byte[] content = Base64
                        .decodeBase64(((String) data.get(ConfigRevisionSerializer.CONTENTS)).getBytes("UTF-8"));

                if (content != null) {
                    form = new BinaryFileData(new ByteArrayInputStream(content), content.length);
                } else {
                    form = new BinaryFileData(new ByteArrayInputStream(new byte[0]), 0);
                }
            } else { // TEXT FILE
                String content;
                if (BooleanUtils.isTrue((Boolean) data.get(ConfigRevisionSerializer.CONTENTS_ENC64))) {
                    content = new String(
                            Base64.decodeBase64(
                                    ((String) data.get(ConfigRevisionSerializer.CONTENTS)).getBytes("UTF-8")),
                            "UTF-8");
                } else {
                    content = (String) data.get(ConfigRevisionSerializer.CONTENTS);
                }
                form = new TextFileData(content);
            }
        } catch (UnsupportedEncodingException e) {
            String msg = "Following errors were encountered " + "when creating the config file.\n"
                    + e.getMessage();
            throw new FaultException(1023, "ConfgFileError", msg);
        }
        String startDelim = (String) data.get(ConfigRevisionSerializer.MACRO_START);
        String stopDelim = (String) data.get(ConfigRevisionSerializer.MACRO_END);

        if (!StringUtils.isBlank(startDelim)) {
            form.setMacroStart(startDelim);
        }
        if (!StringUtils.isBlank(stopDelim)) {
            form.setMacroEnd(stopDelim);
        }
    } else if (ConfigFileType.symlink().equals(type)) {
        form = new SymlinkData((String) data.get(ConfigRevisionSerializer.TARGET_PATH));
    } else {
        form = new DirectoryData();
    }

    form.setPath(path);

    if (!ConfigFileType.symlink().equals(type)) {
        form.setOwner((String) data.get(ConfigRevisionSerializer.OWNER));
        form.setGroup((String) data.get(ConfigRevisionSerializer.GROUP));
        form.setPermissions((String) data.get(ConfigRevisionSerializer.PERMISSIONS));
    }
    String selinux = (String) data.get(ConfigRevisionSerializer.SELINUX_CTX);
    form.setSelinuxCtx(selinux == null ? "" : selinux);
    if (data.containsKey(ConfigRevisionSerializer.REVISION)) {
        form.setRevNumber(String.valueOf(data.get(ConfigRevisionSerializer.REVISION)));
    }

    ConfigFileBuilder helper = ConfigFileBuilder.getInstance();
    try {
        return helper.createOrUpdate(form, loggedInUser, channel);
    } catch (ValidatorException ve) {
        String msg = "Following errors were encountered " + "when creating the config file.\n"
                + ve.getMessage();
        throw new FaultException(1023, "ConfgFileError", msg);

    } catch (IOException ie) {
        String msg = "Error encountered when saving the config file. " + "Please retry. " + ie.getMessage();
        throw new FaultException(1024, "ConfgFileError", msg);
    }
}

From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java

public void execute() throws MojoExecutionException {
    this.getLog().info("Uploading project to BukkitDev");
    final String gameVersion = this.getGameVersion();
    final URIBuilder builder = new URIBuilder();
    final MultipartEntity entity = new MultipartEntity();
    HttpPost request;/*  w  w w .  j  a v  a 2  s. co  m*/

    // create the request
    builder.setScheme("http");
    builder.setHost("dev.bukkit.org");
    builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json");
    try {
        entity.addPart("file_type", new StringBody(this.getFileType()));
        entity.addPart("name", new StringBody(this.project.getArtifact().getVersion()));
        entity.addPart("game_versions", new StringBody(gameVersion));
        entity.addPart("change_log", new StringBody(this.changeLog));
        entity.addPart("known_caveats", new StringBody(this.knownCaveats));
        entity.addPart("change_markup_type", new StringBody(this.markupType));
        entity.addPart("caveats_markup_type", new StringBody(this.markupType));
        entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact())));
    } catch (final UnsupportedEncodingException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    // create the actual request
    try {
        request = new HttpPost(builder.build());
        request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0");
        request.setHeader("X-API-Key", this.key);
        request.setEntity(entity);
    } catch (final URISyntaxException exception) {
        throw new MojoExecutionException(exception.getMessage());
    }

    this.getLog().debug(request.toString());

    // send the request and handle any replies
    try {
        final HttpClient client = new DefaultHttpClient();
        final HttpResponse response = client.execute(request);
        switch (response.getStatusLine().getStatusCode()) {
        case 201:
            this.getLog().info("File uploaded successfully.");
            break;
        case 403:
            this.getLog().error(
                    "You have not specifed your API key correctly or do not have permission to upload to that project.");
            break;
        case 404:
            this.getLog().error("Project was not found. Either it is specified wrong or been renamed.");
            break;
        case 422:
            this.getLog().error("There was an error in uploading the plugin");
            this.getLog().debug(request.toString());
            this.getLog().debug(EntityUtils.toString(response.getEntity()));
            break;
        default:
            this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode());
            break;
        }
    } catch (final ClientProtocolException exception) {
        throw new MojoExecutionException(exception.getMessage());
    } catch (final IOException exception) {
        throw new MojoExecutionException(exception.getMessage());
    }

}

From source file:com.pl.plugins.commons.dal.utils.reports.JasperReportService.java

private JasperReport loadAndCompileReport(String reportTemplate) throws JRException, SystemException {
    String reportXML = getXMLTemplate(reportTemplate);

    if (reportXML == null) {
        throw new SystemException("Report not found: [" + reportTemplate + "]");
    }/*  ww w  .j  a  va  2s .co m*/

    try {
        JasperReport jasperReport;

        JasperDesign jd = JRXmlLoader.load(new ByteArrayInputStream(reportXML.getBytes("UTF-8")));
        jd.setWhenNoDataType(JasperDesign.WHEN_NO_DATA_TYPE_ALL_SECTIONS_NO_DETAIL);
        jasperReport = JasperCompileManager.compileReport(jd);
        return jasperReport;
    } catch (UnsupportedEncodingException e) {
        log.error(e);
        throw new SystemException(e.getMessage());
    }
}

From source file:edu.asu.msse.sgowdru.moviesqldb.SearchMovie.java

public void searchButtonClicked(View view) {
    String searchString = info[0].getText().toString();

    android.util.Log.w(getClass().getSimpleName(), searchString);
    try {/*www  . java  2  s.  c  om*/
        cur = crsDB.rawQuery("select Title from Movies where Title='" + searchString + "';", new String[] {});
        android.util.Log.w(getClass().getSimpleName(), searchString);

        //If the Movie Exists in the Local Database, we will retrieve it from the Local DB
        if (cur.getCount() != 0) {
            //Raise toast message that the movie is already present in local DB
            text = " already present in DB, Retrieving..";
            Toast toast = Toast.makeText(context, "Movie " + searchString + text, duration);
            toast.show();

            //Retrieving the Movie since we know that the movie exists in DB
            cur = crsDB.rawQuery("select Title, Genre, Years, Rated, Actors from Movies where Title = ?;",
                    new String[] { searchString });

            //Movie Already present hence disabling the Add Button
            btn.setEnabled(false);

            //Move the Cursor and set the Fields
            cur.moveToNext();
            info[1].setText(cur.getString(0));
            info[2].setText(cur.getString(1));
            info[3].setText(cur.getString(2));
            info[4].setText(cur.getString(4));

            //Set the Ratings dropdown
            if (cur.getString(3).equals("PG"))
                dropdown.setSelection(0);
            else if (cur.getString(3).equals("PG-13"))
                dropdown.setSelection(1);
            else if (cur.getString(3).equals("R"))
                dropdown.setSelection(2);
        }

        //If the Movie Does not exist in the Local Database, we will retrieve it from the OMDB
        else {
            //Movie not present in local DB, raise a toast message
            text = " being retrieved from OMDB now.";
            Toast toast = Toast.makeText(context, "Movie " + searchString + text, duration);
            toast.show();

            //Encode the search string to be appropriate to be placed in a url
            String encodedUrl = null;
            try {
                encodedUrl = URLEncoder.encode(searchString, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                android.util.Log.e(getClass().getSimpleName(), e.getMessage());
            }

            //ASync thread running the query from OMDB and retrieving the movie details as JSON
            JSONObject result = new MovieGetInfoAsync()
                    .execute("http://www.omdbapi.com/?t=\"" + encodedUrl + "\"&r=json").get();

            //Check if the Movie query was successful
            if (result.getString("Response").equals("True")) {
                info[1].setText(result.getString("Title"));
                info[2].setText(result.getString("Genre"));
                info[3].setText(result.getString("Year"));
                info[4].setText(result.getString("Actors"));

                //Ratings field is of type Spinner class with field values (PG, PG-13, R rated)
                ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Ratings,
                        android.R.layout.simple_spinner_item);
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dropdown.setAdapter(adapter);

                if (result.getString("Rated").equals("PG"))
                    dropdown.setSelection(0);
                else if (result.getString("Rated").equals("PG-13"))
                    dropdown.setSelection(1);
                else if (result.getString("Rated").equals("R"))
                    dropdown.setSelection(2);
            }
            //Search query was unsuccessful in getting movie with such a name
            else if (result.getString("Response").equals("False")) {
                //Raise a toast message
                text = " not present in OMDB, You can add it manually!";
                toast = Toast.makeText(context, "Movie " + searchString + text, duration);
                toast.show();
            }
        }
    } catch (Exception e) {
        android.util.Log.w(getClass().getSimpleName(), e.getMessage());
    }
}

From source file:com.gliffy.restunit.comparator.StrictMatchComparator.java

/** Given two differing bytestreams, and the content types attached to each, returns a string-based diff message that can help the
 * tester understand why the comparison failed.
 * @param expectedBody the body expected, will not be null (nulls from server get converted to empty arrays)
 * @param expectedContentType the content type expected by the test, or null if it wasn't specified
 * @param receivedBody the body received, will not be null (nulls from server get converted to empty arrays)
 * @param receivedContentType the content type received in the response, or null if it wasn't specified
 * @return a human-readable message explaining why the comparison failed.  This version checks to see if the expected content type is a text-based type.
 * If so, it attempts to convert the bytestreams to strings using the encodings specified in their content types.  If the expectedContentType has no encoding
 * the receivedContentType's encoding is used.  If no encodings were detected, the system default is used.  You should probably write your tests with encodings
 * because of this./*from  w  ww . j  a  v  a 2s  .  co  m*/
 */
protected String createDiffMessage(byte[] expectedBody, ContentType expectedContentType, byte[] receivedBody,
        ContentType receivedContentType) {
    String extra = "";
    if ((expectedContentType != null) && (expectedContentType.getMimeType().startsWith("text/"))) {
        itsLogger.debug("Expected content type was " + expectedContentType.getMimeType());
        String expectedEncoding = expectedContentType.getEncoding();
        String receivedEncoding = receivedContentType == null ? null : receivedContentType.getEncoding();
        if (expectedEncoding == null)
            expectedEncoding = receivedEncoding;

        try {
            String expected = null;
            String received = null;
            String expectedEncodingDesc = DEFAULT_ENCODING_DESC;
            String receivedEncodingDesc = DEFAULT_ENCODING_DESC;
            if (expectedEncoding == null) {
                expected = new String(expectedBody);
            } else {
                expectedEncodingDesc = expectedEncoding;
                expected = new String(expectedBody, expectedEncoding);
            }

            if (receivedEncoding == null) {
                received = new String(receivedBody);
            } else {
                received = new String(receivedBody, receivedEncoding);
                receivedEncodingDesc = receivedEncoding;
            }
            return MessageFormat.format(
                    "Bodies didn't match; expected (using encoding {0}):\n'{1}'\nreceived (using encoding {2}):\n'{3}'",
                    expectedEncodingDesc, expected, receivedEncodingDesc, received);
        } catch (UnsupportedEncodingException e) {
            itsLogger.warn("Coding " + expectedEncoding + " or " + receivedEncoding + " was not supported", e);
            extra = " (while attempting to output data in string format: " + e.getMessage() + ")";
        }
    } else {
        itsLogger.debug("Expected Content-Type was "
                + (expectedContentType == null ? "not specified" : expectedContentType.getMimeType()));
    }
    return "Bodies didn't match" + extra;
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

private static void parseSignedDoc(List<XMLObject> attributeValues, String nameSpace, String prefix,
        String value) {//from  www.j  a  v  a  2  s . c  o m
    DocumentBuilderFactory domFactory = EIDASSAMLEngine.newDocumentBuilderFactory();
    domFactory.setNamespaceAware(true);
    Document document = null;
    DocumentBuilder builder;

    // Parse the signedDoc value into an XML DOM Document
    try {
        builder = domFactory.newDocumentBuilder();
        InputStream is;
        is = new ByteArrayInputStream(value.trim().getBytes("UTF-8"));
        document = builder.parse(is);
        is.close();
    } catch (SAXException e1) {
        LOG.info("ERROR : SAX Error while parsing signModule attribute", e1.getMessage());
        LOG.debug("ERROR : SAX Error while parsing signModule attribute", e1);
        throw new EIDASSAMLEngineRuntimeException(e1);
    } catch (ParserConfigurationException e2) {
        LOG.info("ERROR : Parser Configuration Error while parsing signModule attribute", e2.getMessage());
        LOG.debug("ERROR : Parser Configuration Error while parsing signModule attribute", e2);
        throw new EIDASSAMLEngineRuntimeException(e2);
    } catch (UnsupportedEncodingException e3) {
        LOG.info("ERROR : Unsupported encoding Error while parsing signModule attribute", e3.getMessage());
        LOG.debug("ERROR : Unsupported encoding Error while parsing signModule attribute", e3);
        throw new EIDASSAMLEngineRuntimeException(e3);
    } catch (IOException e4) {
        LOG.info("ERROR : IO Error while parsing signModule attribute", e4.getMessage());
        LOG.debug("ERROR : IO Error while parsing signModule attribute", e4);
        throw new EIDASSAMLEngineRuntimeException(e4);
    }

    // Create the XML statement(this will be overwritten with the previous DOM structure)
    final XSAny xmlValue = (XSAny) SAMLEngineUtils.createSamlObject(new QName(nameSpace, "XMLValue", prefix),
            XSAny.TYPE_NAME);

    //Set the signedDoc XML content to this element
    xmlValue.setDOM(document.getDocumentElement());

    // Create the attribute statement
    final XSAny attrValue = (XSAny) SAMLEngineUtils
            .createSamlObject(new QName(nameSpace, "AttributeValue", prefix), XSAny.TYPE_NAME);

    //Add previous signedDocXML to the AttributeValue Element
    attrValue.getUnknownXMLObjects().add(xmlValue);

    attributeValues.add(attrValue);
}

From source file:com.wso2telco.gsma.authenticators.extension.CustomRequestCoordinator.java

private String getCallerPath(HttpServletRequest request) throws FrameworkException {
    String callerPath = request.getParameter(FrameworkConstants.RequestParams.CALLER_PATH);
    try {/*w w w  . j a  va2  s.  c om*/
        if (callerPath != null) {
            callerPath = URLDecoder.decode(callerPath, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        throw new FrameworkException(e.getMessage(), e);
    }
    return callerPath;
}

From source file:fr.paris.lutece.portal.web.search.SearchApp.java

/**
 * Returns search results/* w  ww.j  a  v  a  2  s.  c om*/
 *
 * @param request The HTTP request.
 * @param nMode The current mode.
 * @param plugin The plugin
 * @return The HTML code of the page.
 * @throws SiteMessageException If an error occurs
 */
@Override
public XPage getPage(HttpServletRequest request, int nMode, Plugin plugin) throws SiteMessageException {
    XPage page = new XPage();
    String strQuery = request.getParameter(PARAMETER_QUERY);
    String strTagFilter = request.getParameter(PARAMETER_TAG_FILTER);

    String strEncoding = AppPropertiesService.getProperty(PROPERTY_ENCODE_URI_ENCODING, DEFAULT_URI_ENCODING);

    if (StringUtils.equalsIgnoreCase(CONSTANT_HTTP_METHOD_GET, request.getMethod())
            && !StringUtils.equalsIgnoreCase(strEncoding, CONSTANT_ENCODING_UTF8)) {
        try {
            if (StringUtils.isNotBlank(strQuery)) {
                strQuery = new String(strQuery.getBytes(strEncoding), CONSTANT_ENCODING_UTF8);
            }

            if (StringUtils.isNotBlank(strTagFilter)) {
                strTagFilter = new String(strTagFilter.getBytes(strEncoding), CONSTANT_ENCODING_UTF8);
            }
        } catch (UnsupportedEncodingException e) {
            AppLogService.error(e.getMessage(), e);
        }
    }

    if (StringUtils.isNotEmpty(strTagFilter)) {
        strQuery = strTagFilter;
    }

    boolean bEncodeUri = Boolean.parseBoolean(
            AppPropertiesService.getProperty(PROPERTY_ENCODE_URI, Boolean.toString(DEFAULT_ENCODE_URI)));

    String strSearchPageUrl = AppPropertiesService.getProperty(PROPERTY_SEARCH_PAGE_URL);
    String strError = "";
    Locale locale = request.getLocale();

    // Check XSS characters
    if ((strQuery != null) && (SecurityUtil.containsXssCharacters(request, strQuery))) {
        strError = I18nService.getLocalizedString(MESSAGE_INVALID_SEARCH_TERMS, locale);
        strQuery = "";
    }

    String strNbItemPerPage = request.getParameter(PARAMETER_NB_ITEMS_PER_PAGE);
    String strDefaultNbItemPerPage = AppPropertiesService.getProperty(PROPERTY_RESULTS_PER_PAGE,
            DEFAULT_RESULTS_PER_PAGE);
    strNbItemPerPage = (strNbItemPerPage != null) ? strNbItemPerPage : strDefaultNbItemPerPage;

    int nNbItemsPerPage = Integer.parseInt(strNbItemPerPage);
    String strCurrentPageIndex = request.getParameter(PARAMETER_PAGE_INDEX);
    strCurrentPageIndex = (strCurrentPageIndex != null) ? strCurrentPageIndex : DEFAULT_PAGE_INDEX;

    SearchEngine engine = (SearchEngine) SpringContextService.getBean(BEAN_SEARCH_ENGINE);
    List<SearchResult> listResults = engine.getSearchResults(strQuery, request);

    // The page should not be added to the cache

    // Notify results infos to QueryEventListeners 
    notifyQueryListeners(strQuery, listResults.size(), request);

    UrlItem url = new UrlItem(strSearchPageUrl);
    String strQueryForPaginator = strQuery;

    if (bEncodeUri) {
        strQueryForPaginator = encodeUrl(request, strQuery);
    }

    if (StringUtils.isNotBlank(strTagFilter)) {
        strQuery = "";
    }

    url.addParameter(PARAMETER_QUERY, strQueryForPaginator);
    url.addParameter(PARAMETER_NB_ITEMS_PER_PAGE, nNbItemsPerPage);

    Paginator<SearchResult> paginator = new Paginator<SearchResult>(listResults, nNbItemsPerPage, url.getUrl(),
            PARAMETER_PAGE_INDEX, strCurrentPageIndex);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_RESULTS_LIST, paginator.getPageItems());
    model.put(MARK_QUERY, strQuery);
    model.put(MARK_PAGINATOR, paginator);
    model.put(MARK_NB_ITEMS_PER_PAGE, strNbItemPerPage);
    model.put(MARK_ERROR, strError);

    ISponsoredLinksSearchService sponsoredLinksService = new SponsoredLinksSearchService();

    if (sponsoredLinksService.isAvailable()) {
        model.put(MARK_SPONSOREDLINKS_SET, sponsoredLinksService.getHtmlCode(strQuery, locale));
    }

    model.put(MARK_LIST_TYPE_AND_LINK, SearchService.getSearchTypesAndLinks());
    model.putAll(SearchParameterHome.findAll());

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_RESULTS, locale, model);

    page.setPathLabel(I18nService.getLocalizedString(PROPERTY_PATH_LABEL, locale));
    page.setTitle(I18nService.getLocalizedString(PROPERTY_PAGE_TITLE, locale));
    page.setContent(template.getHtml());

    return page;
}

From source file:ti.modules.titanium.geolocation.TiLocation.java

private String buildGeocoderURL(String direction, String mid, String aguid, String sid, String query,
        String countryCode) {// w  w w .  j  a va2s  .  com
    String url = null;

    try {
        StringBuilder sb = new StringBuilder();
        sb.append(BASE_GEO_URL).append("d=r").append("&mid=").append(mid).append("&aguid=").append(aguid)
                .append("&sid=").append(sid).append("&q=").append(URLEncoder.encode(query, "utf-8"));

        url = sb.toString();

    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "Unable to encode query to utf-8: " + e.getMessage());
    }

    return url;
}

From source file:com.sitexa.android.data.net.volley.VolleyApi.java

private String getGetMethodParams(Map<String, String> params) {
    if (params != null && params.size() > 0) {
        try {/*from  w w  w  .jav a 2 s . co m*/
            StringBuffer actionUrl = new StringBuffer();
            actionUrl.append("?");
            for (String key : params.keySet()) {
                actionUrl.append(key).append("=").append(URLEncoder.encode(params.get(key), "utf-8"))
                        .append("&");
            }
            return actionUrl.toString();
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
    return "";
}