List of usage examples for java.io UnsupportedEncodingException getMessage
public String getMessage()
From source file:net.fluxo.dd.FluxoWSProcess.java
/** * Add a HTTP-based download to current list of downloads for the server to process. * <p>URL to reach this method: http://[address-or-ip]:[port]/comm/rs/ws/adduri/[user-id]/[http-url]</p> * * @param uri HTTP download url// w w w. j a v a 2s . c om * @param owner user ID associated with this download * @return a string containing the status of the request; "OK" followed by download ID or an error message */ @GET @Path("/adduri/{owner}/{uri}") @Produces("text/plain") public Response getHttpUrl(@Context HttpServletRequest htRequest, @DefaultValue("") @PathParam("uri") String uri, @DefaultValue("") @PathParam("owner") String owner) { String username = htRequest.getHeader("DDUSER"); String password = htRequest.getHeader("DDPWD"); if (username == null || password == null || !DbControl.authCredentials(username, password)) { return Response.status(400).entity("NOT-AUTHORIZED").build(); } try { if (uri.length() > 0 && owner.length() > 0) { String decodedURL = URLDecoder.decode(uri, "UTF-8"); String response = OAria.processRequest(decodedURL, owner, true, "", ""); return Response.status(200).entity(response).build(); } } catch (UnsupportedEncodingException uee) { return Response.status(500).entity(uee.getMessage()).build(); } return Response.status(400).entity("EITHER-URI-ERROR-OR-NO-OWNER").build(); }
From source file:com.sitexa.android.data.net.volley.VolleyApi.java
protected Observable<ApiResult> doPost(final String doAction, final Map<String, String> requestParam, final boolean shouldCache, final boolean refreshCache, final boolean checkNetwork) { final ApiResult result = new ApiResult(); return Observable.create(new Observable.OnSubscribe<ApiResult>() { @Override//from w w w. jav a 2 s . c o m public void call(Subscriber<? super ApiResult> subscriber) { if (checkNetwork && !isThereInternetConnection()) { subscriber.onError(new NetworkConnectionException( CodeConstants.ApiCode.NETWORK_ERROR + ":" + "Network connection error")); } else { try { final String api = getApi(doAction); Log.d(TAG, String.format("Request url %s", api)); StringRequest request = new StringRequest(Request.Method.POST, api, json -> { Log.d(TAG, json); Map map = gson.fromJson(json, Map.class); Object code = map.get(CodeConstants.HttpCode.CODE); Object value = map.get(CodeConstants.HttpCode.VALUE); if (CodeConstants.HttpCode.SUCCESS_CODE.equals(code)) { result.setCode(CodeConstants.ApiCode.OK); result.setOriginalCode(String.valueOf(code)); result.setValue(gson.toJson(value)); subscriber.onNext(result); subscriber.onCompleted(); } else { subscriber.onError(new NetworkConnectionException(CodeConstants.ApiCode.ERROR + ":" + String.valueOf(code) + ":" + value.toString())); } Log.d(TAG, String.format("Request %s success. Result code: %s value: %s", api, CodeConstants.ApiCode.ERROR, value.toString())); }, volleyError -> { subscriber.onError( new NetworkConnectionException(CodeConstants.ApiCode.SERVER_CONNECTION_ERROR + ":" + (volleyError != null ? volleyError.getMessage() : ""))); Log.d(TAG, String.format("Request %s failure. Result code: %s message: %s", api, CodeConstants.ApiCode.SERVER_CONNECTION_ERROR, volleyError != null ? volleyError.getMessage() : "")); }) { @Override protected Map<String, String> getParams() throws AuthFailureError { return requestParam; } @Override protected Response<String> parseNetworkResponse(NetworkResponse response) { String setCookie = response.headers.get("Set-Cookie"); if (StringUtils.isNotEmpty(setCookie)) { mCookie = setCookie; } Log.d(TAG, "Response cookie " + mCookie); String json = ""; if (shouldCache) { int maxAge = 7 * 24 * 60 * 60; response.headers.remove("Cache-Control"); response.headers.remove("Pragma"); response.headers.remove("Expires"); if (refreshCache) { invalidateCached(api); } try { json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.getMessage(), e); } return Response.success(json, cache(response, maxAge)); } return super.parseNetworkResponse(response); } @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> localHashMap = new HashMap<String, String>(); if (StringUtils.isNotEmpty(mCookie)) { localHashMap.put("Cookie", mCookie); } return localHashMap; } }; request.setShouldCache(shouldCache); requestQueue.add(request); } catch (Exception e) { subscriber.onError(new NetworkConnectionException(e.getCause())); } } } }); }
From source file:org.s1.testing.httpclient.TestHttpClient.java
/** * * @param u/*from ww w .ja v a 2s. c om*/ * @param data * @return */ protected String getURL(String u, Map<String, Object> data) { if (data == null) data = new HashMap<String, Object>(); String query = ""; int i = 0; for (String key : data.keySet()) { if (i != 0) query += "&"; try { query += (key + "=" + URLEncoder.encode("" + data.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } i++; } if (!query.isEmpty()) u += ("?" + query); return u; }
From source file:net.fluxo.dd.FluxoWSProcess.java
/** * Add a HTTP-based download to current list of downloads for the server to process, with authentication (username * and password).//from www .j a v a2 s . c o m * <p>URL to reach this method: http://[address-or-ip]:[port]/comm/rs/ws/adduric/[user-id]/[username]/[password]/[http-url]</p> * * @param uri HTTP download url * @param owner user ID associated with this download * @param username username for authentication * @param password password for authentication * @return a string containing the status of the request; "OK" followed by download ID or an error message */ @GET @Path("/adduric/{owner}/{username}/{password}/{uri}") @Produces("text/plain") public Response getHttpUrlC(@Context HttpServletRequest htRequest, @DefaultValue("") @PathParam("uri") String uri, @DefaultValue("") @PathParam("owner") String owner, @DefaultValue("") @PathParam("username") String username, @DefaultValue("") @PathParam("password") String password) { String credUsername = htRequest.getHeader("DDUSER"); String credPassword = htRequest.getHeader("DDPWD"); if (credUsername == null || credPassword == null || !DbControl.authCredentials(credUsername, credPassword)) { return Response.status(400).entity("NOT-AUTHORIZED").build(); } try { if (uri.length() > 0 && owner.length() > 0 && username.length() > 0 && password.length() > 0) { String decodedURL = URLDecoder.decode(uri, "UTF-8"); String response = OAria.processRequest(decodedURL, owner, true, username, password); return Response.status(200).entity(response).build(); } } catch (UnsupportedEncodingException uee) { return Response.status(500).entity(uee.getMessage()).build(); } return Response.status(400).entity("EITHER-URI-ERROR-OR-NO-OWNER-OR-USERNAME-PASSWORD-ERROR").build(); }
From source file:grails.web.servlet.mvc.GrailsParameterMap.java
/** * Converts this parameter map into a query String. Note that this will flatten nested keys separating them with the * . character and URL encode the result * * @return A query String starting with the ? character *//*from ww w .j a v a 2 s . co m*/ public String toQueryString() { String encoding = request.getCharacterEncoding(); try { return WebUtils.toQueryString(this, encoding); } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException( "Unable to convert parameter map [" + this + "] to a query string: " + e.getMessage(), e); } }
From source file:net.solarnetwork.node.hw.currentcost.CCMessageParser.java
/** * Parse a CurrentCost XML message into a CCDatum object. * /*from w w w .ja v a 2s .c o m*/ * @param messageXML * the message bytes to parse * @return the CCDatum instance, or <em>null</em> if any parsing error * occurs */ public CCDatum parseMessage(byte[] messageXML) { CCDatum d = new CCDatum(); if (log.isDebugEnabled()) { try { log.debug("Parsing CC XML: {}", new String(messageXML, "UTF-8")); } catch (UnsupportedEncodingException e) { // shouldn't get here } } try { extractBeanDataFromXml(d, getDocBuilderFactory().newDocumentBuilder().parse(new ByteArrayInputStream(messageXML)), xpathMapping); } catch (Exception e) { try { log.debug("XML parsing exception: {}; message: {}", e.getMessage(), new String(messageXML, "US-ASCII")); } catch (UnsupportedEncodingException e1) { log.debug("XML parsing exception: {}", e.getMessage()); } return null; } return d; }
From source file:gov.nist.appvet.toolmgr.ToolServiceAdapter.java
public MultipartEntity getMultipartEntity() { final MultipartEntity entity = new MultipartEntity(); File apkFile = null;/*from w w w . ja v a2 s.c om*/ FileBody fileBody = null; try { String fileUploadParamName = null; // Add parameter name-value pairs if (formParameterNames != null) { for (int i = 0; i < formParameterNames.size(); i++) { final String paramName = formParameterNames.get(i); String paramValue = formParameterValues.get(i); if (paramValue.equals("APP_FILE")) { fileUploadParamName = paramName; } else { if (paramValue.equals("APPVET_DEFINED")) { if (paramName.equals("appid")) { appInfo.log.debug("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "'. Setting to appid = '" + appInfo.appId + "'"); paramValue = appInfo.appId; } else { appInfo.log.error("Found " + paramName + " = " + "'APPVET_DEFINED' for tool '" + id + "' but no actual value is set by AppVet. Aborting."); return null; } } if ((paramName == null) || paramName.isEmpty()) { appInfo.log.warn("Param name is null or empty " + "for tool '" + name + "'"); } else if ((paramValue == null) || paramValue.isEmpty()) { appInfo.log.warn("Param value is null or empty " + "for tool '" + name + "'"); } StringBody partValue = new StringBody(paramValue, Charset.forName("UTF-8")); entity.addPart(paramName, partValue); partValue = null; } } } final String apkFilePath = appInfo.getIdPath() + "/" + appInfo.fileName; appInfo.log.debug("Sending file: " + apkFilePath); apkFile = new File(apkFilePath); fileBody = new FileBody(apkFile); entity.addPart(fileUploadParamName, fileBody); return entity; } catch (final UnsupportedEncodingException e) { appInfo.log.error(e.getMessage()); return null; } }
From source file:com.google.cloud.solutions.smashpix.MainActivity.java
/** * Uploads the image to Google Cloud Storage. *///from w ww .j av a 2 s . com public Boolean uploadToCloudStorage(ServicesStorageSignedUrlResponse signedUrlParams, File localImageStoragePath){ if (!signedUrlParams.isEmpty() && localImageStoragePath.exists()) { FileBody binary = new FileBody(localImageStoragePath); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(signedUrlParams.getFormAction()); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { entity.addPart("bucket", new StringBody(signedUrlParams.getBucket())); entity.addPart("key", new StringBody(signedUrlParams.getFilename())); entity.addPart("policy", new StringBody(signedUrlParams.getPolicy())); entity.addPart("signature", new StringBody(signedUrlParams.getSignature())); entity.addPart("x-goog-meta-owner", new StringBody(accountName)); entity.addPart("GoogleAccessId", new StringBody(signedUrlParams.getGoogleAccessId())); entity.addPart("file", binary); } catch (UnsupportedEncodingException e) { Log.e(Constants.APP_NAME, e.getMessage()); return false; } httpPost.setEntity(entity); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 204) { Log.i(Constants.APP_NAME, "Image Uploaded"); return true; } } catch (ClientProtocolException e) { Log.e(Constants.APP_NAME, e.getMessage()); } catch (IOException e) { Log.e(Constants.APP_NAME, e.getMessage()); } } Log.e(Constants.APP_NAME, "Image Upload Failed"); return false; }
From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java
private void setHttpBody(HttpEntityEnclosingRequestBase requestBase, JSONObject body) { if (body != null) { try {// w ww . j av a 2 s . co m StringEntity entity = new StringEntity(body.toString()); entity.setContentType("application/json"); entity.setContentEncoding("UTF-8"); requestBase.setEntity(entity); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); } } }
From source file:com.mobiperf.Checkin.java
private String serviceRequest(String url, String jsonString) throws IOException { if (this.accountSelector == null) { accountSelector = new AccountSelector(context); }/*from www . ja va2s .c o m*/ if (!accountSelector.isAnonymous()) { synchronized (this) { if (authCookie == null) { if (!checkGetCookie()) { throw new IOException("No authCookie yet"); } } } } HttpClient client = getNewHttpClient(); String fullurl = (accountSelector.isAnonymous() ? phoneUtils.getAnonymousServerUrl() : phoneUtils.getServerUrl()) + "/" + url; Logger.i("Checking in to " + fullurl); HttpPost postMethod = new HttpPost(fullurl); StringEntity se; try { se = new StringEntity(jsonString); } catch (UnsupportedEncodingException e) { throw new IOException(e.getMessage()); } postMethod.setEntity(se); postMethod.setHeader("Accept", "application/json"); postMethod.setHeader("Content-type", "application/json"); if (!accountSelector.isAnonymous()) { // TODO(mdw): This should not be needed postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue()); } ResponseHandler<String> responseHandler = new BasicResponseHandler(); Logger.i("Sending request: " + fullurl); String result = client.execute(postMethod, responseHandler); return result; }