Example usage for java.io UnsupportedEncodingException toString

List of usage examples for java.io UnsupportedEncodingException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

/**
 * @throws UnsupportedEncodingException/*from   w w w  .  j av a  2  s  .  co m*/
 * @see de.ingrid.portal.interfaces.WMSInterface#getWMSAddedServiceURL(java.util.ArrayList,
 *      java.lang.String)
 */
public String getWMSAddedServiceURL(List services, String sessionId, boolean jsEnabled, Locale language,
        boolean isViewer) {
    WMSServiceDescriptor service;
    String serviceURL;
    String serviceName;
    StringBuffer resultB;
    if (isViewer) {
        resultB = new StringBuffer(getWMSViewerURL(sessionId, jsEnabled, language));
    } else {
        resultB = new StringBuffer(this.getWMSSearchURL(sessionId, jsEnabled, language));
    }
    boolean prequestAdded = false;

    // check for invalid service parameter
    if (services == null || services.size() == 0) {
        return resultB.toString();
    }

    try {
        // add services
        for (int i = 0; i < services.size(); i++) {
            service = (WMSServiceDescriptor) services.get(i);
            serviceURL = service.getUrl();
            serviceName = service.getName();
            if (serviceURL != null && serviceURL.length() > 0) {
                if (!prequestAdded) {
                    if (mapBenderVersion.equals(MAPBENDER_VERSION_2_1)) {
                        resultB.append("&PREQUEST=setServices");
                    } else {
                        resultB.append("&COMMAND=addWMS");
                    }
                    prequestAdded = true;
                }
                if (serviceName != null && serviceName.length() > 0) {
                    resultB.append("&wmsName" + (i + 1) + "=" + URLEncoder.encode(serviceName, "UTF-8"));
                }
                if (mapBenderVersion.equals(MAPBENDER_VERSION_2_1)) {
                    serviceURL.replace('&', ',');
                }
                resultB.append("&wms" + (i + 1) + "=" + URLEncoder.encode(serviceURL, "UTF-8")
                        + "&addwms_zoomToExtent=1&addwms_showWMS=10");

            }
        }
    } catch (UnsupportedEncodingException e) {
        log.error(e.toString());
    }

    return resultB.toString();
}

From source file:org.transdroid.daemon.Qbittorrent.QbittorrentAdapter.java

private String makeRequest(Log log, String path, NameValuePair... params) throws DaemonException {

    try {/*w w  w .ja v a  2 s  .  c om*/

        // Setup request using POST
        HttpPost httppost = new HttpPost(buildWebUIUrl(path));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Collections.addAll(nvps, params);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        return makeWebRequest(httppost, log);

    } catch (UnsupportedEncodingException e) {
        throw new DaemonException(ExceptionType.ConnectionError, e.toString());
    }

}

From source file:org.etudes.util.XrefHelper.java

/**
 * Translate the resource's body html with the translations. Optionally shorten full URLs.
 * //www  .j  av  a  2 s. com
 * @param ref
 *        The resource reference.
 * @param translations
 *        The complete set of translations.
 * @param context
 *        The context.
 * @param shortenUrls
 *        if true, full references to resources on this server are shortened.
 */
public static void translateHtmlBody(Reference ref, Collection<Translation> translations, String context,
        boolean shortenUrls) {
    // ref is the destination ("to" in the translations) resource - we need the "parent ref" from the source ("from" in the translations) resource
    String parentRef = ref.getReference();
    for (Translation translation : translations) {
        parentRef = translation.reverseTranslate(parentRef);
    }

    // bypass security when reading the resource to copy
    SecurityService.pushAdvisor(new SecurityAdvisor() {
        public SecurityAdvice isAllowed(String userId, String function, String reference) {
            return SecurityAdvice.ALLOWED;
        }
    });

    try {
        // Reference does not know how to make the id from a private docs reference.
        String id = ref.getId();
        if (id.startsWith("/content/")) {
            id = id.substring("/content".length());
        }

        // get the resource
        ContentResource resource = ContentHostingService.getResource(id);
        String type = resource.getContentType();

        // translate if we are html
        if (type.equals("text/html")) {
            byte[] body = resource.getContent();
            if (body != null) {
                String bodyString = new String(body, "UTF-8");

                String translated = null;
                if (shortenUrls) {
                    translated = translateEmbeddedReferencesAndShorten(bodyString, translations, context,
                            parentRef);
                } else {
                    translated = translateEmbeddedReferences(bodyString, translations, context, parentRef);
                }
                body = translated.getBytes("UTF-8");

                ContentResourceEdit edit = ContentHostingService.editResource(resource.getId());
                edit.setContent(body);
                ContentHostingService.commitResource(edit, 0);
            }
        }
    } catch (UnsupportedEncodingException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (PermissionException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (IdUnusedException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (TypeException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (ServerOverloadException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (InUseException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (OverQuotaException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } finally {
        SecurityService.popAdvisor();
    }
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@Override
public Person lookupPerson(String personId) {
    Person person = null;/*from   www  .ja va  2  s . c o m*/

    BufferedReader reader = null;
    try {
        URL service = new URL(PERSON_LOOKUP_URL + personId);
        LOG.debug("Personlookupurl :" + PERSON_LOOKUP_URL + personId);

        String jsonData = null;
        jsonData = IOUtils.toString(service, DEFAULT_CHARACTER_SET);

        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;
        JSONObject jsonPerson = (JSONObject) jsonObject.get("person");

        if (jsonPerson == null) {
            LOG.debug("Results were not parsed, " + personId + " not found.");
        } else if (jsonPerson.containsKey("errors") && jsonPerson.get("errors") != null
                && jsonPerson.get("errors").hashCode() != 0) {
            // TODO get error description
            // Object v = raw.get("errors");
            LOG.debug("errors:" + jsonPerson.get("errors"));
        } else {
            person = parsePerson(jsonPerson);
        }

    } catch (UnsupportedEncodingException uee) {
        LOG.error(uee.toString());
    } catch (IOException ioe) {
        LOG.error(ioe.toString());
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException logOrIgnore) {
                LOG.error(logOrIgnore.getLocalizedMessage());
            }
        }
    }
    return person;
}

From source file:org.etudes.util.XrefHelper.java

@SuppressWarnings("unchecked")
public static void translateUrl(Reference ref, Collection<Translation> translations, String context,
        boolean shortenUrls) {
    // ref is the destination ("to" in the translations) resource - we need the "parent ref" from the source ("from" in the translations) resource
    String parentRef = ref.getReference();
    for (Translation translation : translations) {
        parentRef = translation.reverseTranslate(parentRef);
    }// w w w . jav a  2 s  .  c o  m

    // get our thread-local list of translations made in this thread (if any)
    List<Translation> threadTranslations = (List<Translation>) ThreadLocalManager.get(THREAD_TRANSLATIONS_KEY);

    // bypass security when reading the resource to copy
    SecurityService.pushAdvisor(new SecurityAdvisor() {
        public SecurityAdvice isAllowed(String userId, String function, String reference) {
            return SecurityAdvice.ALLOWED;
        }
    });

    try {
        // Reference does not know how to make the id from a private docs reference.
        String id = ref.getId();
        if (id.startsWith("/content/")) {
            id = id.substring("/content".length());
        }

        // get the resource
        ContentResource resource = ContentHostingService.getResource(id);
        String type = resource.getContentType();

        // translate if we are url
        if (type.equals("text/url")) {
            byte[] body = resource.getContent();
            if (body != null) {
                String bodyString = new String(body, "UTF-8");

                // expand to a full reference if relative
                bodyString = adjustRelativeReference(bodyString, parentRef);

                // harvest any content hosting reference
                int index = indexContentReference(bodyString);
                if (index != -1) {
                    // except those we don't want to harvest
                    if (exception(bodyString, context))
                        index = -1;
                }

                if (index != -1) {
                    // translate just the reference part (i.e. after the /access);
                    String normal = bodyString.substring(index + 7);

                    // deal with %20, &amp;, and other encoded URL stuff
                    normal = decodeUrl(normal);

                    // translate the normal form
                    String translated = normal;
                    for (Translation translation : translations) {
                        translated = translation.translate(translated);
                    }

                    // also translate with our global list
                    if (threadTranslations != null) {
                        for (Translation translation : threadTranslations) {
                            translated = translation.translate(translated);
                        }
                    }

                    // if changed, replace
                    if (!normal.equals(translated)) {
                        // URL encode translated
                        bodyString = escapeUrl("/access/" + translated);
                        body = bodyString.getBytes("UTF-8");

                        ContentResourceEdit edit = ContentHostingService.editResource(resource.getId());
                        edit.setContent(body);
                        ContentHostingService.commitResource(edit, 0);
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (PermissionException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (IdUnusedException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (TypeException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (ServerOverloadException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (InUseException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } catch (OverQuotaException e) {
        M_log.warn("translateHtmlBody: " + e.toString());
    } finally {
        SecurityService.popAdvisor();
    }
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

public void collect() {
    if (isPingCompat.get()) {
        // back compat w/ old url.availability templates
        super.collect();
        return;/* w  ww  .  jav  a  2  s . co m*/
    }
    this.matches.clear();
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert());
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    double avail = 0;
    try {
        if (getMethod().equals(HttpHead.METHOD_NAME)) {
            request = new HttpHead(getURL());
            addParams(request, this.params.get());
        } else if (getMethod().equals(HttpPost.METHOD_NAME)) {
            HttpPost httpPost = new HttpPost(getURL());
            request = httpPost;
            addParams(httpPost, this.params.get());
        } else {
            request = new HttpGet(getURL());
            addParams(request, this.params.get());
        }
        request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow());
        addCredentials(request, client);
        startTime();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        int tries = 0;
        while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) {
            tries++;
            Header header = response.getFirstHeader("Location");
            String url = header.getValue();
            String[] toks = url.split(";");
            String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0];
            response = getRedirect(toks[0], t.length > 1 ? t[1] : "");
            statusCode = response.getStatusLine().getStatusCode();
        }
        endTime();
        setResponseCode(statusCode);
        avail = getAvail(statusCode);
        StringBuilder msg = new StringBuilder(String.valueOf(statusCode));
        Header header = response.getFirstHeader("Server");
        msg.append(header != null ? " (" + header.getValue() + ")" : "");
        setLastModified(response, statusCode);
        avail = checkPattern(response, avail, msg);
        setAvailMsg(avail, msg);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding: " + e, e);
    } catch (IOException e) {
        avail = Metric.AVAIL_DOWN;
        setErrorMessage(e.toString());
    } finally {
        setAvailability(avail);
    }
    netstat();
}

From source file:com.google.wave.splash.auth.oauth.OAuthRequestFactory.java

@Override
public ListenableFuture<String> makeSignedRequest(String body) {
    SessionContext session = sessionProvider.get();
    InputStream bodyStream;/*w ww  .  j  av  a2 s . c o m*/
    try {
        bodyStream = new ByteArrayInputStream(body.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }

    String result = null;
    try {
        InputStream output;
        if (session.isAuthenticated()) {
            output = getSignedResult(session, bodyStream);
        } else {
            output = getUnsignedResult(body, bodyStream);
        }
        result = CharStreams.toString(new InputStreamReader(output, HttpMessage.DEFAULT_CHARSET));
    } catch (URISyntaxException e) {
        LOG.warning(e.toString());
    } catch (OAuthException e) {
        LOG.warning(e.toString());
    } catch (IOException e) {
        LOG.severe(e.toString());
    }
    return Futures.immediateFuture(result);
}

From source file:com.webber.webber.client.NetworkUtilities.java

/**
 * Connects to the webber server, authenticates the provided
 * username and password.//from w w  w. j  a va 2  s.c  om
 *
 * @param username The server account username
 * @param password The server account password
 * @return String The authentication token returned by the server (or null)
 */
public static WebberAccount authenticate(String username, String password) {

    final HttpResponse resp;
    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    final HttpEntity entity;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new IllegalStateException(e);
    }
    Log.i(TAG, "Authenticating to: " + AUTH_URI);
    final HttpPost post = new HttpPost(AUTH_URI);
    post.addHeader(entity.getContentType());
    post.setEntity(entity);
    try {
        resp = getHttpClient().execute(post);
        String strResult = EntityUtils.toString(resp.getEntity());

        Log.v(TAG, strResult);

        JSONObject userObject = new JSONObject(strResult);
        boolean valid = userObject.getBoolean("valid");
        String uid = null;
        String realname = null;
        String authToken = null;
        if (valid) {
            WebberAccount wa = new WebberAccount();
            wa.uid = userObject.getString("uid");
            wa.realname = userObject.getString("realname");
            wa.authToken = userObject.getString("authToken");

            if ((wa.authToken != null) && (wa.authToken.length() > 0)) {
                Log.v(TAG, "Successful authentication");
                return wa;
            }
        } else {
            Log.e(TAG, "Error authenticating" + resp.getStatusLine());
            return null;
        }
    } catch (final ClientProtocolException e) {
        // TODO Auto-generated catch block
        Log.v(TAG, e.toString());
    } catch (final IOException e) {
        Log.e(TAG, "IOException when getting authtoken", e);
        return null;
    } catch (final JSONException e) {
        Log.v(TAG, e.toString());
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }

    return null;
}

From source file:com.procleus.brime.utils.JSONParser.java

public JSONObject getJSONFromUrl(String url) {

    try {/*from   w w w  . j  a  v  a  2 s.  c  o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;
}