List of usage examples for java.io UnsupportedEncodingException printStackTrace
public void printStackTrace()
From source file:com.o2o.util.WebUtils.java
public static void clearCookie(HttpServletRequest request, HttpServletResponse response, String path, String domain) {//from ww w . j a v a 2 s.co m Assert.notNull(request); Assert.notNull(response); try { Cookie[] cookies = request.getCookies(); for (Cookie cookie_old : cookies) { String name = URLEncoder.encode(cookie_old.getName(), "UTF-8"); Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } response.addCookie(cookie); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
From source file:com.github.consiliens.harv.util.Utils.java
/** * Extracts headers from allHeaders and updates harHeaders and harCookies. * /*from w ww . j a v a 2 s. c o m*/ * Returns the size of the headers (calculated by summing the length of * each name and value in UTF8 bytes). **/ public static long extractHeadersAndCookies(final Header[] allHeaders, final HarHeaders harHeaders, final HarCookies harCookies) { long headersSize = 0; final CookieDecoder decoder = new CookieDecoder(); final CookieDateFormat format = new CookieDateFormat(); for (final Header header : allHeaders) { final String headerName = header.getName(); final String headerValue = header.getValue(); try { headersSize += headerName.getBytes(UTF8).length + headerValue.getBytes(UTF8).length; } catch (final UnsupportedEncodingException e1) { e1.printStackTrace(); } harHeaders.addHeader(new HarHeader(headerName, headerValue)); if (headerValue != null && headerName.equalsIgnoreCase("Cookie")) { final Set<Cookie> cookies = decoder.decode(headerValue); for (final Cookie cookie : cookies) { Date expires = null; final int maxAge = cookie.getMaxAge(); if (maxAge != -1) { try { // TODO: Is CookieDateFormat formatting maxAge // properly? expires = format.parse(format.format(maxAge)); } catch (final ParseException e) { e.printStackTrace(); } } harCookies.addCookie( new HarCookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), expires, cookie.isHttpOnly(), cookie.isSecure(), cookie.getComment())); } } } return headersSize; }
From source file:com.o2o.util.WebUtils.java
/** * ?cookie/*from w ww . ja va2 s .co m*/ * * @param request * HttpServletRequest * @param name * cookie?? * @return ?null */ public static String getCookie(HttpServletRequest request, String name) { if (null == name) { return null; } Assert.notNull(request); Assert.hasText(name); Cookie[] cookies = request.getCookies(); if (cookies != null) { try { name = URLEncoder.encode(name, "UTF-8"); for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return URLDecoder.decode(cookie.getValue(), "UTF-8"); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return null; }
From source file:co.mike.apptemplate.Utils.ServerUtils.RESTCient.java
public static void setPostAsync(String URL, final int TYPE, RequestParams params, final onResponseServer listener) { if (postClient != null && isTaskPostRun) { Log.e(TAG, "setPost isTaskRun "); } else {/*from w w w . ja v a 2 s.c o m*/ postClient = new AsyncHttpClient(); AsyncHttpResponseHandler post = new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); Log.e(TAG, "onStart"); isTaskPostRun = true; } @Override public void onProgress(int bytesWritten, int totalSize) { super.onProgress(bytesWritten, totalSize); isTaskPostRun = true; Log.e(TAG, "onProgress bytesWritten " + bytesWritten + " totalSize " + totalSize); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { isTaskPostRun = false; try { String str = new String(responseBody, "UTF-8"); Log.e(TAG, "onSuccess statusCode " + statusCode + " responseBody " + str); listener.OnResponse(str, statusCode, TYPE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { try { isTaskPostRun = false; String str = new String(responseBody, "UTF-8"); Log.e(TAG, "onFailure statusCode " + statusCode + " responseBody " + str); listener.OnResponse(str, statusCode, TYPE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void onRetry(int retryNo) { super.onRetry(retryNo); Log.e(TAG, "onRetry No " + retryNo); } @Override public void onFinish() { super.onFinish(); isTaskPostRun = false; Log.e(TAG, "onFinish"); } }; postClient.post(URL, params, post); } }
From source file:setiquest.renderer.Utils.java
/** * Send a BSON file./* ww w.j a va 2 s .c o m*/ * @param filename the full path to the BSON file. * @param actId the activity Id. * @param obsId the observation Id. * @param pol the POL of thedata. * @param subchannel the subchannel of the data. */ public static String sendBSONFile(String filename, int actId, int obsId, int pol, String subchannel) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Utils.getSubjectsURL()); Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:" + subchannel); FileBody bin = new FileBody(new File(filename)); try { StringBody comment = new StringBody("Filename: " + filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("type", new StringBody("data/bson")); reqEntity.addPart("subject[activity_id]", new StringBody("" + actId)); reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId)); reqEntity.addPart("subject[pol]", new StringBody("" + pol)); reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel)); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); Log.log(response.toString()); return response.toString(); /* sendResult = "subject[activity_id]: " + actId + "\n"; sendResult += "subject[observation_id]: " + obsId + "\n"; sendResult += "subject[pol]: " + pol + "\n"; sendResult += "subject[subchannel]: " + subchannel + "\n"; sendResult += response.toString() + "|\n"; */ } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "ERROR"; }
From source file:com.fengduo.bee.commons.util.StringUtils.java
public static String abbr2(String param, int length) { if (param == null) { return ""; }//from w w w . ja v a 2s. c o m StringBuffer result = new StringBuffer(); int n = 0; char temp; boolean isCode = false; // ?HTML? boolean isHTML = false; // ?HTML, for (int i = 0; i < param.length(); i++) { temp = param.charAt(i); if (temp == '<') { isCode = true; } else if (temp == '&') { isHTML = true; } else if (temp == '>' && isCode) { n = n - 1; isCode = false; } else if (temp == ';' && isHTML) { isHTML = false; } try { if (!isCode && !isHTML) { n += String.valueOf(temp).getBytes("GBK").length; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (n <= length - 3) { result.append(temp); } else { result.append("..."); break; } } // ??HTML String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2"); // ??HTML temp_result = temp_result.replaceAll( "</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", ""); // ?HTML temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2"); // ?? Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>"); Matcher m = p.matcher(temp_result); List<String> endHTML = Lists.newArrayList(); while (m.find()) { endHTML.add(m.group(1)); } // ??HTML for (int i = endHTML.size() - 1; i >= 0; i--) { result.append("</"); result.append(endHTML.get(i)); result.append(">"); } return result.toString(); }
From source file:jeeves.server.sources.JeevletServiceRequestFactory.java
private static String simplifyName(String file) { //--- get the file name without path file = new File(file).getName(); //--- the previous getName method is not enough //--- with IE and a server running on Linux we still have a path problem int pos1 = file.lastIndexOf("\\"); int pos2 = file.lastIndexOf("/"); int pos = Math.max(pos1, pos2); if (pos != -1) file = file.substring(pos + 1).trim(); //--- we need to sanitize the filename here - make it UTF8, no ctrl //--- characters and only containing [A-Z][a-z][0-9],_.- //--- start by converting to UTF-8 try {/*from w w w. j a v a 2 s. c om*/ byte[] utf8Bytes = file.getBytes("UTF8"); file = new String(utf8Bytes, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //--- replace whitespace with underscore file = file.replaceAll("\\s", "_"); //--- remove everything that isn't [0-9][a-z][A-Z],#_.- file = file.replaceAll("[^\\w&&[^,_.-]]", ""); return file; }
From source file:com.pti.mates.ServerUtilities.java
private static void updatePreferences(JSONObject user, Context ctx, String fbid) { DefaultHttpClient client = new MyHttpClient(ctx); HttpPost post = new HttpPost("https://54.194.14.115:443/upload"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("user", user.toString())); try {/*from w w w .j a va 2s .c o m*/ post.setHeader("Content-type", "application/json"); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HttpResponse postResponse; try { postResponse = client.execute(post); HttpEntity responseEntity = postResponse.getEntity(); InputStream is = responseEntity.getContent(); } catch (ClientProtocolException e) { Log.e("ERROR", e.toString()); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); Log.e("ERROR", e.toString()); s = "ERROR: " + e.toString() + " :("; } Log.d("CHIVATO", "FIN THREAD"); }
From source file:com.pti.mates.ServerUtilities.java
private static void post2(String endpoint, final String msg, final String id, final Context ctx) { DefaultHttpClient client = new MyHttpClient(ctx); HttpPost post = new HttpPost("https://54.194.14.115:443/send"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("receiver", id)); nameValuePairs.add(new BasicNameValuePair("sender", Common.getFBID())); nameValuePairs.add(new BasicNameValuePair("data", msg)); try {//w w w . ja va 2 s . c o m post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Execute the Post call and obtain the response HttpResponse postResponse; s = "s No inicialitzada"; try { postResponse = client.execute(post); HttpEntity responseEntity = postResponse.getEntity(); InputStream is = responseEntity.getContent(); s = convertStreamToString(is); } catch (ClientProtocolException e) { Log.e("ERROR", e.toString()); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); Log.e("ERROR", e.toString()); s = "ERROR: " + e.toString() + " :("; } Log.d("CHIVATO", "FIN THREAD"); //return s; }
From source file:jeeves.server.sources.ServiceRequestFactory.java
/** Builds the request with data supplied by tomcat. * A request is in the form: srv/<language>/<service>[!]<parameters> *//*from w ww.j a v a2s .c o m*/ public static ServiceRequest create(HttpServletRequest req, HttpServletResponse res, String uploadDir, int maxUploadSize) throws Exception { String url = req.getPathInfo(); // FIXME: if request character encoding is undefined set it to UTF-8 String encoding = req.getCharacterEncoding(); try { // verify that encoding is valid Charset.forName(encoding); } catch (Exception e) { encoding = null; } if (encoding == null) { try { req.setCharacterEncoding(Jeeves.ENCODING); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } } //--- extract basic info HttpServiceRequest srvReq = new HttpServiceRequest(res); srvReq.setDebug(extractDebug(url)); srvReq.setLanguage(extractLanguage(url)); srvReq.setService(extractService(url)); srvReq.setJSONOutput(extractJSONFlag(url)); String ip = req.getRemoteAddr(); String forwardedFor = req.getHeader("x-forwarded-for"); if (forwardedFor != null) ip = forwardedFor; srvReq.setAddress(ip); srvReq.setOutputStream(res.getOutputStream()); //--- discover the input/output methods String accept = req.getHeader("Accept"); if (accept != null) { int soapNDX = accept.indexOf("application/soap+xml"); int xmlNDX = accept.indexOf("application/xml"); int htmlNDX = accept.indexOf("html"); if (soapNDX != -1) srvReq.setOutputMethod(OutputMethod.SOAP); else if (xmlNDX != -1 && htmlNDX == -1) srvReq.setOutputMethod(OutputMethod.XML); } if ("POST".equals(req.getMethod())) { srvReq.setInputMethod(InputMethod.POST); String contType = req.getContentType(); if (contType != null) { if (contType.indexOf("application/soap+xml") != -1) { srvReq.setInputMethod(InputMethod.SOAP); srvReq.setOutputMethod(OutputMethod.SOAP); } else if (contType.indexOf("application/xml") != -1 || contType.indexOf("text/xml") != -1) srvReq.setInputMethod(InputMethod.XML); } } //--- retrieve input parameters InputMethod input = srvReq.getInputMethod(); if ((input == InputMethod.XML) || (input == InputMethod.SOAP)) { if (req.getMethod().equals("GET")) srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize)); else srvReq.setParams(extractXmlParameters(req)); } else { //--- GET or POST srvReq.setParams(extractParameters(req, uploadDir, maxUploadSize)); } srvReq.setHeaders(extractHeaders(req)); return srvReq; }