Example usage for java.io UnsupportedEncodingException printStackTrace

List of usage examples for java.io UnsupportedEncodingException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.vmware.vchs.publicapi.samples.HttpUtils.java

/**
 * Gets the string content from the passed in InputStream
 * //from   w  w w .  j  a  va2 s . c om
 * @param is
 *            response stream from GET/POST method call
 * @return String content of the passed in InputStream
 */
public static String getContent(InputStream is) {
    if (is != null) {
        StringBuilder sb = new StringBuilder();
        String line;

        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    throw new RuntimeException(e);
                }
            }
        }

        return sb.toString();
    }

    return "";
}

From source file:com.tinyhydra.botd.BotdServerOperations.java

public static void CastVote(final Activity activity, final Handler handler, final String email,
        final String shopId, final String shopRef) {
    new Thread() {
        @Override/*w  ww .j a  va 2 s. c om*/
        public void run() {
            try {
                URI uri = new URI(activity.getResources().getString(R.string.server_url));
                HttpClient client = new DefaultHttpClient();
                HttpPut put = new HttpPut(uri);

                JSONObject voteObj = new JSONObject();

                // user's phone-account-email-address is used to prevent multiple votes
                // the server will validate. 'shopId' is a consistent id for a specific location
                // but can't be used to get more data. 'shopRef' is an id that changes based on
                // some criteria that google places has imposed, but will let us grab data later on
                // and various Ref codes with the same id will always resolve to the same location.
                voteObj.put(JSONvalues.email.toString(), email);
                voteObj.put(JSONvalues.shopId.toString(), shopId);
                voteObj.put(JSONvalues.shopRef.toString(), shopRef);
                put.setEntity(new StringEntity(voteObj.toString()));

                HttpResponse response = client.execute(put);
                InputStream is = response.getEntity().getContent();
                int ch;
                StringBuffer sb = new StringBuffer();
                while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                }
                if (sb.toString().equals("0")) {
                    Utils.PostToastMessageToHandler(handler, "Vote cast!", Toast.LENGTH_SHORT);
                    // Set a local flag to prevent duplicate voting
                    SharedPreferences settings = activity.getSharedPreferences(Const.GenPrefs, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putLong(Const.LastVoteDate, Utils.GetDate());
                    editor.commit();
                } else {
                    // The user shouldn't see this. The above SharedPreferences code will be evaluated
                    // when the user hits the Vote button. If the user gets sneaky and deletes local data though,
                    // the server will catch the duplicate vote based on the user's email address and send back a '1'.
                    Utils.PostToastMessageToHandler(handler,
                            "Vote refused. You've probably already voted today.", Toast.LENGTH_LONG);
                }
                GetTopTen(activity, handler, true);
                // Catch blocks. Return a generic error if anything goes wrong.
                //TODO: implement some better/more appropriate error handling.
            } catch (URISyntaxException usex) {
                usex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (UnsupportedEncodingException ueex) {
                ueex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (ClientProtocolException cpex) {
                cpex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (IOException ioex) {
                ioex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (JSONException jex) {
                jex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            }
        }
    }.start();
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

public static JSONArray getJSONArray(String url, String userId) {

    InputStream is = null;//from   w  w w.  j  a  va 2 s.  c o  m
    JSONArray jArray = null;
    String json = "";

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("user_id", userId));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        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 parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;
}

From source file:com.iterzp.momo.utils.WebUtils.java

/**
 * cookie//from   w  ww .  ja  v  a  2s . c  o  m
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param path
 *            
 * @param domain
 *            
 */
public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String path, String domain) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        name = URLEncoder.encode(name, "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:de.betterform.agent.web.WebFactory.java

/**
 * allow absolute paths otherwise resolve relative to the servlet context
 *
 * @param resolvePath XPath locationpath
 * @return the absolute path or path relative to the servlet context
 * @deprecated//from   w  w  w  . j a  v  a  2  s  .c  o  m
 */
public static final String resolvePath(String resolvePath, ServletContext servletContext) {
    String path = resolvePath;
    try {
        if (path != null && !(path.startsWith("/"))) {
            path = "/" + path;
        }
        URL pathURL = servletContext.getResource(path);
        if (pathURL != null) {
            path = java.net.URLDecoder.decode(pathURL.getPath(), StandardCharsets.UTF_8.name());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return path;
}

From source file:com.iterzp.momo.utils.WebUtils.java

/**
 * ?cookie//from  www  .j av  a 2 s .co  m
 * 
 * @param request
 *            HttpServletRequest
 * @param name
 *            cookie??
 * @return ?null
 */
public static String getCookie(HttpServletRequest request, String name) {
    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.cask.cdap.gateway.util.Util.java

/**
 * decode an URL-encoded string into bytes.
 *///from  w  w  w  .j a va2  s  .co  m
public static byte[] urlDecode(String str) {
    try { // we use a base encoding that accepts all byte values
        return URLDecoder.decode(str, "ISO8859_1").getBytes("ISO8859_1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null; // cant' happen with ISO8859_1 = Latin1
    }
}

From source file:edu.umass.cs.nio.MessageExtractor.java

protected static void fatalExit(UnsupportedEncodingException e) {
    e.printStackTrace();
    System.err.println("NIO failed because the charset encoding " + JSONNIOTransport.NIO_CHARSET_ENCODING
            + " is not supported; exiting");
    System.exit(1);/* www .  j  a  v a 2s  .c o  m*/
}

From source file:com.iterzp.momo.utils.WebUtils.java

/**
 * cookie/*from  www . ja va 2s .c  o  m*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param value
 *            cookie
 * @param maxAge
 *            (??: )
 * @param path
 *            
 * @param domain
 *            
 * @param secure
 *            ??
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, Integer maxAge, String path, String domain, Boolean secure) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        name = URLEncoder.encode(name, "UTF-8");
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(name, value);
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        if (secure != null) {
            cookie.setSecure(secure);
        }
        response.addCookie(cookie);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java

/**
 * ?request?fireDir?request.setAttribute(fieldName, value)?
 *
 * @param request /*from  ww  w. jav  a 2s. c  o  m*/
 * @param fileDir 
 * @param maxSize ?
 * @param isFileNameBaseTime ????
 * @param encoding
 */
public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize,
        boolean isFileNameBaseTime, String encoding) {
    // ?
    if (!isFileUploadRequest(request))
        return null;
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // dir??
    File dir = new File(fileDir);
    if (!dir.exists()) {
        if (dir.mkdirs()) {
            throw new FileDirFaultException(dir);
        }
        ;
    }
    if (maxSize > 0) {
        factory.setSizeThreshold(maxSize);
    }

    factory.setRepository(dir);

    // ?
    ServletFileUpload fileUploader = new ServletFileUpload(factory);
    fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
    String realEncoding = fileUploader.getHeaderEncoding();

    List<FileItem> items = null;
    try {
        items = fileUploader.parseRequest(request);
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }
    if (items == null)
        return null;

    FileUploadRequestParamterContext context = new FileUploadRequestParamterContext();
    Map<String, List<File>> fileMap = context.getFileMap();
    Map<String, List<String>> fieldMap = context.getFormFieldMap();

    FileItem fileItem = null;
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        fileItem = iter.next();
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            List<String> values = fieldMap.get(fieldName);
            if (values == null) {
                values = new ArrayList<String>();
                fieldMap.put(fieldName, values);
            }
            String value = null;
            try {
                value = fileItem.getString(realEncoding);
            } catch (UnsupportedEncodingException e) {
                value = "";
                e.printStackTrace();
            }
            values.add(value);
            log.info("param:\t" + fieldName + "=" + value);
        } else {
            List<File> files = fileMap.get(fieldName);
            if (files == null) {
                files = new ArrayList<File>();
                fileMap.put(fieldName, files);
            }

            String clientFileName = fileItem.getName();// ???
            if (StringUtil.isNull(clientFileName)) { // 
                continue;
            }
            String realFileName = FileUtil.getRealFileName(clientFileName);
            String newFileName = null;
            if (isFileNameBaseTime) {
                newFileName = new FileNameBuilder().build(realFileName);
            } else {
                newFileName = realFileName;
            }
            File tempfile = new File(dir, newFileName);
            try {
                fileItem.write(tempfile);
                log.info("???\t" + newFileName);
                files.add(tempfile);
            } catch (Exception e) {
                continue;
            }
        }
    }

    return null;
}