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.fanfou.app.opensource.util.NetworkHelper.java

public static MultipartEntity encodeMultipartParameters(final List<SimpleRequestParam> params) {
    if (CommonHelper.isEmpty(params)) {
        return null;
    }// w w w .  ja va  2  s  .  c om
    final MultipartEntity entity = new MultipartEntity();
    try {
        for (final SimpleRequestParam param : params) {
            if (param.isFile()) {
                entity.addPart(param.getName(), new FileBody(param.getFile()));
            } else {
                entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(HTTP.UTF_8)));
            }
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return entity;
}

From source file:com.ms.commons.utilities.CharTools.java

/**
 * textGBK???XML?//  w  w  w  . j  av a2 s  . c  o  m
 * 
 * @param text
 * @param maxLen
 * @return CheckResult
 */
public static CheckResult checkXmlGbkChar(String text, int maxLen) {
    if (text == null || text.length() == 0 || maxLen == 0) {
        return new CheckResult(false, -1, -1, "Text is null or MaxLen is zero");
    }
    StringBuilder sb = new StringBuilder();
    boolean success = true;
    char[] chars = text.toCharArray();
    int byteLength = 0;
    for (int i = 0; i < chars.length; i++) {
        byte[] bytes;
        try {
            bytes = ("" + chars[i]).getBytes("GBK");
            int temp = bytes[0] & 0xff;
            if (bytes.length == 1 && temp < 32) // 320?31?????
            {
                sb.append("?char(" + temp + ")");
                success = false;
            }
            byteLength += bytes.length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    if (byteLength > maxLen) {
        success = false;
    }
    return new CheckResult(success, text.length(), byteLength, sb.toString());
}

From source file:com.lambdasoup.panda.PandaHttp.java

static String postFile(String url, Map<String, String> params, Properties properties, File file) {
    Map<String, String> sParams = signedParams("POST", url, params, properties);
    String flattenParams = canonicalQueryString(sParams);
    String requestUrl = "http://" + properties.getProperty("api-host") + ":80/v2" + url + "?" + flattenParams;

    HttpPost httpPost = new HttpPost(requestUrl);
    String stringResponse = null;
    FileBody bin = new FileBody(file, "application/octet-stream");
    try {/*from   w  w  w  .  java  2s  .  com*/
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", bin);

        httpPost.setEntity(entity);

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpResponse response = httpclient.execute(httpPost);
        stringResponse = EntityUtils.toString(response.getEntity());

    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringResponse;
}

From source file:com.utest.webservice.client.rest.RestClient.java

private static String paramsToString(final Map<String, Object> params) {
    if (params == null)
        return "";
    String str = "";
    String separator = "?";
    for (final Map.Entry<String, Object> param : params.entrySet()) {
        try {/* w w w .ja v  a 2  s  .  c o  m*/

            if (param.getValue() instanceof List) {
                for (Object l : (List) param.getValue()) {
                    str += separator + param.getKey() + "=" + URLEncoder.encode(l.toString(), "UTF-8");
                    separator = "&";
                }
            } else {
                str += separator + param.getKey() + "="
                        + URLEncoder.encode(param.getValue().toString(), "UTF-8");
            }
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        separator = "&";
    }
    return str;
}

From source file:org.openmhealth.shim.OAuth1Utils.java

/**
 * Builds a signed URL with the given parameters
 *
 * @param unsignedUrl     - The unsigned URL
 * @param clientId        - The external provider assigned client id
 * @param clientSecret    - The external provider assigned client secret
 * @param token           - The access token
 * @param tokenSecret     - The 'secret' parameter to be used (Note: token secret != client secret)
 * @param oAuthParameters - Any additional parameters
 * @return A Signed URL// w w w  .  j av a 2s  .  c o m
 * @throws ShimException
 */
public static URL buildSignedUrl(String unsignedUrl, String clientId, String clientSecret, String token,
        String tokenSecret, Map<String, String> oAuthParameters) throws ShimException {

    // Build the oauth consumer used for signing requests.
    OAuthConsumer consumer = createOAuthConsumer(clientId, clientSecret);

    if (token != null) {
        consumer.setTokenWithSecret(token, tokenSecret);
    }

    // Add any additional parameters.
    if (oAuthParameters != null) {
        try {
            HttpParameters httpParameters = new HttpParameters();
            for (String key : oAuthParameters.keySet()) {
                if (key.equals(OAuth.OAUTH_CALLBACK)) {
                    httpParameters.put(key, URLEncoder.encode(oAuthParameters.get(key), "UTF-8"));
                } else {
                    httpParameters.put(key, oAuthParameters.get(key));
                }
            }
            consumer.setAdditionalParameters(httpParameters);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new ShimException("Could not URL Encode callbackUrl, cannot continue");
        }
    }

    // Sign the URL.
    URL url;
    try {
        UrlStringRequestAdapter adapter = new UrlStringRequestAdapter(unsignedUrl);
        consumer.sign(adapter);
        url = new URL(adapter.getRequestUrl());
    } catch (MalformedURLException | OAuthExpectationFailedException | OAuthCommunicationException
            | OAuthMessageSignerException e) {
        throw new ShimException("Error signing URL", e);
    }

    return url;
}

From source file:com.ms.commons.utilities.CharTools.java

/**
 * ?textUTF8????maxLen<br>/*from  w ww. j a  va  2  s  .c  om*/
 * Oracle?3??String.length()??<br>
 * 
 * @param text 
 * @param maxLen  (3,???)
 * @return
 */
public static List<String> splitText4UTF8(String text, int maxLen) {
    Assert.isTrue(maxLen >= 3); // 3,???
    List<String> list = new ArrayList<String>();
    if (text == null || text.length() == 0) {
        return list;
    }
    char[] chars = text.toCharArray();
    StringBuilder sb = new StringBuilder(maxLen);
    int currentLength = 0;
    for (int i = 0; i < chars.length; i++) {
        byte[] bytes;
        try {
            bytes = ("" + chars[i]).getBytes("UTF-8");
            if (currentLength + bytes.length <= maxLen) {
                sb.append(chars[i]);
                currentLength += bytes.length;
            } else {
                list.add(sb.toString());
                sb = new StringBuilder(maxLen);
                sb.append(chars[i]);
                currentLength = bytes.length;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    if (sb.length() > 0) {
        list.add(sb.toString());
    }
    return list;
}

From source file:info.guardianproject.mrapp.server.Util.java

public static String makeJsonRpcCall(String jsonRpcUrl, JSONObject payload, String authToken, Context context) {
    Log.d(LOG_TAG, jsonRpcUrl + " " + payload.toString());
    try {/*from ww  w .  ja  v a  2 s .  com*/
        HttpClient client = new StrongHttpsClient(context);
        HttpPost httpPost = new HttpPost(jsonRpcUrl);

        if (authToken != null) {
            httpPost.addHeader(new BasicHeader("Authorization", "GoogleLogin auth=" + authToken));
        }

        httpPost.setEntity(new StringEntity(payload.toString(), "UTF-8"));

        HttpResponse httpResponse = client.execute(httpPost);
        if (200 == httpResponse.getStatusLine().getStatusCode()) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);

            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            return sb.toString();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.firejack.platform.core.utils.FileUtils.java

/**
 * @param child/*w  w w  .jav a 2  s  .c o m*/
 *
 * @return
 */
public static File getResource(String... child) {
    URL url = Thread.currentThread().getContextClassLoader().getResource("");
    String file = url.getFile();
    try {
        file = URLDecoder.decode(file, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return FileUtils.create(file, child);
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;//from  w ww . j  av a2 s . c om
    List fileItems = null;
    int i = 0;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        try {
            if (fi1.isFormField()) {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } else {

                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    filemap.put(i, fi1.getFieldName());
                    i++;
                    fileUpload = true;
                }
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.qualogy.qafe.bind.orm.jibx.ORMBinder.java

/**
 * closing the bytearrayinputstream has now effect
 * @param doc/* w w  w  . ja  v a  2s  . c om*/
 * @param root
 * @return
 */
public static Object bind(Document doc, String root, Class expectedResultType, boolean readInDebugMode) {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    // Refactor the commented code below, to make Google App Engine (GAE) compatible
    // The com.sun.org.apache.xml.internal.serialize.OutputFormat class is restricted
    /*OutputFormat format = new OutputFormat(doc);
    format.setIndenting(true);
    try {
       new XMLSerializer(bout, format).serialize(doc);
    } catch (IOException e) {
       throw new BindException(e);
    }*/
    /*try {
       Source source = new DOMSource(doc);
       Result result = new StreamResult(bout);
       TransformerFactory factory = TransformerFactory.newInstance();
       Transformer transformer = factory.newTransformer();
       transformer.transform(source, result);
    } catch (Exception e) {
       throw new BindException(e);
    }*/

    String docAsString = docToString(doc);
    byte[] docAsBytes = null;

    try {
        docAsBytes = docAsString.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    ByteArrayInputStream in = new ByteArrayInputStream(docAsBytes);
    //ByteArrayInputStream in = new ByteArrayInputStream(bout.toByteArray());

    if (readInDebugMode && logger.isLoggable(Level.FINE)) {
        try {
            logger.fine(docToString(in));
        } catch (IOException e1) {
            logger.log(Level.WARNING, "unable to print the merged document contents due to error", e1);
        }
    }

    Object obj = null;
    try {
        IBindingFactory bfact = BindingDirectory.getFactory(expectedResultType);
        IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
        obj = uctx.unmarshalDocument(in, root, ENCODING_TYPE);
    } catch (JiBXException e) {
        String line = JIBXExceptionTranslator.getLine(e, in);
        BindException be = (line != null) ? new BindException(e.getMessage() + "\nLine: " + line, e)
                : new BindException(e);
        throw be;
    } catch (ClassCastException e) {
        throw new BindException(e);
    }
    return obj;
}