java.io.UnsupportedEncodingException Java Examples
The following examples show how to use
java.io.UnsupportedEncodingException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RevenueCalculatorBean.java From development with Apache License 2.0 | 6 votes |
private void serializeBillingDetails(BillingResult billingResult, BillingDetailsType billingDetails) { try { final JAXBContext context = JAXBContext .newInstance(BillingdataType.class); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final Marshaller marshaller = context.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", Boolean.FALSE); final BillingdataType billingdataType = new BillingdataType(); billingdataType.getBillingDetails().add(billingDetails); marshaller.marshal(factory.createBillingdata(billingdataType), out); final String xml = new String(out.toByteArray(), "UTF-8"); billingResult.setResultXML(xml.substring( xml.indexOf("<Billingdata>") + 13, xml.indexOf("</Billingdata>")).trim()); billingResult.setGrossAmount(billingDetails.getOverallCosts() .getGrossAmount()); billingResult.setNetAmount(billingDetails.getOverallCosts() .getNetAmount()); } catch (JAXBException | UnsupportedEncodingException ex) { throw new BillingRunFailed(ex); } }
Example #2
Source File: DockerAction.java From netbeans with Apache License 2.0 | 6 votes |
public void rename(DockerContainer container, String name) throws DockerException { Parameters.notNull("name", name); try { doPostRequest("/containers/" + container.getId() + "/rename?name=" + HttpUtils.encodeParameter(name), false, Collections.singleton(HttpURLConnection.HTTP_NO_CONTENT)); long time = System.currentTimeMillis() / 1000; // XXX we send it as older API does not have the commit event if (emitEvents) { instance.getEventBus().sendEvent( new DockerEvent(instance, DockerEvent.Status.RENAME, container.getId(), container.getId(), time)); } } catch (UnsupportedEncodingException ex) { throw new DockerException(ex); } }
Example #3
Source File: Utility.java From iBeebo with GNU General Public License v3.0 | 6 votes |
public static Bundle decodeUrl(String s) { Bundle params = new Bundle(); if (s != null) { String array[] = s.split("&"); for (String parameter : array) { String v[] = parameter.split("="); try { params.putString(URLDecoder.decode(v[0], "UTF-8"), URLDecoder.decode(v[1], "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } return params; }
Example #4
Source File: ClientSystemFileCommands.java From p4ic4idea with Apache License 2.0 | 6 votes |
public Map<String, Object> convertFileDataMap(Map<String, Object> map, Charset charset, boolean isUnicodeServer) { if (map != null) { String dataString = null; byte[] dataBytes = null; try { dataBytes = (byte[]) map.get(RpcFunctionMapKey.DATA); } catch (Throwable thr) { Log.exception(thr); } if (dataBytes != null) { try { dataString = new String(dataBytes, charset == null ? RpcConnection.NON_UNICODE_SERVER_CHARSET_NAME : (isUnicodeServer ? CharsetDefs.UTF8_NAME : charset.name())); map.put(RpcFunctionMapKey.DATA, dataString); } catch (UnsupportedEncodingException e) { Log.exception(e); } } } return map; }
Example #5
Source File: RichEditor.java From imsdk-android with MIT License | 6 votes |
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) { String decode; try { decode = URLDecoder.decode(url, "UTF-8"); } catch (UnsupportedEncodingException e) { // No handling return false; } if (TextUtils.indexOf(url, CALLBACK_SCHEME) == 0) { callback(decode); return true; } else if (TextUtils.indexOf(url, STATE_SCHEME) == 0) { stateCheck(decode); return true; } return super.shouldOverrideUrlLoading(view, url); }
Example #6
Source File: Encoder.java From barcodescanner-lib-aar with MIT License | 6 votes |
private static boolean isOnlyDoubleByteKanji(String content) { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException ignored) { return false; } int length = bytes.length; if (length % 2 != 0) { return false; } for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false; } } return true; }
Example #7
Source File: HttpHeaderTransport.java From tracee with BSD 3-Clause "New" or "Revised" License | 6 votes |
Map<String, String> parse(String serialized) { final StringTokenizer pairTokenizer = new StringTokenizer(serialized.trim(), ","); final Map<String, String> context = new HashMap<>(); while (pairTokenizer.hasMoreTokens()) { final String pairStr = pairTokenizer.nextToken(); final String[] keyValuePair = pairStr.split("="); if (keyValuePair.length != 2) { continue; } try { final String key = URLDecoder.decode(keyValuePair[0], ENCODING_CHARSET); final String value = URLDecoder.decode(keyValuePair[1], ENCODING_CHARSET); context.put(key, value); } catch (UnsupportedEncodingException e) { LOGGER.error("Charset not found", e); } } return context; }
Example #8
Source File: DemonstrationGradeEncryptionServiceImpl.java From rice with Educational Community License v2.0 | 6 votes |
public String decrypt(String ciphertext) throws GeneralSecurityException { checkEnabled(); if (StringUtils.isBlank(ciphertext)) { return ""; } // Initialize the same cipher for decryption Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, desKey); try { // un-Base64 encode the encrypted data byte[] encryptedData = Base64.decodeBase64(ciphertext.getBytes(CHARSET)); // Decrypt the ciphertext byte[] cleartext1 = cipher.doFinal(encryptedData); return new String(cleartext1, CHARSET); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example #9
Source File: LdapURL.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
static String toUrlString(String host, int port, String dn, boolean useSsl) { try { String h = (host != null) ? host : ""; if ((h.indexOf(':') != -1) && (h.charAt(0) != '[')) { h = "[" + h + "]"; // IPv6 literal } String p = (port != -1) ? (":" + port) : ""; String d = (dn != null) ? ("/" + UrlUtil.encode(dn, "UTF8")) : ""; return useSsl ? "ldaps://" + h + p + d : "ldap://" + h + p + d; } catch (UnsupportedEncodingException e) { // UTF8 should always be supported throw new IllegalStateException("UTF-8 encoding unavailable"); } }
Example #10
Source File: AESEncrypter.java From development with Apache License 2.0 | 6 votes |
/** * Encrypts a given string based on a shared secret. * * @param text * the text to encrypt * @return the iv and encrypted text as Base64 separated with ':'. * @throws GeneralSecurityException * on any problem during encryption */ public static String encrypt(String text) throws GeneralSecurityException { if (text == null) { return null; } byte[] decrypted; try { decrypted = text.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byte[] iv = new byte[IV_BYTES]; new SecureRandom().nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec); byte[] encrypted = cipher.doFinal(decrypted); return new String(Base64.encodeBase64(iv)) + ":" + new String(Base64.encodeBase64(encrypted)); }
Example #11
Source File: Id3Decoder.java From TelePlus-Android with GNU General Public License v2.0 | 5 votes |
private static UrlLinkFrame decodeUrlLinkFrame(ParsableByteArray id3Data, int frameSize, String id) throws UnsupportedEncodingException { byte[] data = new byte[frameSize]; id3Data.readBytes(data, 0, frameSize); int urlEndIndex = indexOfZeroByte(data, 0); String url = new String(data, 0, urlEndIndex, "ISO-8859-1"); return new UrlLinkFrame(id, null, url); }
Example #12
Source File: Perf.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * convert string to an array of UTF-8 bytes */ private static byte[] getBytes(String s) { byte[] bytes = null; try { bytes = s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // ignore, UTF-8 encoding is always known } return bytes; }
Example #13
Source File: LineEncoder.java From JavaTutorial with Apache License 2.0 | 5 votes |
@Override public ByteBuffer encode(Object source) { String line = (String) source; try { ByteBuffer buffer = ByteBuffer.wrap(line.getBytes(Constant.CHARSET_UTF8)); return buffer; } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "将响应数据转换成ByteBuffer出错", e); } return null; }
Example #14
Source File: ZAProxy.java From zaproxy-plugin with MIT License | 5 votes |
/** * set up form based authentication method for the created context * @param listener the listener to display log during the job execution in jenkins * @param zapClientAPI the client API to use ZAP API methods * @param loggedInIdicator indication for know its logged in * @param usernameParameter parameter define in passing username * @param passwordParameter parameter that define in passing password for the user * @param extraPostData other post data than credentials * @param contextId id of the creted context * @param loginUrl login page url * @throws ClientApiException * @throws UnsupportedEncodingException */ private void setUpFormBasedAuthenticationMethod(BuildListener listener, ClientApi zapClientAPI, String loggedInIndicator, String usernameParameter, String passwordParameter,String extraPostData, String contextId, String loginUrl) throws ClientApiException, UnsupportedEncodingException{ String loginRequestData = usernameParameter+"={%username%}&"+passwordParameter+"={%password%}&"+extraPostData; // set form based authentication method // Prepare the configuration in a format similar to how URL parameters are formed. This // means that any value we add for the configuration values has to be URL encoded. StringBuilder formBasedConfig = new StringBuilder(); formBasedConfig.append("loginUrl=").append(URLEncoder.encode(loginUrl, "UTF-8")); formBasedConfig.append("&loginRequestData=").append(URLEncoder.encode(loginRequestData, "UTF-8")); zapClientAPI.authentication.setAuthenticationMethod(API_KEY, contextId, "formBasedAuthentication",formBasedConfig.toString()); listener.getLogger().println("Authentication config: " + zapClientAPI.authentication.getAuthenticationMethod(contextId).toString(0)); //end set auth method listener.getLogger().println("Form Based Authentication added to context"); //add logged in idicator if (!loggedInIndicator.equals("")) { zapClientAPI.authentication.setLoggedInIndicator(API_KEY, contextId, loggedInIndicator); listener.getLogger().println("Logged in indicator "+loggedInIndicator+" added to context "); } }
Example #15
Source File: PerfDataType.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
private PerfDataType(String name, String c, int size) { this.name = name; this.size = size; try { byte[] b = c.getBytes("UTF-8"); this.value = b[0]; } catch (UnsupportedEncodingException e) { // ignore, "UTF-8" is always a known encoding throw new InternalError("Unknown encoding", e); } }
Example #16
Source File: JsonStorageService.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * Escapes all invalid url characters and strips the maximum length to 127 to be used as a file name * * @param s the string to be escaped * @return url-encoded string or the original string if UTF-8 is not supported on the system */ protected String urlEscapeUnwantedChars(String s) { String result; try { result = URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.warn("Encoding UTF-8 is not supported, might generate invalid filenames."); result = s; } int length = Math.min(result.length(), MAX_FILENAME_LENGTH); return result.substring(0, length); }
Example #17
Source File: ToHTMLStream.java From jdk1.8-source-analysis with Apache License 2.0 | 5 votes |
/** * Initialize the serializer with the specified output stream and output * format. Must be called before calling any of the serialize methods. * * @param output The output stream to use * @param format The output format * @throws UnsupportedEncodingException The encoding specified in the * output format is not supported */ protected synchronized void init(OutputStream output, Properties format) throws UnsupportedEncodingException { if (null == format) { format = OutputPropertiesFactory.getDefaultMethodProperties(Method.HTML); } super.init(output,format, false); }
Example #18
Source File: WebTargets.java From pulsar with Apache License 2.0 | 5 votes |
static WebTarget addParts(WebTarget target, String[] parts) { if (parts != null && parts.length > 0) { for (String part : parts) { String encode; try { encode = URLEncoder.encode(part, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { log.error("{} is Unknown exception - [{}]", StandardCharsets.UTF_8.toString(), e); encode = part; } target = target.path(encode); } } return target; }
Example #19
Source File: HttpRequestFactory.java From sana.mobile with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static HttpPost getPostRequest(URI uri, List<NameValuePair> postData) throws IllegalArgumentException { try { HttpPost post = new HttpPost(uri); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8"); post.setEntity(entity); return post; } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } }
Example #20
Source File: DevicesApi.java From freeiot-android with MIT License | 5 votes |
/** * device unbinding (/v1/devices/{identifier}/unbinding) * @param context * @param accessToken * @param responseHandler */ public static void deviceUnbinding(Context context, String accessToken, String identifier, AsyncHttpResponseHandler responseHandler) { List<Header> headerList = new ArrayList<Header>(); headerList.add(new BasicHeader(ApiKey.HeadKey.ACCESS_TOKEN, accessToken)); try { post(context, String.format(getApiServerUrl() + DEVICE_UNBINDING, identifier), headerList, null, responseHandler); } catch (UnsupportedEncodingException e) { e.printStackTrace(); responseHandler.onFailure(INNER_ERROR_CODE, null, null, e); } }
Example #21
Source File: UnicodeRegex.java From j2objc with Apache License 2.0 | 5 votes |
/** * Utility for loading lines from a UTF8 file. * @param result The result of the appended lines. * @param inputStream The input stream. * @param encoding if null, then UTF-8 * @return filled list * @throws IOException If there were problems opening the input stream for reading. */ public static List<String> appendLines(List<String> result, InputStream inputStream, String encoding) throws UnsupportedEncodingException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, encoding == null ? "UTF-8" : encoding)); while (true) { String line = in.readLine(); if (line == null) break; result.add(line); } return result; }
Example #22
Source File: FileUrlServlet.java From spiracle with Apache License 2.0 | 5 votes |
private String read(InputStream inStream) throws IOException, UnsupportedEncodingException { List<Byte> byteList = new ArrayList<Byte>(); int streamBuf = inStream.read(); while(streamBuf != -1) { byteList.add(new Byte((byte) streamBuf)); streamBuf = inStream.read(); } byte [] byteArr = new byte[byteList.size()]; for(int i = 0; i < byteList.size(); i++) { byteArr[i] = byteList.get(i).byteValue(); } return new String(byteArr, "UTF-8"); }
Example #23
Source File: OAuth2ClientController.java From hsweb-framework with Apache License 2.0 | 5 votes |
@GetMapping("/boot/{serverId}") @ApiOperation("跳转至OAuth2.0服务授权页面") public RedirectView boot(@PathVariable String serverId, @RequestParam(defaultValue = "/") String redirect, HttpServletRequest request, HttpSession session) throws UnsupportedEncodingException { OAuth2ServerConfigEntity entity = oAuth2ServerConfigService.selectByPk(serverId); if (entity == null) { return new RedirectView("/401.html"); } String callback = WebUtil.getBasePath(request) .concat("oauth2/callback/") .concat(serverId).concat("/?redirect=") .concat(URLEncoder.encode(redirect, "UTF-8")); RedirectView view = new RedirectView(entity.getRealUrl(entity.getAuthUrl())); view.addStaticAttribute(OAuth2Constants.response_type, "code"); view.addStaticAttribute(OAuth2Constants.state, requestState(session).getResult()); view.addStaticAttribute(OAuth2Constants.client_id, entity.getClientId()); view.addStaticAttribute(OAuth2Constants.redirect_uri, callback); return view; }
Example #24
Source File: DocDownloadAction.java From scada with MIT License | 5 votes |
public void setFileName(String fileName) { try { fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //System.out.println("----"+fileName); this.fileName = fileName; }
Example #25
Source File: HierarchicalUriComponents.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public PathComponent encode(String encoding) throws UnsupportedEncodingException { List<String> pathSegments = getPathSegments(); List<String> encodedPathSegments = new ArrayList<String>(pathSegments.size()); for (String pathSegment : pathSegments) { String encodedPathSegment = encodeUriComponent(pathSegment, encoding, Type.PATH_SEGMENT); encodedPathSegments.add(encodedPathSegment); } return new PathSegmentComponent(encodedPathSegments); }
Example #26
Source File: SlackRequestParserTest.java From java-slack-sdk with MIT License | 5 votes |
@Test public void testMessageShortcutPayload() throws UnsupportedEncodingException { MessageShortcutPayload payload = new MessageShortcutPayload(); MessageShortcutPayload.Team team = new MessageShortcutPayload.Team(); team.setId("T123"); payload.setTeam(team); MessageShortcutPayload.User user = new MessageShortcutPayload.User(); user.setId("U123"); payload.setUser(user); SlackRequestParser.HttpRequest request = SlackRequestParser.HttpRequest.builder() .requestBody("payload=" + URLEncoder.encode(gson.toJson(payload), "UTF-8")) .headers(new RequestHeaders(new HashMap<>())) .build(); Request<?> slackRequest = parser.parse(request); assertNotNull(slackRequest); }
Example #27
Source File: URLEncoder.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * URL encodes the provided path using the given encoding. * * @param path The path to encode * @param encoding The encoding to use to convert the path to bytes * * @return The encoded path * * @deprecated This will be removed in Tomcat 9.0.x */ @Deprecated public String encode(String path, String encoding) { Charset charset; try { charset = B2CConverter.getCharset(encoding); } catch (UnsupportedEncodingException e) { charset = Charset.defaultCharset(); } return encode(path, charset); }
Example #28
Source File: ZKSessionLock.java From distributedlog with Apache License 2.0 | 5 votes |
/** * Get client id and its ephemeral owner. * * @param zkClient * zookeeper client * @param lockPath * lock path * @param nodeName * node name * @return client id and its ephemeral owner. */ static Future<Pair<String, Long>> asyncParseClientID(ZooKeeper zkClient, String lockPath, String nodeName) { String[] parts = nodeName.split("_"); // member_<clientid>_s<owner_session>_ if (4 == parts.length && parts[2].startsWith("s")) { long sessionOwner = Long.parseLong(parts[2].substring(1)); String clientId; try { clientId = URLDecoder.decode(parts[1], UTF_8.name()); return Future.value(Pair.of(clientId, sessionOwner)); } catch (UnsupportedEncodingException e) { // if failed to parse client id, we have to get client id by zookeeper#getData. } } final Promise<Pair<String, Long>> promise = new Promise<Pair<String, Long>>(); zkClient.getData(lockPath + "/" + nodeName, false, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (KeeperException.Code.OK.intValue() != rc) { promise.setException(KeeperException.create(KeeperException.Code.get(rc))); } else { promise.setValue(Pair.of(deserializeClientId(data), stat.getEphemeralOwner())); } } }, null); return promise; }
Example #29
Source File: Bytes.java From PoseidonX with Apache License 2.0 | 5 votes |
/** * Converts a string to a UTF-8 byte array. * */ public static byte[] toBytes(String s) { try { return s.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { return null; } }
Example #30
Source File: FileUtils.java From swellrt with Apache License 2.0 | 5 votes |
/** * Converts an arbitrary string into a format that can be stored safely on the filesystem. * * @param str the string to encode * @return the encoded string */ public static String toFilenameFriendlyString(String str) { byte[] bytes; try { bytes = str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // This should never happen. throw new IllegalStateException("UTF-8 not supported", e); } return new String(Hex.encodeHex(bytes)); }