List of usage examples for java.lang String getBytes
public byte[] getBytes(Charset charset)
From source file:com.jt.https.test.send.java
public static void main(String[] args) throws Exception { //final String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ChinaTourinsApply xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Head><UserId>0000000000</UserId><CommandId>CTAA0001</CommandId><SeqNo>JT2014_0000000263863</SeqNo></Head><Body><Apply><ApplyId>1201201407256948</ApplyId><TravelAgencyInfo><Id>1129035</Id><Name>???</Name><Address>?45?</Address><Zipcode>310000</Zipcode><Telphone>0571-63700288</Telphone><License>L-ZJ00295</License><OrgCode>79093228-2</OrgCode><OutboundTourismCredentials>N</OutboundTourismCredentials><LastYearTouristAmount>0.0</LastYearTouristAmount><LastYearRevenue>0-600</LastYearRevenue><last3YearAccidents>N</last3YearAccidents><Last1YearAccidentsFee>0.0</Last1YearAccidentsFee><Last2YearAccidentsFee>0.0</Last2YearAccidentsFee><Last3YearAccidentsFee>0.0</Last3YearAccidentsFee><Contact><Name></Name><Telphone>0571-63700288</Telphone><Mail>385816647@qq.ocm</Mail><Fax>0571-63700288</Fax></Contact><Branches /><Location><ProvinceId>12</ProvinceId><ProvinceName>?</ProvinceName><CityId>1201</CityId><CityName>?</CityName></Location><Properties><Key Name=\"LastApplyNo\" /><Key Name=\"LastPolicyNo\" /><Key Name=\"NewNum\" /><Key Name=\"NewLocation\" /></Properties><Last1YearPolicyNoList><Last1YearPolicyNoInfo><UserId /><PolicyNo /></Last1YearPolicyNoInfo></Last1YearPolicyNoList></TravelAgencyInfo><InsurancePolicyInfo><BeginDate>20140801</BeginDate><EndDate>20141231</EndDate><InsuranceDays>153</InsuranceDays><Renewal>N</Renewal><IssuingCompanyId>2014004</IssuingCompanyId><IssuingCompanyName>?????</IssuingCompanyName><IssuingGeneralCompanyName>???</IssuingGeneralCompanyName><RetroactiveDate>20140801</RetroactiveDate><MainInsurance><EachAccidentLiabilityLimit>20141000</EachAccidentLiabilityLimit><EachAccidentEveryLiabilityLimit>20142004</EachAccidentEveryLiabilityLimit><Properties><Key Name=\"MainPremium\">3135.4509</Key></Properties></MainInsurance><AdditionalInfo><Properties /></AdditionalInfo><PayDate>20140730</PayDate><PremiumInfo><PremiumAdjustmentFactor><YearTouristAmountRatio>-0.15</YearTouristAmountRatio><DistrictRatio>0</DistrictRatio><EachAccidentEveryLiabilityLimitRatio>0.1</EachAccidentEveryLiabilityLimitRatio><LossRatio>0</LossRatio><PreviousLossRatio>0</PreviousLossRatio><AdditionalRatio>0</AdditionalRatio><RiskControlRatio>0</RiskControlRatio><LoyaltyRatio>0</LoyaltyRatio><CoverageRateSystem>0</CoverageRateSystem><DatePreferentialRatio /></PremiumAdjustmentFactor><PremiumDistribution><TotalPremium>3135.45</TotalPremium><Distribution><RenBao CompanyId=\"2014004\">1442.30</RenBao><TaiBao CompanyId=\"2014058\">501.67</TaiBao><RenShou CompanyId=\"2014049\">250.84</RenShou><PingAn CompanyId=\"2014060\">344.90</PingAn><DaDi CompanyId=\"2014045\">282.19</DaDi><TaiPing CompanyId=\"2014039\">313.55</TaiPing></Distribution></PremiumDistribution><PremiumAdjust><RiskControl>0</RiskControl><Prepaid /></PremiumAdjust></PremiumInfo></InsurancePolicyInfo></Apply></Body></ChinaTourinsApply>"; final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ChinaTourinsResponse><Head><UserId>String</UserId><CommandId>String</CommandId><SeqNo>String</SeqNo><Ref-SeqNo>String</Ref-SeqNo></Head><Body><Apply><ApplyId>String</ApplyId><TravelAgencyId>String</TravelAgencyId><ResponseCode>String</ResponseCode><ResponseMessage>String</ResponseMessage><PolicyNo>String</PolicyNo><UpdateNo>String</UpdateNo><Fee>String</Fee><IssuingDate>String</IssuingDate><ElectricalDocument>String</ElectricalDocument></Apply></Body><IssuingCompany><Name>String</Name><Address>String</Address><Zipcode>String</Zipcode><Telphone>String</Telphone><Contact><Name>String</Name><Telphone>String</Telphone><Mail>String</Mail><Fax>String</Fax></Contact><Ccheck>String</Ccheck><Cbill>String</Cbill><Agent>String</Agent></IssuingCompany></ChinaTourinsResponse>"; WebInsuranceExchangeStub client = new WebInsuranceExchangeStub( "http://localhost/exchange/webservices/webInsuranceExchange"); com.jt.https.test.WebInsuranceExchangeStub.PolicyApplyConfirm post = new com.jt.https.test.WebInsuranceExchangeStub.PolicyApplyConfirm(); post.setUserId(""); DataHandler param = new DataHandler(new DataSource() { public InputStream getInputStream() { return new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8"))); }/*from w w w.j a v a 2 s . c om*/ public OutputStream getOutputStream() { return null; } public String getContentType() { return ""; } public String getName() { return ""; } }); post.setConfirmMessage(param); com.jt.https.test.WebInsuranceExchangeStub.PolicyApplyConfirmResponse response = client .policyApplyConfirm(post); InputStream is = response.getResponseMessage().getInputStream(); String xml_result = ToolsUtils.ConvertStreamToString(is); System.out.println(xml_result); //PostTo(xml); }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
static public void main(String... args) throws Exception { if (args.length < 1) { System.err.println("You must specify an action"); System.exit(-1);//from w ww . j a va2s . c om return; } String action = args[0]; if (action.equalsIgnoreCase("initializePairing")) { if (args.length < 5) { System.err.println("You must specify a location ID"); System.exit(-2); return; } String endpoint = args[1]; String locationId = args[2]; String apiKeyId = args[3]; String apiKeySecret = args[4]; HashMap<String, Object> act = new HashMap<String, Object>(); act.put("action", "initializePairing"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPut method = new HttpPut(endpoint + "/location/" + locationId); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "put:/location/" + locationId + ":" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(act)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_OK) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("pairingCode") && !u.isNull("pairingCode")) ? u.getString("pairingCode") : "--no code--"); } else { System.err.println("Failed to initialize pairing (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else if (action.equalsIgnoreCase("create")) { if (args.length < 7) { System.err.println("create ENDPOINT NAME DESCRIPTION TIMEZONE API_KEY_ID API_KEY_SECRET"); System.exit(-2); return; } String endpoint = args[1]; String name = args[2]; String description = args[3]; String tz = args[4]; String apiKeyId = args[5]; String apiKeySecret = args[6]; HashMap<String, Object> lstate = new HashMap<String, Object>(); lstate.put("name", name); lstate.put("description", description); lstate.put("timeZone", tz); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); HttpClient client = new DefaultHttpClient(params); HttpPost method = new HttpPost(endpoint + "/location"); long timestamp = System.currentTimeMillis(); System.out.println( "Signing: " + "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", CloudService.VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", apiKeyId); method.addHeader("x-imaginary-signature", CloudService.sign(apiKeySecret.getBytes("utf-8"), "post:/location:" + apiKeyId + ":" + timestamp + ":" + CloudService.VERSION)); //noinspection deprecation method.setEntity(new StringEntity((new JSONObject(lstate)).toString(), "application/json", "UTF-8")); HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() == HttpServletResponse.SC_CREATED) { String json = EntityUtils.toString(response.getEntity()); JSONObject u = new JSONObject(json); System.out.println((u.has("locationId") && !u.isNull("locationId")) ? u.getString("locationId") : "--no location--"); } else { System.err.println("Failed to create location (" + status.getStatusCode() + ": " + EntityUtils.toString(response.getEntity())); System.exit(status.getStatusCode()); } } else { System.err.println("No such action: " + action); System.exit(-3); } }
From source file:ebay.Ebay.java
/** * @param args the command line arguments *//*w w w .j av a 2 s . c om*/ public static void main(String[] args) { HttpClient client = null; HttpResponse response = null; BufferedReader rd = null; Document doc = null; String xml = ""; EbayDAO<Producto> db = new EbayDAO<>(Producto.class); String busqueda; while (true) { busqueda = JOptionPane.showInputDialog(null, "ingresa una busqueda"); if (busqueda != null) { busqueda = busqueda.replaceAll(" ", "%20"); try { client = new DefaultHttpClient(); /* peticion GET */ HttpGet request = new HttpGet("http://open.api.ebay.com/shopping?" + "callname=FindPopularItems" + "&appid=student11-6428-4bd4-ac0d-6ed9d84e345" + "&version=517&QueryKeywords=" + busqueda + "&siteid=0" + "&responseencoding=XML"); /* se ejecuta la peticion GET */ response = client.execute(request); rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); /* comienza la lectura de la respuesta a la peticion GET */ String line; while ((line = rd.readLine()) != null) { xml += line + "\n"; } } catch (IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } /* creamos nuestro documentBulder(documento constructor) y obtenemos nuestro objeto documento apartir de documentBuilder */ try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); } catch (ParserConfigurationException | SAXException | IOException ex) { Logger.getLogger(Ebay.class.getName()).log(Level.SEVERE, null, ex); } Element raiz = doc.getDocumentElement(); if (raiz == null) { System.exit(0); } if (raiz.getElementsByTagName("Ack").item(0).getTextContent().equals("Success")) { NodeList array = raiz.getElementsByTagName("ItemArray").item(0).getChildNodes(); for (int i = 0; i < array.getLength(); ++i) { Node n = array.item(i); if (n.getNodeType() != Node.TEXT_NODE) { Producto p = new Producto(); if (((Element) n).getElementsByTagName("ItemID").item(0) != null) p.setId(new Long( ((Element) n).getElementsByTagName("ItemID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("EndTime").item(0) != null) p.setEndtime( ((Element) n).getElementsByTagName("EndTime").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch").item(0) != null) p.setViewurl(((Element) n).getElementsByTagName("ViewItemURLForNaturalSearch") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("ListingType").item(0) != null) p.setListingtype( ((Element) n).getElementsByTagName("ListingType").item(0).getTextContent()); if (((Element) n).getElementsByTagName("GalleryURL").item(0) != null) p.setGalleryurl( ((Element) n).getElementsByTagName("GalleryURL").item(0).getTextContent()); if (((Element) n).getElementsByTagName("PrimaryCategoryID").item(0) != null) p.setPrimarycategoryid(new Integer(((Element) n) .getElementsByTagName("PrimaryCategoryID").item(0).getTextContent())); if (((Element) n).getElementsByTagName("PrimaryCategoryName").item(0) != null) p.setPrimarycategoryname(((Element) n).getElementsByTagName("PrimaryCategoryName") .item(0).getTextContent()); if (((Element) n).getElementsByTagName("BidCount").item(0) != null) p.setBidcount(new Integer( ((Element) n).getElementsByTagName("BidCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ConvertedCurrentPrice").item(0) != null) p.setConvertedcurrentprice(new Double(((Element) n) .getElementsByTagName("ConvertedCurrentPrice").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListingStatus").item(0) != null) p.setListingstatus(((Element) n).getElementsByTagName("ListingStatus").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("TimeLeft").item(0) != null) p.setTimeleft( ((Element) n).getElementsByTagName("TimeLeft").item(0).getTextContent()); if (((Element) n).getElementsByTagName("Title").item(0) != null) p.setTitle(((Element) n).getElementsByTagName("Title").item(0).getTextContent()); if (((Element) n).getElementsByTagName("ShippingServiceCost").item(0) != null) p.setShippingservicecost(new Double(((Element) n) .getElementsByTagName("ShippingServiceCost").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ShippingType").item(0) != null) p.setShippingtype(((Element) n).getElementsByTagName("ShippingType").item(0) .getTextContent()); if (((Element) n).getElementsByTagName("WatchCount").item(0) != null) p.setWatchcount(new Integer( ((Element) n).getElementsByTagName("WatchCount").item(0).getTextContent())); if (((Element) n).getElementsByTagName("ListedShippingServiceCost").item(0) != null) p.setListedshippingservicecost( new Double(((Element) n).getElementsByTagName("ListedShippingServiceCost") .item(0).getTextContent())); try { db.insert(p); } catch (Exception e) { db.update(p); } } } } Ventana.crear(xml); } else System.exit(0); } }
From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * /*from ww w. j av a2 s . c o m*/ * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Account Management"); _log.info("Please choose:"); //_log.info("list - list registered accounts"); _log.info("reg - register a new account"); _log.info("rem - remove a registered account"); _log.info("prom - promote a registered account"); _log.info("dem - demote a registered account"); _log.info("ban - ban a registered account"); _log.info("unban - unban a registered account"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2AccountManager acm = new L2AccountManager(); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); Connection con = null; switch (acm.getState()) { case USER_NAME: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (!rs.next()) { acm.setUser(line); _log.info("Desired password:"); acm.setState(ManagerState.PASSWORD); } else { _log.info("User name already in use."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case PASSWORD: try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] pass = sha.digest(line.getBytes("US-ASCII")); acm.setPass(HexUtil.bytesToHexString(pass)); } catch (NoSuchAlgorithmException e) { _log.fatal("SHA1 is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } catch (UnsupportedEncodingException e) { _log.fatal("ASCII is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } _log.info("Super user: [y/n]"); acm.setState(ManagerState.SUPERUSER); break; case SUPERUSER: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') acm.setSuper(true); else if (line.charAt(0) == 'n') acm.setSuper(false); else throw new IllegalArgumentException("Invalid choice."); _log.info("Date of birth: [yyyy-mm-dd]"); acm.setState(ManagerState.DOB); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; case DOB: try { Date d = Date.valueOf(line); if (d.after(new Date(System.currentTimeMillis()))) throw new IllegalArgumentException("Future date specified."); acm.setDob(d); _log.info("Ban reason ID or nothing:"); acm.setState(ManagerState.SUSPENDED); } catch (IllegalArgumentException e) { _log.info("[yyyy-mm-dd] in the past:"); } break; case SUSPENDED: try { if (line.length() > 0) { int id = Integer.parseInt(line); acm.setBan(L2BanReason.getById(id)); } else acm.setBan(null); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)"); ps.setString(1, acm.getUser()); ps.setString(2, acm.getPass()); ps.setBoolean(3, acm.isSuper()); ps.setDate(4, acm.getDob()); L2BanReason lbr = acm.getBan(); if (lbr == null) ps.setNull(5, Types.INTEGER); else ps.setInt(5, lbr.getId()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been registered."); ps.close(); } catch (SQLException e) { _log.error("Could not register an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); } catch (NumberFormatException e) { _log.info("Ban reason ID or nothing:"); } break; case REMOVE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?"); ps.setString(1, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been removed."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not remove an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case PROMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, true); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been promoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not promote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case DEMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, false); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been demoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case UNBAN: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setNull(1, Types.INTEGER); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been unbanned."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case BAN: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (rs.next()) { acm.setUser(line); _log.info("Ban reason ID:"); acm.setState(ManagerState.REASON); } else { _log.info("Account does not exist."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case REASON: try { int ban = Integer.parseInt(line); con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setInt(1, ban); ps.setString(2, acm.getUser()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been banned."); ps.close(); } catch (NumberFormatException e) { _log.info("Ban reason ID:"); } catch (SQLException e) { _log.error("Could not ban an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; default: line = line.toLowerCase(); if (line.equals("reg")) { _log.info("Desired user name:"); acm.setState(ManagerState.USER_NAME); } else if (line.equals("rem")) { _log.info("User name:"); acm.setState(ManagerState.REMOVE); } else if (line.equals("prom")) { _log.info("User name:"); acm.setState(ManagerState.PROMOTE); } else if (line.equals("dem")) { _log.info("User name:"); acm.setState(ManagerState.DEMOTE); } else if (line.equals("unban")) { _log.info("User name:"); acm.setState(ManagerState.UNBAN); } else if (line.equals("ban")) { _log.info("User name:"); acm.setState(ManagerState.BAN); } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
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>"; ///* w w w . j av a2s . c om*/ // 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
private static int getBytesLength(String msg) { return msg.getBytes(Charset.forName("GB2312")).length; }
From source file:Main.java
public static byte[] StringToByte(String s) { byte[] b = s.getBytes(Charset.forName("US-ASCII")); return b;/*from w w w.j a va2 s . c o m*/ }
From source file:Main.java
private static byte[] encodeUTF8(String string) { return string.getBytes(UTF8_CHARSET); }
From source file:Main.java
public static byte[] stringToByte(String string) { return string.getBytes(Charset.defaultCharset()); }
From source file:Main.java
@SuppressLint("NewApi") private static int getBytesLength(String msg) { return msg.getBytes(Charset.forName("GB2312")).length; }