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.thed.zapi.cloud.sample.FetchExecuteUpdate.java

public static void main(String[] args) throws JSONException, URISyntaxException, ParseException, IOException {
    final String issueSearchUri = API_SEARCH_ISSUES.replace("{SERVER}", jiraBaseURL);

    /**/*from   w  ww .  j  a  v  a2 s .  c o  m*/
     * Get Test Issues by JQL
     * 
     */

    //Json object for JQL search
    JSONObject jqlJsonObj = new JSONObject();
    jqlJsonObj.put("jql", "project = SUP"); // Replace the value with Valid JQL
    jqlJsonObj.put("startAt", 0);
    jqlJsonObj.put("maxResults", 21); // maxResults to be returned by search
    jqlJsonObj.put("fieldsByKeys", false);

    String[] IssueIds = getIssuesByJQL(issueSearchUri, userName, password, jqlJsonObj);
    // System.out.println(ArrayUtils.toString(IssueIds));

    /**
     * Add tests to Cycle
     * 
     */

    final String addTestsUri = API_ADD_TESTS.replace("{SERVER}", zephyrBaseUrl) + cycleId;

    /** Create JSON object by providing input values */
    String[] IssueIds = new String[25];
    JSONObject addTestsObj = new JSONObject();
    addTestsObj.put("issues", IssueIds);
    addTestsObj.put("method", "1");
    addTestsObj.put("projectId", projectId);
    addTestsObj.put("versionId", versionId);

    StringEntity addTestsJSON = null;
    try {
        addTestsJSON = new StringEntity(addTestsObj.toString());
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    addTestsToCycle(addTestsUri, client, accessKey, addTestsJSON);

    /**
     * Get Execution Id's by CycleId and Add them to Ad Hoc cycle of
     * UnScheduled Version
     * 
     */
    Map<String, String> executionIds = new HashMap<String, String>();
    final String getExecutionsUri = API_GET_EXECUTIONS.replace("{SERVER}", zephyrBaseUrl) + cycleId
            + "?projectId=" + projectId + "&versionId=" + versionId;

    executionIds = getExecutionsByCycleId(getExecutionsUri, client, accessKey);

    /**
     * Bulk Update Executions with Status by Execution Id
     * 
     */

    JSONObject statusObj = new JSONObject();
    statusObj.put("id", "1");

    JSONObject executeTestsObj = new JSONObject();
    executeTestsObj.put("status", statusObj);
    executeTestsObj.put("cycleId", cycleId);
    executeTestsObj.put("projectId", projectId);
    executeTestsObj.put("versionId", versionId);
    executeTestsObj.put("comment", "Executed by ZAPI Cloud");

    for (String key : executionIds.keySet()) {
        final String updateExecutionUri = API_UPDATE_EXECUTION.replace("{SERVER}", zephyrBaseUrl) + key;
        // System.out.println(updateExecutionUri);
        // System.out.println(executionIds.get(key));
        executeTestsObj.put("issueId", executionIds.get(key));
        // System.out.println(executeTestsObj.toString());
        StringEntity executeTestsJSON = null;
        try {
            executeTestsJSON = new StringEntity(executeTestsObj.toString());
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        updateExecutions(updateExecutionUri, client, accessKey, executeTestsJSON);
    }

}

From source file:com.sociesc.findasmartphonespark.Main.java

public static void main(String[] args) {
    String apiPrefix = "api/v1/";

    //setIpAddress("192.168.56.1");
    setPort(9010);/*w w  w.j a  v a2  s  .  co m*/

    try {
        Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados");
        DatabaseUtils.seedDatabase();
    } catch (SQLException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    Dao<User> userDao = new Dao(User.class);

    get(apiPrefix + "/hello/:name", (request, response) -> {
        ObjectMapper objectMapper = new ObjectMapper();

        /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>();
                
        for (int i = 0; i < 10; i++) {
        AccessPoint ap = new AccessPoint();
        ap.setBSSID("AP" + i);
        ap.setSSID("00:00:00:0" + i);
        ap.setRSSI(-50 + i);
        ap.setSala("Sala" + i);
                
        arrayAp.add(ap);
                
        //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI());
        }
                
        String retornoJson = rwJson.writeJson(arrayAp);*/

        //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol")));
        ArrayList<AccessPoint> arrayAp = null;
        try {
            arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return arrayAp.get(0).getBSSID();

        //return "Hello: " + request.params(":name");
        //return arrayAp[0].get;
    });

    post(apiPrefix + "/findUser/:data", (request, response) -> {
        String userId = request.params(":data");

        ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString());

        /*JsonObject json = new JsonObject();
                
        try {
        json = JsonObject.readFrom(request.params(":data"));
        } catch (Exception ex) {
        System.out.println("erro no json:\n" + ex.getMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
        }*/
        try {
            for (int i = 0; i < aps.size(); i++) {
                System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID()
                        + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala());
            }
        } catch (Exception ex) {
            System.out.println("erro no json:\n" + ex.getMessage());
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            //json.add("error", ex.getMessage());
            response.status(500);
            return ex.getMessage();
        }

        return userId.toString();
    });

    /*post(apiPrefix + "/findUser/", (request, response) ->{
     JsonObject json = new JsonObject();
            
    // Informaes do roteador/AP
    String[] BSSID; // basic service set identifier - nome da conexo
    String[] SSID; // service set identifier - identificador nico da conexo
    int[]    RSSI; // received signal strength indicator - potencia do sinal (-87 a -32)
    String   sala;
            
    String jsonBody = request.body();
    JsonObject reqJson = JsonObject.readFrom(jsonBody);
    JsonObject wifiJson = reqJson.get("wifi").asObject();
            
    System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size());
            
    RSSI = new int[wifiJson.size()];
    BSSID = new String[wifiJson.size()];
    SSID = new String[wifiJson.size()];
            
    try{
        for (int i = 0; i < wifiJson.size(); i++) {
            // recebe informaes das conexes encontradas
            BSSID[i] = wifiJson.get("BSSID").asString();
            SSID[i] = wifiJson.get("SSID").asString();
            RSSI[i] = wifiJson.get("RSSI").asInt();
        }
            
        return json.toString();
    }catch(Exception ex){
        System.out.println("erro no json:\n" + ex.getMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
    }
    return json.toString();
    });*/

    get(apiPrefix + "/users", (request, response) -> {
        JsonObject json = new JsonObject();

        request.params();

        try {
            List<User> users = userDao.findAll();
            JsonArray usersJson = new JsonArray();
            for (User u : users) {
                JsonObject uJson = new JsonObject();
                uJson.add("id", u.getId());
                uJson.add("name", u.getName());
                uJson.add("email", u.getEmail());
                usersJson.add(uJson);
            }
            json.add("users", usersJson);

        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }

        return json.toString();
    });

    /*get(apiPrefix + "/users/:id", (request, response) -> {
    Long userId = Long.parseLong(request.params(":id"));
    JsonObject json = new JsonObject();
    try{
        User user = userDao.findById(userId);
        if(user == null){
            json.add("error", "user not found");
            response.status(404);
            return json.toString();
        }
                
        JsonObject userJson = new JsonObject();
        userJson.add("id", user.getId());
        userJson.add("name", user.getName());
        userJson.add("email", user.getEmail());
        json.add("user", userJson);
        return json.toString();
                
    }catch(Exception ex){
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
    }
            
    return json.toString();
    });*/

    delete(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try {
            userDao.removeById(userId);
            json.add("message", "user removed");
            response.status(200);
            return json.toString();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }

        return json.toString();
    });

    put(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try {
            String jsonBody = request.body();
            JsonObject reqJson = JsonObject.readFrom(jsonBody);
            JsonObject userJson = reqJson.get("user").asObject();
            String name = userJson.get("name") != null ? userJson.get("name").asString() : null;
            String email = userJson.get("email") != null ? userJson.get("email").asString() : null;
            String password = userJson.get("password") != null ? userJson.get("password").asString() : null;

            User user = userDao.findById(userId);

            if (name != null)
                user.setName(name);

            if (email != null)
                user.setEmail(email);

            if (password != null) {
                String passwordDigest = DatabaseUtils.criptPass(password);
                user.setPasswordDigest(passwordDigest);
            }

            userDao.update(user);

            JsonObject resUserJson = new JsonObject();
            resUserJson.add("id", user.getId());
            resUserJson.add("name", user.getName());
            resUserJson.add("email", user.getEmail());

            json.add("user", resUserJson);
            return json.toString();

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
    });

    post(apiPrefix + "/users", (request, response) -> {
        JsonObject json = new JsonObject();
        try {
            String jsonBody = request.body();
            JsonObject reqJson = JsonObject.readFrom(jsonBody);
            JsonObject userJson = reqJson.get("user").asObject();
            User user = new User();
            user.setName(userJson.get("name").asString());
            user.setEmail(userJson.get("email").asString());
            user.setPasswordDigest(DatabaseUtils.criptPass("tempPass"));
            userDao.create(user);

            JsonObject resUserJson = new JsonObject();
            resUserJson.add("id", user.getId());
            resUserJson.add("name", user.getName());
            resUserJson.add("email", user.getEmail());
            resUserJson.add("passwordDigest", user.getPasswordDigest());

            json.add("user", resUserJson);
            return json.toString();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
    });

}

From source file:com.foo.manager.commonManager.thread.HttpHandleThread.java

public static void main(String arg[]) {

    //      String logistics_interface = "<LoadHead><loadContents><loadContent><loadContentId>1</loadContentId><outorderId>6666666666</outorderId></loadContent><loadContent><loadContentId>2</loadContentId><outorderId>7777777777</outorderId></loadContent></loadContents><loadHeadId>12</loadHeadId><loadId>1736474588</loadId><total>2</total><tracyNum>3</tracyNum><TotalWeight>2.5</TotalWeight><CarEcNo>?A234234</CarEcNo></LoadHead>";
    ///*from   w  w  w  .ja  v  a 2 s  . c  o m*/
    //      String data_digest = CommonUtil.makeSign(logistics_interface);
    //
    //      System.out.println(data_digest);
    //      try {
    //         System.out
    //               .println("logistics_interface="
    //                     + URLEncoder.encode(logistics_interface, "utf-8")
    //                     + "&data_digest="
    //                     + URLEncoder.encode(data_digest, "utf-8"));
    //      } catch (UnsupportedEncodingException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }
    //
    //      try {
    //         System.out.println(URLEncoder.encode("helloworld", "utf-8"));
    //         System.out.println(URLEncoder.encode("voQc3u6+f6pSflMPdw4ySQ==",
    //               "utf-8"));
    //      } catch (UnsupportedEncodingException e) {
    //         // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Map<String, Object> map1 = new HashMap<String, Object>();
    map1.put("RECORD_NO", "335");
    map1.put("CREAT_TIME", "2018-09-14 21:46:17");
    Map<String, Object> map2 = new HashMap<String, Object>();
    map2.put("RECORD_NO", "145");
    map2.put("CREAT_TIME", "2018-09-14 23:46:17");
    Map<String, Object> map3 = new HashMap<String, Object>();
    map3.put("RECORD_NO", "285");
    map3.put("CREAT_TIME", "2018-09-14 22:46:17");
    Map<String, Object> map4 = new HashMap<String, Object>();
    map4.put("RECORD_NO", "265");
    map4.put("CREAT_TIME", "2018-09-14 22:46:17");
    list.add(map1);
    list.add(map2);
    list.add(map3);
    list.add(map4);
    // ??
    for (Map<String, Object> map : list) {
        System.out.println(map);
    }

    Collections.sort(list, new Comparator<Map>() {
        public int compare(Map o1, Map o2) {
            //            double qty1 = Double.valueOf(o1.get("QTY")
            //                  .toString());
            //            double qty2 = Double.valueOf(o2.get("QTY")
            //                  .toString());
            String recordNo1 = o1.get("RECORD_NO") != null ? o1.get("RECORD_NO").toString() : "";
            String recordNo2 = o2.get("RECORD_NO") != null ? o2.get("RECORD_NO").toString() : "";
            //            if (qty1 > qty2) {
            if (recordNo1.compareTo(recordNo2) < 0) {
                return 0;
            } else {
                return 1;
            }
            //            } else {
            //               return 0;
            //            }
        }
    });

    System.out.println("-------------------");
    for (Map<String, Object> map : list) {
        System.out.println(map);
    }
    //
    //      String s = "<![CDATA[?]]>";
    //      Pattern p = Pattern.compile(".*<!\\[CDATA\\[(.*)\\]\\]>.*");
    //      Matcher m = p.matcher(s);
    //
    //      if (m.matches()) {
    //         System.out.println(m.group(1));
    //      }else{
    //         System.out.println(s);
    //      }
    //      
    //      System.out.println(CommonUtil.getDateFormatter(CommonDefine.COMMON_FORMAT_2)
    //               .format(new Date()));

    //      String response = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\"><soapenv:Body><ns:sendOrderResponse xmlns:ns=\"http://ws.com\"><ns:return><?xml version=\"1.0\" encoding=\"UTF-8\"?><DATA><ORDER><ORDER_CODE>W100133410</ORDER_CODE><CD>OK</CD><INFO>11811000073</INFO></ORDER></DATA></ns:return></ns:sendOrderResponse></soapenv:Body></soapenv:Envelope>";
    //      
    //      String xxxx = StringEscapeUtils.escapeXml(response);

    //      String returnXmlData = XmlUtil
    //            .getResponseFromXmlString_CJ(xxxx);

    //      String returnXmlData = XmlUtil.getTotalMidValue(response,"<ns:return>","</ns:return>");
    //      
    //      Map orderResult = XmlUtil.parseXmlFPAPI_SingleNodes(returnXmlData, "//DATA/ORDER/child::*");

    //      System.out.println(xxxx);

    //      System.out.println(orderResult);

    try {
        String xxx = "<returnInfo>?????????????</returnInfo>";

        xxx = "<returnInfo>?????????????/returnInfo>";

        //         String xxx = "??[??3201966A69??AAAA124613101110701] ?[3201966A69]??[AAAA124613101110701]??? ??[1210680001]???[245119218897]???? ?[3201966A69]??[AAAA124613101110701]??";

        //         String uft_gbk = new String(xxx.getBytes("UTF-8"),"GBK");

        String gbk_utf = new String(xxx.getBytes("GBK"), "UTF-8");

        //         System.out.println(uft_gbk);
        System.out.println(gbk_utf);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:Main.java

public static String fromByteArrayToUtf8String(byte[] bytes) {
    try {//ww w  .  j  av  a2  s . c  o  m
        return new String(bytes, "utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String utf8StringFromBytes(byte[] bytes) {
    try {/*from   w  w  w  . j ava2  s  .c o m*/
        return new String(bytes, "utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String urlEncoderStr(String string) {
    try {//from w w w.  java  2 s . c  o m
        return URLEncoder.encode(string, "utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return string;
}

From source file:Main.java

public static String urlEncode(String code) {
    try {//w  w w . j ava  2  s . c om
        return URLEncoder.encode(code, "UTF-8").replaceAll(" ", "").trim();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String urlDecoder(String code) {
    try {//from w  w  w.  j av a  2  s . co  m
        return URLDecoder.decode(code, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static String base64Encode(String str) {
    try {//from  w w w.  j  a  v  a 2s .  co  m
        str = Base64.encodeToString(str.getBytes("UTF-8"), Base64.DEFAULT);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return str;
}

From source file:Main.java

public static String urlDecode(String content, String charsetName) {
    try {//ww  w .  ja  v  a  2  s.  c o m
        return URLDecoder.decode(content, charsetName);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return "";
}