private String spejdPost(JsonObject jo) { @SuppressWarnings({"resource"}) DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse resp; HttpPost httpPost = new HttpPost(SPEJD_SERVICE_POST); httpPost.addHeader("Content-Type", "application/json"); StringEntity reqEntity = null; try { reqEntity = new StringEntity(jo.toString()); } catch (UnsupportedEncodingException e) { System.out.println(e.toString()); } assert reqEntity != null; httpPost.setEntity(reqEntity); try { resp = httpclient.execute(httpPost); return EntityUtils.toString(resp.getEntity()); } catch (IOException e) { e.printStackTrace(); } return null; }
/** @param args */ public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java " + ATBCorrector.class.getName() + " filename\n"); System.exit(-1); } TreeTransformer tt = new ATBCorrector(); File f = new File(args[0]); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); TreeReaderFactory trf = new ArabicTreeReaderFactory.ArabicRawTreeReaderFactory(); TreeReader tr = trf.newTreeReader(br); int nTrees = 0; for (Tree t; (t = tr.readTree()) != null; nTrees++) { Tree fixedT = tt.transformTree(t); System.out.println(fixedT.toString()); } tr.close(); System.err.printf("Wrote %d trees%n", nTrees); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException { InputStream input = new ByteArrayInputStream(xml.getBytes()); ByteArrayOutputStream output = new ByteArrayOutputStream(); JsonXMLConfig config = new JsonXMLConfigBuilder() .autoArray(true) .autoPrimitive(true) .prettyPrint(formatted) .build(); try { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input); XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output); writer.add(reader); reader.close(); writer.close(); try { return output.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e.getMessage()); } } finally { // dp nothing } }
private void saveCurrent() { PrintWriter writer = null; try { writer = new PrintWriter("config.txt", "UTF-8"); writer.println("PhoneNumbers:"); for (String s : Main.getEmails()) { writer.println(s); } writer.println("Items:"); for (Item s : Main.getItems()) { writer.println(s.getName() + "," + s.getWebsite()); } results.setText("Current settings have been saved sucessfully."); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } writer.close(); }
private String getStrToSign(HttpServletRequest request) { try { this.body = GetPostBody( request.getInputStream(), Integer.parseInt(request.getHeader("content-length"))); } catch (IOException e) { log.error(e.getMessage()); return null; } String queryString = request.getQueryString(); String uri = request.getRequestURI(); String decodeUri; try { decodeUri = java.net.URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); return null; } String authStr = decodeUri; if (queryString != null && !queryString.equals("")) { authStr += "?" + queryString; } authStr += "\n" + this.body; return authStr; }
/** * Get请求 * * @param url * @param params * @return */ public static String get(String url, List<NameValuePair> params) { String body = null; try { // Get请求 HttpGet httpget = new HttpGet(url); // 设置参数 String str = EntityUtils.toString(new UrlEncodedFormEntity(params)); httpget.setURI(new URI(httpget.getURI().toString() + "?" + str)); // 发送请求 HttpResponse httpresponse = httpClient.execute(httpget); // 获取返回数据 HttpEntity entity = httpresponse.getEntity(); body = EntityUtils.toString(entity); if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return body; }
public static String getAddressByIP(String ip) { try { String js = visitWeb("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip); JsonParser jsonParser = new JsonParser(); js = js.trim(); JsonObject jo = jsonParser.parse(js.substring(21, js.length() - 1)).getAsJsonObject(); String province = ""; String city = ""; try { // 获取 省、市 province = jo.get("province") == null ? "" : URLDecoder.decode(jo.get("province").toString(), "UTF-8"); city = jo.get("city") == null ? "" : URLDecoder.decode(jo.get("city").toString(), "UTF-8"); // 省为空用国家代替 if (StringUtils.isEmpty(province)) { province = jo.get("country") == null ? "" : URLDecoder.decode(jo.get("country").toString(), "UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return (province.equals("") || province.equals(city)) ? city : province + " " + city; } catch (Exception e) { e.printStackTrace(); return ""; } }
public SummaryResultsParser(String path) { this(); try { parseSummaryFile(path); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
static void uIDfill(String file, OptionsFiller filler) { InputStream assetsDB = null; try { assetsDB = getContext().getAssets().open(file); } catch (IOException e) { e.printStackTrace(); return; } BufferedReader buf = null; try { buf = new BufferedReader(new InputStreamReader(assetsDB, "UTF-8")); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } try { while (buf.ready()) { String str = buf.readLine(); /* * Test for BOM */ if (str.length() > 0 && (int) str.charAt(0) == 65279) { str = str.substring(1); } int spaceIndex = str.indexOf(' '); if (spaceIndex < 0) { break; } int index1 = str.indexOf(':'); int index2 = str.lastIndexOf(':', spaceIndex); if (index2 == index1) { filler.fill( new UniqueID(str.substring(0, spaceIndex)).hashCode(), str.substring(spaceIndex + 1), null); } else { filler.fill( new UniqueID(str.substring(0, index2)).hashCode(), str.substring(spaceIndex + 1), str.substring(index2 + 1, spaceIndex)); } } } catch (IOException e1) { e1.printStackTrace(); } try { assetsDB.close(); } catch (IOException e) { e.printStackTrace(); } }
public void flush() { try { m_txtArea.append(new String(buffer.toByteArray(), encoding)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } buffer.reset(); }
/** * This method will set the content-string to be the content of this Information object. * Internally, the content will be written into a newly created ByteArrayOutputStream. Calling * this method will erase previously set content on this object. The content-string will be read * as UTF8. * * @param content The content to be set. */ @Override public void setContent(String content) { try { setContent(content.getBytes(KEPMessage.ENCODING)); } catch (UnsupportedEncodingException e) { // FIXME: Catch unknown encoding exception?! e.printStackTrace(); } }
private String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException unsupportedEncodingException) { throw new HipChatNotificationPluginException( "URL encoding error: [" + unsupportedEncodingException.getMessage() + "].", unsupportedEncodingException); } }
/** {@inheritDoc} */ public synchronized Result createConference(String creator, String mucRoomName) { Conference conference = conferenceMap.get(mucRoomName); if (conference == null) { // Create new conference try { ApiResult result = api.createNewConference(creator, mucRoomName); if (result.getError() == null) { conference = result.getConference(); conferenceMap.put(mucRoomName, conference); } else if (result.getStatusCode() == 409 && result.getError().getConflictId() != null) { Number conflictId = result.getError().getConflictId(); // Conference already exists(check if we have it locally) conference = findConferenceForId(conflictId); logger.info("Conference '" + mucRoomName + "' already " + "allocated, id: " + conflictId); // do GET conflict conference if (conference == null) { ApiResult getResult = api.getConference(conflictId); if (getResult.getConference() != null) { conference = getResult.getConference(); // Fill full room name as it is not transferred // over REST API conference.setMucRoomName(mucRoomName); conferenceMap.put(mucRoomName, conference); } else { logger.error("API error: " + result); return new Result(RESULT_INTERNAL_ERROR, result.getError().getMessage()); } } } else { // Other error logger.error("API error: " + result); return new Result(RESULT_INTERNAL_ERROR, result.getError().getMessage()); } } catch (FaultTolerantRESTRequest.RetryExhaustedException e) { logger.error(e, e); return new Result(RESULT_INTERNAL_ERROR, e.getMessage()); } catch (UnsupportedEncodingException e) { logger.error(e, e); return new Result(RESULT_INTERNAL_ERROR, e.getMessage()); } } // Verify owner == creator if (creator.equals(conference.getOwner())) { return new Result(RESULT_OK); } else { logger.error( "Room " + mucRoomName + ", conflict : " + creator + " != " + conference.getOwner()); return new Result(RESULT_CONFLICT); } }
public XMLCleanup() { bytes = new ByteArrayOutputStream(); try { out = new OutputStreamWriter(bytes, "UTF8"); } catch (UnsupportedEncodingException e) { LOG.warn("XMLCleanup() unsupported encoding: " + e.getMessage()); } }
private void parseAuth() { errReceiver.info( new SAXParseException(WscompileMessages.WSIMPORT_READING_AUTH_FILE(authFile), null)); BufferedReader in; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(authFile), "UTF-8")); } catch (UnsupportedEncodingException e) { error(new SAXParseException(e.getMessage(), null)); return; } catch (FileNotFoundException e) { error( new SAXParseException( WscompileMessages.WSIMPORT_AUTH_FILE_NOT_FOUND(authFile, defaultAuthfile), null, e)); return; } String text; LocatorImpl locator = new LocatorImpl(); try { int lineno = 1; locator.setSystemId(authFile.getCanonicalPath()); while ((text = in.readLine()) != null) { locator.setLineNumber(lineno++); try { URL url = new URL(text); String authinfo = url.getUserInfo(); if (authinfo != null) { int i = authinfo.indexOf(':'); if (i >= 0) { String user = authinfo.substring(0, i); String password = authinfo.substring(i + 1); authInfo.add(new AuthInfo(new URL(text), user, password)); } else { error( new SAXParseException( WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(url), locator)); } } else { error( new SAXParseException(WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(url), locator)); } } catch (NumberFormatException e) { error(new SAXParseException(WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(text), locator)); } } in.close(); } catch (IOException e) { error( new SAXParseException( WscompileMessages.WSIMPORT_FAILED_TO_PARSE(authFile, e.getMessage()), locator)); } }
private void extractInfo(File filename) { checkpoint = false; String line; try { ArrayList<String> order = new ArrayList<String>(); BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "iso-8859-1")); while ((line = input.readLine()) != null) { if (line.equalsIgnoreCase("hämtas")) checkpoint = true; if (checkpoint) order.add(new String(line)); } // printList(order); int quant = Integer.parseInt(order.get(2)); int rows = 9; int outer = (quant * rows); double price; double total; // DecimalFormat decimal = (DecimalFormat) format; Number number; for (int i = 4; i <= outer; i += 9) { Data d = new Data( order.get(i + 1), order.get(i + 3), order.get(i + 4), order.get(i + 5), order.get(i + 7)); dataList.add(d); /* try { System.out.println(order.get(i+5)); number = format.parse(order.get(i+5)); System.out.println("Number is " + number); price = number.doubleValue(); System.out.println("Price is " + price); number = format.parse(order.get(i+7)); total = number.doubleValue(); Data d = new Data(order.get(i), Integer.parseInt(order.get(i+1)), Integer.parseInt(order.get(i+2)), order.get(i+3), order.get(i+4), price, total); dataList.add(d); } catch (ParseException numExcep) { numExcep.printStackTrace(); System.exit(1); } **/ } // printDataList(dataList); } catch (FileNotFoundException found) { found.printStackTrace(); System.exit(1); } catch (UnsupportedEncodingException encode) { encode.printStackTrace(); System.exit(1); } catch (IOException ioexcep) { ioexcep.printStackTrace(); System.exit(1); } }
/** * 访问服务器环境 * * @param names 参数名字 * @param values 参数值 */ public static void visitEnvServerByParameters(String[] names, String[] values) { int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values)); String[] segs = new String[len]; for (int i = 0; i < len; i++) { try { // 设计器里面据说为了改什么界面统一, 把分隔符统一用File.separator, 意味着在windows里面报表路径变成了\ // 以前的超链, 以及预览url什么的都是/, 产品组的意思就是用到的地方替换下, 真恶心. String value = values[i].replaceAll("\\\\", "/"); segs[i] = URLEncoder.encode(CodeUtils.cjkEncode(names[i]), EncodeConstants.ENCODING_UTF_8) + "=" + URLEncoder.encode(CodeUtils.cjkEncode(value), "UTF-8"); } catch (UnsupportedEncodingException e) { FRContext.getLogger().error(e.getMessage(), e); } } String postfixOfUri = (segs.length > 0 ? "?" + StableUtils.join(segs, "&") : StringUtils.EMPTY); if (FRContext.getCurrentEnv() instanceof RemoteEnv) { try { if (Utils.isEmbeddedParameter(postfixOfUri)) { String time = Calendar.getInstance().getTime().toString().replaceAll(" ", ""); boolean isUserPrivilege = ((RemoteEnv) FRContext.getCurrentEnv()).writePrivilegeMap(time, postfixOfUri); postfixOfUri = isUserPrivilege ? postfixOfUri + "&fr_check_url=" + time + "&id=" + FRContext.getCurrentEnv().getUserID() : postfixOfUri; } String urlPath = getWebBrowserPath(); Desktop.getDesktop().browse(new URI(urlPath + postfixOfUri)); } catch (Exception e) { FRContext.getLogger().error("cannot open the url Successful", e); } } else { try { String web = GeneralContext.getCurrentAppNameOfEnv(); String url = "http://localhost:" + DesignerEnvManager.getEnvManager().getJettyServerPort() + "/" + web + "/" + ConfigManager.getProviderInstance().getServletMapping() + postfixOfUri; StartServer.browerURLWithLocalEnv(url); } catch (Throwable e) { // } } }
/** * Sets a JSON String as a request entity. * * @param httpRequest The request to set entity. * @param json The JSON String to set. */ protected void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) { try { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpRequest.setEntity(entity); } catch (UnsupportedEncodingException e) { log.error("Error setting request data. " + e.getMessage()); throw new IllegalArgumentException(e); } }
private void refreshContent() { if (dirty) { try { this.content = URLEncodedUtils.format(params, charset).getBytes(charset); } catch (UnsupportedEncodingException e) { LogUtils.e(e.getMessage(), e); } dirty = false; } }
public FileConfiguration getMensagensConfig() { if (mensagens == null) { try { reloadMensagensConfig(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return mensagens; }
public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException { String realm = "/"; String data = null; ErrorInfo ei = null; InputStreamReader iss = null; BufferedReader br = null; HttpURLConnection urlc = null; InputStream inputStream = null; try { data = "policynames=" + URLEncoder.encode(polname, "UTF-8") + "&realm=" + URLEncoder.encode(realm, "UTF-8") + "&submit=" + URLEncoder.encode("Submit", "UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } if (data != null) { try { r.Connect(new URL(url + ssoadm_list)); } catch (MalformedURLException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } urlc = (HttpURLConnection) r.c; urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\""); r.Send(urlc, data); String answer = null; int status = 0; inputStream = urlc.getInputStream(); iss = new InputStreamReader(inputStream); br = new BufferedReader(iss); answer = BrToString(br); status = urlc.getResponseCode(); if (answer != null) { ei = new ErrorInfo(answer, status); } br.close(); iss.close(); inputStream.close(); urlc.disconnect(); } return ei; }
public static byte[] func_75895_a(String p_75895_0_, PublicKey p_75895_1_, SecretKey p_75895_2_) { try { return func_75893_a( "SHA-1", new byte[][] { p_75895_0_.getBytes("ISO_8859_1"), p_75895_2_.getEncoded(), p_75895_1_.getEncoded() }); } catch (UnsupportedEncodingException unsupportedencodingexception) { unsupportedencodingexception.printStackTrace(); } return null; }
public static ResourceBundle loadLocale(String localeString) { JarFile jarFile; try { jarFile = new JarFile(MyPetPlugin.getPlugin().getFile()); } catch (IOException ignored) { return null; } ResourceBundle newLocale = null; try { JarEntry jarEntry = jarFile.getJarEntry("locale/MyPet_" + localeString + ".properties"); if (jarEntry != null) { java.util.ResourceBundle defaultBundle = new PropertyResourceBundle( new InputStreamReader(jarFile.getInputStream(jarEntry), "UTF-8")); newLocale = new ResourceBundle(defaultBundle); } else { throw new IOException(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); DebugLogger.printThrowable(e); } catch (IOException ignored) { } File localeFile = new File( MyPetPlugin.getPlugin().getDataFolder() + File.separator + "locale" + File.separator + "MyPet_" + localeString + ".properties"); if (localeFile.exists()) { if (newLocale == null) { newLocale = new ResourceBundle(); } try { java.util.ResourceBundle optionalBundle = new PropertyResourceBundle( new InputStreamReader(new FileInputStream(localeFile), "UTF-8")); newLocale.addExtensionBundle(optionalBundle); } catch (IOException e) { e.printStackTrace(); DebugLogger.printThrowable(e); } } return newLocale; }
public static void save_file(File file) { try { save_sifp(file); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public String encodeQingcloud(String data) { data = data.replace("+", "-"); data = data.replace("/", "_"); while (data.endsWith("=")) { data = data.substring(0, data.length() - 1); } String encodeData = null; try { encodeData = new String(Base64.encodeBase64(encodeData.getBytes("UTF-8")), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodeData; }
@Override protected PaymentType doInBackground(String... params) { PaymentType paymentType = null; InputStream inputStream = null; HttpEntity httpEntity = null; try { httpEntity = Response.getResponse(params[0]).getEntity(); inputStream = httpEntity.getContent(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } inputStream.close(); result = builder.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { JSONObject jsonObject = new JSONObject(result); JSONObject paymentTypeObject = jsonObject.getJSONObject("paymentType"); int id = paymentTypeObject.getInt("id"); int informationTypeId = paymentTypeObject.getInt("informationTypeId"); String time = paymentTypeObject.getString("time"); double price = paymentTypeObject.getDouble("price"); paymentType = new PaymentType(id, informationTypeId, time, price); } catch (JSONException e) { e.printStackTrace(); } return paymentType; }
public ErrorInfo doLogin() throws IOException, RestException { String data = null; ErrorInfo ei = null; InputStreamReader iss = null; BufferedReader br = null; HttpURLConnection urlc = null; InputStream inputStream = null; try { data = "username="******"UTF-8") + "&password="******"UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } if (data != null) { try { r.Connect(new URL(url + authenticate)); } catch (MalformedURLException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } urlc = (HttpURLConnection) r.c; r.Send(urlc, data); String answer = null; int status = 0; inputStream = urlc.getInputStream(); iss = new InputStreamReader(inputStream); br = new BufferedReader(iss); answer = BrToString(br); status = urlc.getResponseCode(); if (answer != null) { ei = new ErrorInfo(answer, status); } br.close(); iss.close(); inputStream.close(); urlc.disconnect(); } return ei; }
public void parsePyPIList(final List<String> packages, final PyPackageService service) { myPackageNames = null; for (String pyPackage : packages) { try { final Matcher matcher = PYPI_PATTERN.matcher(URLDecoder.decode(pyPackage, "UTF-8")); if (matcher.find()) { final String packageName = matcher.group(1); final String packageVersion = matcher.group(2); if (!packageName.contains(" ")) service.PY_PACKAGES.put(packageName, packageVersion); } } catch (UnsupportedEncodingException e) { LOG.warn(e.getMessage()); } } }
public void printString(String output) { PrintWriter printer; try { printer = new PrintWriter("botOutput.txt", "UTF-8"); printer.write(output); printer.close(); /* for (String word : individual.toString().split(" ")) { printer.write(word); }*/ } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
private static void createFile(List<String> palabras, String pathToWords) { PrintWriter writer = null; try { writer = new PrintWriter(pathToWords, "UTF-8"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } for (String temp : palabras) { writer.println(temp); } writer.close(); }