List of usage examples for java.io UnsupportedEncodingException getLocalizedMessage
public String getLocalizedMessage()
From source file:com.otisbean.keyring.Ring.java
/** * Encrypt the given data with our key, prepending saltLength random * characters./*from w ww . java2 s .c om*/ * @return Base64 encoded representation of the encrypted data. */ String encrypt(String data, int saltLength) throws GeneralSecurityException { log("encrypt()"); try { cipher.init(Cipher.ENCRYPT_MODE, key, iv); } catch (InvalidKeyException ike) { throw new GeneralSecurityException("InvalidKeyException: " + ike.getLocalizedMessage() + "\nYou (probably) need to " + "install the \"Java Cryptography Extension (JCE) " + "Unlimited Strength Jurisdiction Policy\" files. Go to " + "http://java.sun.com/javase/downloads/index.jsp, download them, " + "and follow the instructions."); } String salted = saltString(saltLength, data); byte[] crypted; byte[] saltedBytes; try { saltedBytes = salted.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new GeneralSecurityException(e.getLocalizedMessage()); } crypted = cipher.doFinal(saltedBytes); return Base64.encodeBytes(crypted); }
From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = super.onOptionsItemSelected(item); if (!handled) { // Put custom menu items handlers here switch (item.getItemId()) { // NFC writing is for debug use only case R.id.write_tag: if (NFCUtil.canNFC(this)) { Intent writeIntent = new Intent(this, NFCWriteActivity.class); NdefMessage msg = getNDEF(mProduct.getCode()); writeIntent.putExtra(NFCWriteActivity.NDEF_MESSAGE, msg); startActivity(writeIntent); } else { Toast.makeText(this, R.string.error_nfc_not_supported, Toast.LENGTH_LONG).show(); }//from w ww . j a va2 s . com return true; case R.id.share: try { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, mProduct.getName() + " - " + getString(R.string.nfc_url, URLEncoder.encode(mProduct.getCode(), "UTF-8"))); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, getString(R.string.share_dialog_title))); } catch (UnsupportedEncodingException e) { LoggingUtils.e(LOG_TAG, "Error trying to encode product code to UTF-8. " + e.getLocalizedMessage(), Hybris.getAppContext()); } return true; default: return false; } } return handled; }
From source file:com.serena.rlc.provider.jenkins.JenkinsExecutionProvider.java
@Action(name = BUILDJOB_ACTION, displayName = "Run Build Job", description = "Run a preconfigured Jenkins build job") @Params(params = {//from w w w.j a va 2s . com @Param(fieldName = BUILD_JOB_PARAM, displayName = "Job", description = "Jenkins build job", required = true, dataType = DataType.SELECT), @Param(fieldName = EXTENDED_FIELDS, displayName = "Extended Fields", description = "Jenkins job extended fields", required = false, environmentProperty = false, dataType = DataType.SELECT) }) public ExecutionInfo buildJob(String taskTitle, String taskDescription, List<Field> properties) throws ProviderException { Field buildJobField = Field.getFieldByName(properties, BUILD_JOB_PARAM); if (buildJobField == null || StringUtils.isEmpty(buildJobField.getValue())) { throw new ProviderException("Missing required field: " + BUILD_JOB_PARAM); } String buildJob = buildJobField.getValue(); // Create parameter string //String paramString = "{\"parameter\": ["; // add taskExecutionId as default parameter UUID executionId = UUID.randomUUID(); String paramString = "?RLC_EXECUTION_ID=" + executionId.toString(); Field extendedFieldsField = Field.getFieldByName(properties, EXTENDED_FIELDS); if (extendedFieldsField != null) { List<Field> extendedFields = extendedFieldsField.getExtendedFields(); int count = 0; for (Field extendedField : extendedFields) { /*if (count > 0) { paramString += ", "; } paramString += "{\"name\":\"" + extendedField.getFieldName() + "\", \"value\":\"" + extendedField.getValue() + "\"}"; */ try { paramString += "&" + extendedField.getFieldName() + "=" + URLEncoder.encode(extendedField.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e) { logger.equals(e.getLocalizedMessage()); } count++; } } //paramString += "]}"; ExecutionInfo retVal = new ExecutionInfo(); JenkinsClient client = new JenkinsClient(this.getJenkinsUrl(), this.getServiceUser(), this.getServicePassword()); try { client.setPollSleepTime(tryParseInt(this.getPollSleepTime(), 1000)); client.setMaxPollCount(tryParseInt(this.getMaxPollCount(), 15)); BuildInfo result = client.startBuild(buildJob, paramString); Boolean statusSet = false; if (result.hasBuildNumber()) { retVal.setExecutionUrl(result.getBuildUrl()); retVal.setMessage(String.format("Build Number: %d", result.getBuildNumber())); retVal.setExecutionId(executionId.toString()); } else { retVal.setExecutionUrl(client.createUrl(this.getJenkinsUrl(), "job/" + buildJob)); retVal.setExecutionId(executionId.toString()); retVal.setMessage("Failed to start job and retrieve a build number. Message: " + result.getMessage() + " - Queue: " + result.getQueueUrl()); if (Boolean.parseBoolean(this.getWaitForBuildNumber())) { retVal.setStatus(ExecutionStatus.FAILED); statusSet = true; } } if (!statusSet) { if (Boolean.parseBoolean(getWaitForCallback())) { retVal.setStatus(ExecutionStatus.PENDING); } else { retVal.setStatus(ExecutionStatus.COMPLETED); } } } catch (JenkinsClientException ex) { logger.error(ex.getMessage(), ex); retVal.setStatus(ExecutionStatus.FAILED); retVal.setExecutionUrl(client.createUrl(this.getJenkinsUrl(), "job/" + buildJob)); retVal.setMessage("Failed to start job and retrieve a build number"); } return retVal; }
From source file:org.eclipse.che.api.factory.FactoryService.java
/** * Get factory information from storage by its id. * * @param id/*from w ww . j a v a2 s. co m*/ * - id of factory * @param uriInfo * - url context * @return - stored data, if id is correct. * @throws org.eclipse.che.api.core.ApiException * - {@link org.eclipse.che.api.core.NotFoundException} when factory with given id doesn't exist */ @ApiOperation(value = "Get Factory information by its ID", notes = "Get JSON with Factory information. Factory ID is passed in a path parameter", response = Factory.class, position = 2) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Factory not found"), @ApiResponse(code = 409, message = "Failed to validate Factory URL"), @ApiResponse(code = 500, message = "Internal Server Error") }) @GET @Path("/{id}") @Produces({ MediaType.APPLICATION_JSON }) public Factory getFactory(@ApiParam(value = "Factory ID", required = true) @PathParam("id") String id, @ApiParam(value = "Legacy. Whether or not to transform Factory into the most recent format", allowableValues = "true,false", defaultValue = "false") @DefaultValue("false") @QueryParam("legacy") Boolean legacy, @ApiParam(value = "Whether or not to validate values like it is done when accepting a Factory", allowableValues = "true,false", defaultValue = "false") @DefaultValue("false") @QueryParam("validate") Boolean validate, @Context UriInfo uriInfo) throws ApiException { Factory factoryUrl = factoryStore.getFactory(id); if (factoryUrl == null) { LOG.warn("Factory URL with id {} is not found.", id); throw new NotFoundException("Factory URL with id " + id + " is not found."); } if (legacy) { factoryUrl = factoryBuilder.convertToLatest(factoryUrl); } try { factoryUrl = factoryUrl.withLinks( linksHelper.createLinks(factoryUrl, factoryStore.getFactoryImages(id, null), uriInfo)); } catch (UnsupportedEncodingException e) { throw new ServerException(e.getLocalizedMessage()); } if (validate) { acceptValidator.validateOnAccept(factoryUrl, true); } return factoryUrl; }
From source file:de.chaosdorf.meteroid.longrunningio.LongRunningIOPost.java
@Override protected String doInBackground(Void... params) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); try {/*from w w w.j a v a2 s. c om*/ httpPost.setEntity(new UrlEncodedFormEntity(postData)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } try { HttpResponse response = httpClient.execute(httpPost, localContext); int code = response.getStatusLine().getStatusCode(); if (code >= 400 && code <= 599) { callback.displayErrorMessage(id, response.getStatusLine().getReasonPhrase()); return null; } HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, HTTP.UTF_8); } catch (Exception e) { callback.displayErrorMessage(id, e.getLocalizedMessage()); return null; } }
From source file:org.ajax4jsf.webapp.BaseFilter.java
private Map<String, String> parseQueryString(String queryString) { if (queryString != null) { Map<String, String> parameters = new HashMap<String, String>(); String[] nvPairs = AMPERSAND.split(queryString); for (String nvPair : nvPairs) { if (nvPair.length() == 0) { continue; }//from w w w . ja v a 2s. co m int eqIdx = nvPair.indexOf('='); if (eqIdx >= 0) { try { String name = URLDecoder.decode(nvPair.substring(0, eqIdx), "UTF-8"); if (!parameters.containsKey(name)) { String value = URLDecoder.decode(nvPair.substring(eqIdx + 1), "UTF-8"); parameters.put(name, value); } } catch (UnsupportedEncodingException e) { //log warning and skip this parameter log.warn(e.getLocalizedMessage(), e); } } } return parameters; } else { return Collections.EMPTY_MAP; } }
From source file:com.teleca.jamendo.api.impl.JamendoGet2ApiImpl.java
@Override public Album[] getUserStarredAlbums(String user) throws JSONException, WSError { try {/*from www . java 2 s . c o m*/ user = URLEncoder.encode(user, "UTF-8"); String jsonString = doGet( "id+name+url+image+rating+artist_name/album/json/album_user_starred/?user_idstr=" + user + "&n=all&order=rating_desc"); JSONArray jsonArrayAlbums = new JSONArray(jsonString); return AlbumFunctions.getAlbums(jsonArrayAlbums); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } catch (JSONException e) { return null; } catch (NullPointerException e) { e.printStackTrace(); throw new WSError(e.getLocalizedMessage()); } }
From source file:org.eclipse.che.api.factory.FactoryService.java
/** * Updates factory with a new factory content * * @param id/*from w w w. ja va 2 s.c o m*/ * id of factory * @param newFactory * the new data for the factory * @throws NotFoundException * when factory with given id doesn't exist * @throws org.eclipse.che.api.core.ServerException * if given factory is null */ @ApiOperation(value = "Updates factory information by its ID", notes = "Updates factory based on the Factory ID which is passed in a path parameter") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 403, message = "User not authorized to call this operation"), @ApiResponse(code = 404, message = "Factory not found"), @ApiResponse(code = 500, message = "Internal Server Error") }) @PUT @Path("/{id}") @RolesAllowed("user") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public Factory updateFactory(@ApiParam(value = "Factory ID", required = true) @PathParam("id") String id, Factory newFactory) throws ApiException { // forbid null update if (newFactory == null) { throw new ServerException("The updating factory shouldn't be null"); } // Do we have a factory for this id ? Factory existingFactory = factoryStore.getFactory(id); if (existingFactory == null) { throw new NotFoundException("Factory with id " + id + " does not exist."); } // Gets the User id final User user = EnvironmentContext.getCurrent().getUser(); String userId = user.getId(); // Validate the factory against the current user factoryEditValidator.validate(existingFactory, userId); processDefaults(newFactory); newFactory.getCreator().withCreated(existingFactory.getCreator().getCreated()); newFactory.setId(existingFactory.getId()); // validate the new content createValidator.validateOnCreate(newFactory); // access granted, user can update the factory factoryStore.updateFactory(id, newFactory); // create links try { newFactory.setLinks( linksHelper.createLinks(newFactory, factoryStore.getFactoryImages(id, null), uriInfo)); } catch (UnsupportedEncodingException e) { throw new ServerException(e.getLocalizedMessage()); } return newFactory; }
From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java
@Override public SearchResultImpl findEntries(SearchCriteria search) { SearchResultImpl results = null;// w w w . ja v a 2s . c o m String searchText = search.getSearchText(); if (searchText != null && searchText.contains("<script>")) { // Do not perform any search } if (searchText != null && searchText.contains(";")) { // Do not perform any search } else if (searchText != null && searchText.contains("eval")) { // Do not perform any search } else { results = (SearchResultImpl) getApplicationContext().getBean("searchResult"); StringBuilder queryString = new StringBuilder(); if (search.getSearchText() != null && !search.getSearchText().trim().isEmpty()) { searchText = searchText.replaceAll("[^\\w\\s]", ""); //Removes all special character queryString.append("searchCriteria="); queryString.append(searchText.trim()); } else if (search.getUserName() != null && !search.getUserName().isEmpty()) { queryString.append("uniqname="); queryString.append(search.getUserName().trim()); } else { if ("starts".equalsIgnoreCase(search.getExactness())) { search.setExactness("starts with"); } if (search.getFirstName() != null && !search.getFirstName().trim().isEmpty()) { queryString.append("givenName="); queryString.append(search.getFirstName().trim()); queryString.append("&givenNameSearchType="); queryString.append(search.getExactness()); queryString.append("&"); } if (search.getLastName() != null && !search.getLastName().trim().isEmpty()) { queryString.append("sn="); queryString.append(search.getLastName().trim()); queryString.append("&snSearchType="); queryString.append(search.getExactness()); } } LOG.debug("QueryString will be : " + queryString.toString()); try { URLConnection connection = new URL(SEARCH_URL).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET); OutputStream output = null; output = connection.getOutputStream(); output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET)); InputStream response = connection.getInputStream(); String contentType = connection.getHeaderField("Content-Type"); if (contentType != null && "application/json".equalsIgnoreCase(contentType)) { // LOG.debug("Attempting to parse JSON using Gson."); List<Person> peeps = new ArrayList<Person>(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(response, DEFAULT_CHARACTER_SET)); String jsonData = IOUtils.toString(response, 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; JSONArray jsonPerson = (JSONArray) jsonObject.get("person"); for (Object o : jsonPerson) { peeps.add(parsePerson((JSONObject) o)); } } catch (UnsupportedEncodingException uee) { LOG.error(uee.getLocalizedMessage()); } catch (IOException ioe) { LOG.error(ioe.getLocalizedMessage()); } catch (ParseException pe) { LOG.error(pe.getLocalizedMessage(), pe); } finally { if (reader != null) { try { reader.close(); } catch (IOException logOrIgnore) { LOG.error(logOrIgnore.getLocalizedMessage()); } } } results.setPeople(peeps); } else { LOG.debug("Content type was not application/json."); } } catch (IOException ioe) { LOG.error(ioe.getLocalizedMessage()); } LOG.debug("Searching for groups."); results.setGroups(searchForGroup(search)); } return results; }