Example usage for java.io UnsupportedEncodingException getLocalizedMessage

List of usage examples for java.io UnsupportedEncodingException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:com.microsoft.rightsmanagement.sampleapp.MainActivity.java

@Override
public void onSendMailButtonClick() {
    byte[] rawData = null;
    try {//  w w w .ja v  a 2  s.  c om
        rawData = mTextEditorFragment.getTextViewText().getBytes("UTF-8");
        if (mTextEditorFragment.getUsePxtFileFormat()) {
            mMsipcTaskFragment.startContentProtectionToPtxtFileFormat(rawData);
        } else {
            mMsipcTaskFragment.startContentProtectionToMyOwnProtectedTextFileFormat(rawData);
        }
    } catch (UnsupportedEncodingException e) {
        App.displayMessageDialog(getSupportFragmentManager(), e.getLocalizedMessage());
    }
}

From source file:talend.ext.images.server.ImageUploadServlet.java

private Object getFileItem(List<FileItem> fileItems, String fieldName) {

    for (FileItem item : fileItems) {
        String name = item.getFieldName();
        if (StringUtils.isNotEmpty(name) && name.equals(fieldName)) {

            if (item.isFormField()) {
                String value = ""; //$NON-NLS-1$

                try {
                    value = new String(item.getString("UTF-8")); //$NON-NLS-1$
                } catch (UnsupportedEncodingException e) {
                    logger.error(e.getLocalizedMessage(), e);
                }//  w w w. j av  a  2  s .c om

                return value;
            } else {

                return item;

            }

        }

    }
    return null;
}

From source file:org.eclipse.smarthome.binding.openweathermap.internal.connection.OpenWeatherMapConnection.java

private String encodeParam(String value) {
    try {//w  w w.j a  v  a 2 s . co m
        return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        logger.debug("UnsupportedEncodingException occurred during execution: {}", e.getLocalizedMessage(), e);
        return StringUtils.EMPTY;
    }
}

From source file:com.ibm.mil.LoyaltyUserAdapterResource.java

/**
 * Retrieve the Watson personality insights for a user. You would normally
 * take a users Twitter feed and supply it to the Watson personality
 * insights service and leverage the results to make informed decisions
 * about what types of offers to make to the user based on their
 * personality./*from   w w  w  . j  a  va2s.  co  m*/
 * 
 * For this simple application we are hard coding the "Twitter feed" that we
 * are suppling the Watson service and are NOT using the results to generate
 * the custom offers we provide for the user as this logic would be very
 * specific to the industry the application is rolled into and the specific
 * business owners needs.
 * 
 * @return The Watson personality insights response as a JSON string.
 */
@GET
@Path("/watson-data")
@Produces(MediaType.APPLICATION_JSON)
public Response getUserWatsonData() {
    // log message to server log
    logger.info(messages.getMessage("MSG0006"));

    Response srvrResponse;
    try {
        HttpPost httpPost = getHttpPost();
        String result = execute(httpPost);

        srvrResponse = Response.ok(result, MediaType.APPLICATION_JSON).build();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        srvrResponse = Response.serverError().entity(
                messages.getMessage("MSG0005") + System.getProperty("line.separator") + e.getLocalizedMessage())
                .build();
    } catch (Exception ex) {
        ex.printStackTrace();
        srvrResponse = Response.serverError().entity(ex.getLocalizedMessage()).build();
    }
    return srvrResponse;
}

From source file:net.oauth.consumer.OAuth2Consumer.java

public String generateRequestAuthorizationUrl(ResponseType responseType, String redirectUri, String state,
        String scopeDelimiter, String... scope) throws OAuthException {
    if (serviceProvider == null) {
        throw new OAuthException(ERROR_NO_SERVICE_PROVIDER);
    }//from  w  ww  .  j a  v  a  2s. co m

    if (responseType == null) {
        throw new OAuthException(
                "REQUIRED - Expected one of these response_type: \"token\", \"code\" OR \"code_and_token\". See "
                        + ResponseType.class.getName());
    }

    if (redirectUri == null || redirectUri.isEmpty()) {
        throw new OAuthException(ERROR_NO_REDIRECT_URI);
    }

    StringBuffer sb = new StringBuffer();

    try {
        sb.append(serviceProvider.getAuthorizationUrl());
        if (serviceProvider.getAuthorizationUrl().indexOf('?') > -1) {
            sb.append('&');
        } else {
            sb.append('?');
        }
        sb.append("response_type=" + URLEncoder.encode(responseType.toString(), URL_ENCODING));

        sb.append('&');
        sb.append(OAuth2Parameters.CLIENT_ID + "=" + URLEncoder.encode(clientID, URL_ENCODING));

        sb.append('&');
        sb.append(OAuth2Parameters.REDIRECT_URI + "=" + URLEncoder.encode(redirectUri, URL_ENCODING));

        if (scope != null && scope.length > 0) {
            sb.append('&');
            sb.append(OAuth2Parameters.SCOPE + "=" + encodeScope(scope, scopeDelimiter));
        }

        if (state != null && !state.isEmpty()) {
            sb.append('&');
            sb.append("state=" + URLEncoder.encode(state, URL_ENCODING));
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        logger.error(e.getLocalizedMessage(), e);
        throw new OAuthException("Encoding Exception:", e);
    }

    return sb.toString();
}

From source file:org.opencms.report.CmsVaadinHtmlReport.java

/**
 * Constructs a new report using the provided locale for the output language.<p>
 *
 * @param locale the locale to use for the output language
 * @param siteRoot the site root of the user who started this report (may be <code>null</code>)
 * @param writeHtml if <code>true</code>, this report should generate HTML instead of JavaScript output
 * @param isTransient If set to <code>true</code> nothing is kept in memory
 * @param logChannel the log channel to send the report output to (or null if this shouldn't be done)
 *//*  ww w .j a v  a  2 s  .c  om*/
public CmsVaadinHtmlReport(Locale locale, String siteRoot, boolean writeHtml, boolean isTransient,
        Object logChannel) {

    init(locale, siteRoot);
    if (logChannel != null) {
        m_logReport = new CmsLogReport(locale, logChannel);
    }
    m_content = new ArrayList<Object>(256);
    m_writeHtml = writeHtml;
    m_transient = isTransient;
    try (InputStream stream = CmsVaadinHtmlReport.class.getResourceAsStream("report.st")) {
        try {
            m_templateGroup = new StringTemplateGroup(new InputStreamReader(stream, "UTF-8"),
                    DefaultTemplateLexer.class, new StringTemplateErrorListener() {

                        @SuppressWarnings("synthetic-access")
                        public void error(String arg0, Throwable arg1) {

                            LOG.error(arg0 + ": " + arg1.getMessage(), arg1);
                        }

                        @SuppressWarnings("synthetic-access")
                        public void warning(String arg0) {

                            LOG.warn(arg0);

                        }
                    });
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (IOException e) {
        LOG.error(e.getLocalizedMessage(), e);
    }
}

From source file:net.oauth.consumer.OAuth2Consumer.java

public String generateRequestAcessTokenUrl(GrantType grantType, OAuth2Parameters parameters,
        String scopeDelimiter, String... scope) throws OAuthException {
    if (serviceProvider == null) {
        throw new OAuthException(ERROR_NO_SERVICE_PROVIDER);
    }//ww  w .ja  v a2  s. c  om

    if (grantType == null) {
        throw new OAuthException(
                "REQUIRED - Expected one of these grant_type: \"authorization_code\", \"password\", \"assertion\", \"refresh_token\" OR \"none\". See net.oauth.enums.GrantType");
    }

    if (parameters.isEmpty()) {
        if (grantType != GrantType.NONE) {
            throw new OAuthException("No OAuth 2 required parameters are provided for grant_type '"
                    + grantType.toString() + "' . Cannot continue request.");
        }
    }

    if (grantType == GrantType.AUTHORIZATION_CODE) {
        if (parameters.getCode() == null || parameters.getRedirectUri() == null) {
            throw new OAuthException("REQUIRED: BOTH \"" + OAuth2Parameters.CODE + "\" and \""
                    + OAuth2Parameters.REDIRECT_URI + "\".");
        }
    } else if (grantType == GrantType.PASSWORD) {
        if (parameters.getUserName() == null || parameters.getPassword() == null) {
            throw new OAuthException("REQUIRED: BOTH \"" + OAuth2Parameters.USERNAME + "\" and \""
                    + OAuth2Parameters.PASSWORD + "\".");
        }
    } else if (grantType == GrantType.ASSERTION) {
        if (parameters.getAssertionType() == null || parameters.getAssertion() == null) {
            throw new OAuthException("REQUIRED: BOTH \"" + OAuth2Parameters.ASSERTION_TYPE + "\" and \""
                    + OAuth2Parameters.ASSERTION + "\".");
        }
    } else if (grantType == GrantType.REFRESH_TOKEN) {
        if (parameters.getRefreshToken() == null) {
            throw new OAuthException("REQUIRED: \"" + OAuth2Parameters.REFRESH_TOKEN + "\".");
        }
    }

    parameters.addParameterValue("grant_type", grantType.toString());
    parameters.addParameterValue(OAuth2Parameters.CLIENT_ID, clientID);
    parameters.addParameterValue("client_secret", clientSecret);

    String serverUrl = null;
    try {
        StringBuffer sb = new StringBuffer();
        for (String parameter : parameters.getParameterNames()) {
            if (sb.length() > 0)
                sb.append('&');

            sb.append(URLEncoder.encode(parameter, URL_ENCODING) + "="
                    + URLEncoder.encode(parameters.getParameterValue(parameter), URL_ENCODING));
        }

        //Scope
        if (scope != null && scope.length > 0) {
            sb.append('&');
            sb.append(OAuth2Parameters.SCOPE + "=" + encodeScope(scope, scopeDelimiter));
        }

        serverUrl = serviceProvider.getAccessTokenUrl();
        if (serviceProvider.getAuthorizationUrl().indexOf('?') > -1) {
            serverUrl += "&";
        } else {
            serverUrl += "?";
        }

        serverUrl += sb.toString();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        logger.error(e.getLocalizedMessage(), e);
    }

    return serverUrl;
}

From source file:org.apache.jmeter.protocol.http.sampler.SoapSampler.java

/**
 * Send POST data from <code>Entry</code> to the open connection.
 *
 * @param post POST request to send// w w w  .j a v  a 2 s  . co  m
 * @param length the length of the content
 */
private String sendPostData(PostMethod post, final int length) {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    final String xmlFile = getXmlFile();
    if (xmlFile != null && xmlFile.length() > 0) {
        File xmlFileAsFile = new File(xmlFile);
        if (!(xmlFileAsFile.exists() && xmlFileAsFile.canRead())) {
            throw new IllegalArgumentException(JMeterUtils.getResString("soap_sampler_file_invalid") // $NON-NLS-1$
                    + xmlFileAsFile.getAbsolutePath());
        }
        // We just add placeholder text for file content
        postedBody.append("Filename: ").append(xmlFile).append("\n");
        postedBody.append("<actual file content, not shown here>");
        post.setRequestEntity(new RequestEntity() {
            @Override
            public boolean isRepeatable() {
                return true;
            }

            @Override
            public void writeRequest(OutputStream out) throws IOException {
                InputStream in = null;
                try {
                    in = new BufferedInputStream(new FileInputStream(xmlFile));
                    IOUtils.copy(in, out);
                    out.flush();
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }

            @Override
            public long getContentLength() {
                switch (length) {
                case -1:
                    return -1;
                case 0: // No header provided
                    return new File(xmlFile).length();
                default:
                    return length;
                }
            }

            @Override
            public String getContentType() {
                // TODO do we need to add a charset for the file contents?
                return DEFAULT_CONTENT_TYPE; // $NON-NLS-1$
            }
        });
    } else {
        postedBody.append(getXmlData());
        post.setRequestEntity(new RequestEntity() {
            @Override
            public boolean isRepeatable() {
                return true;
            }

            @Override
            public void writeRequest(OutputStream out) throws IOException {
                // charset must agree with content-type below
                IOUtils.write(getXmlData(), out, ENCODING); // $NON-NLS-1$
                out.flush();
            }

            @Override
            public long getContentLength() {
                try {
                    return getXmlData().getBytes(ENCODING).length; // so we don't generate chunked encoding
                } catch (UnsupportedEncodingException e) {
                    log.warn(e.getLocalizedMessage());
                    return -1; // will use chunked encoding
                }
            }

            @Override
            public String getContentType() {
                return DEFAULT_CONTENT_TYPE + "; charset=" + ENCODING; // $NON-NLS-1$
            }
        });
    }
    return postedBody.toString();
}

From source file:com.hybris.mobile.Hybris.java

public void setUuid(Context context) {
    final String uuid = Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_UUID);
    UUID unique_uid;//from   w w  w .j  a  v a 2 s .c  o  m
    if (uuid.isEmpty()) {
        final String id = Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_DEVICE_ID);
        if (!id.isEmpty()) {
            // Use the ids previously computed and stored in the prefs file
            try {
                unique_uid = UUID.nameUUIDFromBytes(id.getBytes("utf8"));
            } catch (UnsupportedEncodingException e) {
                LoggingUtils.e(LOG_TAG, "Error creating UUID " + e.getLocalizedMessage(), getAppContext());
                throw new RuntimeException(e);
            }
        } else {
            try {
                final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                        .getDeviceId();
                unique_uid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8"))
                        : UUID.randomUUID();
            } catch (UnsupportedEncodingException e) {
                LoggingUtils.e(LOG_TAG, "Error creating UUID " + e.getLocalizedMessage(), getAppContext());
                throw new RuntimeException(e);
            }
        }
        // Write the value out to the prefs file
        Hybris.setSharedPreferenceString(InternalConstants.KEY_PREF_UUID, unique_uid.toString());

    }
}

From source file:com.team08storyapp.ESHelper.java

/**
 * Adds or updates a story on the webservice. The method checks the Story
 * object passed in to see if it contains a onlineStoryId. If it does not it
 * finds the next possible Id to assigned to it and then adds the Story to
 * the webservice with that Id. If the Story object contains an
 * onlineStoryId then it calls the webservice with that Id and the story
 * object, updating the Story that was located at that Id.
 * /*  w  ww  .  j a  v a2s . c  o  m*/
 * @param story
 *            The Story that is being added or updated to the webservice.
 * @return The onlineStoryId of the Story that was added or updated.
 * @see Story
 */
public int addOrUpdateOnlineStory(Story story) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    HttpPost httpPost;
    /*
     * check if there is an online story Id to determine if adding or
     * updating the story
     */
    if (story.getOnlineStoryId() == 0) {
        /*
         * find out how many stories are stored online in order to generate
         * an appropriate online story Id
         */
        ArrayList<Story> stories = getOnlineStories();
        int nextId = stories.size() + 1;

        /*
         * create the httppost item with the webservice information and the
         * new id to put the story under
         */
        httpPost = new HttpPost("http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + nextId);
        story.setOnlineStoryId(nextId);
    } else {
        /*
         * create the httppost item with the webservice information and the
         * story's online id so that it upates that item
         */
        httpPost = new HttpPost(
                "http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + story.getOnlineStoryId());
    }

    /* convert the story object to JSON format */
    StringEntity stringentity = null;
    try {
        stringentity = new StringEntity(gson.toJson(story));
    } catch (UnsupportedEncodingException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return 0;
    }

    /*
     * set the httppost so that it knows it is accepting a JSON formatted
     * object to add
     */
    httpPost.setHeader("Accept", "application/json");
    /* set the object to add into the httppost */
    httpPost.setEntity(stringentity);

    HttpResponse response = getHttpResponse(httpPost);
    /* Retrieve and print to the log cat the status result of the post */
    String status = response.getStatusLine().toString();
    Log.d(TAG, status);

    HttpEntity entity = response.getEntity();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        String output;

        Log.d(TAG, "Output from Server -> ");
        while ((output = br.readLine()) != null) {
            Log.d(TAG, output);
        }
    } catch (IllegalStateException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return 0;
    } catch (IOException e) {
        Log.d(TAG, e.getLocalizedMessage());
        return 0;
    }

    /*
     * return back to the calling class the online story id for the story
     * object added or updated
     */
    return story.getOnlineStoryId();
}