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: RichEditor.java    From imsdk-android with MIT License 6 votes vote down vote up
@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 #2
Source File: HttpHeaderTransport.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #3
Source File: DemonstrationGradeEncryptionServiceImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
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 #4
Source File: RevenueCalculatorBean.java    From development with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: DockerAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: Utility.java    From iBeebo with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: LdapURL.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: AESEncrypter.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: ClientSystemFileCommands.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: Encoder.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
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 #11
Source File: Tool.java    From eLong-OpenAPI-JAVA-demo with Apache License 2.0 5 votes vote down vote up
public static String encodeUri(String url) {

		try {
			return java.net.URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}
		return url;
	}
 
Example #12
Source File: XmlEncodingBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @param encoding The encoding of the XML source that was used to
 *                 populated this object.
 * @deprecated This method will be removed in Tomcat 9
 */
@Deprecated
public void setEncoding(String encoding) {
    try {
        charset = B2CConverter.getCharset(encoding);
    } catch (UnsupportedEncodingException e) {
        log.warn(sm.getString("xmlEncodingBase.encodingInvalid", encoding, charset.name()), e);
    }
}
 
Example #13
Source File: ByteUtils.java    From bop-bitcoin-client with Apache License 2.0 5 votes vote down vote up
/**
 * convert a byte array to hexadecimal
 * 
 * @param data
 * @return
 */
public static String toHex (byte[] data)
{
	try
	{
		return new String (Hex.encode (data), "US-ASCII");
	}
	catch ( UnsupportedEncodingException e )
	{
	}
	return null;
}
 
Example #14
Source File: Request.java    From pearl with Apache License 2.0 5 votes vote down vote up
/**
 * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
 */
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
    StringBuilder encodedParams = new StringBuilder();
    try {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
            encodedParams.append('=');
            encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
            encodedParams.append('&');
        }
        return encodedParams.toString().getBytes(paramsEncoding);
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
    }
}
 
Example #15
Source File: AttachmentUnmarshallerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String decode(String cid) {
   try {
      return URLDecoder.decode(cid, "UTF-8");
   } catch (UnsupportedEncodingException var2) {
      throw new IllegalStateException(var2);
   }
}
 
Example #16
Source File: PayloadTypeDetectorTest.java    From java-slack-sdk with MIT License 5 votes vote down vote up
@Test
public void block_actions() throws UnsupportedEncodingException {
    String encoded = URLEncoder.encode(blockActionJson, "UTF-8");
    String json = URLDecoder.decode(encoded, "UTF-8");
    BlockActionPayload payload = GsonFactory.createSnakeCase().fromJson(json, BlockActionPayload.class);
    assertThat(payload.getType(), is("block_actions"));
}
 
Example #17
Source File: Base64CoderTest.java    From snake-yaml with Apache License 2.0 5 votes vote down vote up
public void testFailure1() throws UnsupportedEncodingException {
    try {
        Base64Coder.decode("YQ=".toCharArray());
        fail();
    } catch (Exception e) {
        assertEquals("Length of Base64 encoded input string is not a multiple of 4.",
                e.getMessage());
    }
}
 
Example #18
Source File: IOUtils.java    From AndroidWear-OpenWear with MIT License 5 votes vote down vote up
public static byte[] stringToBytes(String origin) {
    try {
        return origin.getBytes("ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return "".getBytes();
}
 
Example #19
Source File: JWTDemo.java    From springbootexamples with Apache License 2.0 5 votes vote down vote up
public String createTokenWithChineseClaim2() throws UnsupportedEncodingException {

		Date nowDate = new Date();
		Date expireDate = getAfterDate(nowDate, 0, 0, 0, 2, 0, 0);// 2小过期

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");

		User user = new User();
		user.setUserNaem("张三");
		user.setDeptName("技术部");
		Gson gson = new Gson();
		String userJson = gson.toJson(user);
		// String encode = URLEncoder.encode(userJson, "UTF-8");

		String userJsonBase64 = BaseEncoding.base64().encode(userJson.getBytes());

		Algorithm algorithm = Algorithm.HMAC256("secret");
		String token = JWT.create().withHeader(map)

				.withClaim("loginName", "zhuoqianmingyue").withClaim("user", userJsonBase64).withIssuer("SERVICE")// 签名是有谁生成
				.withSubject("this is test token")// 签名的主题
				// .withNotBefore(new Date())//该jwt都是不可用的时间
				.withAudience("APP")// 签名的观众 也可以理解谁接受签名的
				.withIssuedAt(nowDate) // 生成签名的时间
				.withExpiresAt(expireDate)// 签名过期的时间
				/* 签名 Signature */
				.sign(algorithm);

		return token;
	}
 
Example #20
Source File: RuleDictClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
private byte[] toJson(AbstractBceRequest bceRequest) {
    String jsonStr = JsonUtils.toJsonString(bceRequest);
    try {
        return jsonStr.getBytes(DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new BceClientException("Fail to get UTF-8 bytes", e);
    }
}
 
Example #21
Source File: MamacnPageProcessor.java    From webmagic with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    Spider.create(new MamacnPageProcessor())
            .setScheduler(new FileCacheQueueScheduler("/data/webmagic/mamacn"))
            .addUrl("http://www.mama.cn/photo/t1-p1.html")
            .addPipeline(new OneFilePipeline("/data/webmagic/mamacn/data"))
            .thread(5)
            .run();
}
 
Example #22
Source File: UnicornPointer.java    From unidbg with Apache License 2.0 5 votes vote down vote up
@Override
public String getString(long offset, String encoding) {
    long addr = peer + offset;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while (true) {
        byte[] data = unicorn.mem_read(addr, 0x10);
        int length = data.length;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == 0) {
                length = i;
                break;
            }
        }
        baos.write(data, 0, length);
        addr += length;

        if (length < data.length) { // reach zero
            break;
        }

        if (baos.size() > 0x10000) { // 64k
            throw new IllegalStateException("buffer overflow");
        }

        if (size > 0 && offset + baos.size() > size) {
            throw new InvalidMemoryAccessException();
        }
    }

    try {
        String ret = baos.toString(encoding);
        log.debug("getString pointer=" + this + ", size=" + baos.size() + ", encoding=" + encoding + ", ret=" + ret);
        return ret;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #23
Source File: StringUtils.java    From essentials with Apache License 2.0 5 votes vote down vote up
/**
 * URL-Decodes a given string using UTF-8. No UnsupportedEncodingException to handle as it is dealt with in this
 * method.
 */
public static String decodeUrl(String stringToDecode) {
    try {
        return URLDecoder.decode(stringToDecode, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        throw new RuntimeException(e1);
    }
}
 
Example #24
Source File: BaseWebService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
static String urlDecode(final String msg) {
    try {
        return URLDecoder.decode(msg, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null; // TODO best response?
    }
}
 
Example #25
Source File: NFS4StringPrep.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] prepare(byte[] src, StringPrep prep)
            throws ParseException, UnsupportedEncodingException{
    String s = new String(src, "UTF-8");
    UCharacterIterator iter =  UCharacterIterator.getInstance(s);
    StringBuffer out = prep.prepare(iter,StringPrep.DEFAULT);
    return out.toString().getBytes("UTF-8");
}
 
Example #26
Source File: ConfigurationAdminImpl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private File getFactoryPath ( final String factoryId ) throws UnsupportedEncodingException
{
    final File path = new File ( this.root, getPath ( factoryId ) );
    if ( !path.exists () )
    {
        logger.info ( "Store for factory ({}) does not exist", factoryId );
        createStore ( path, factoryId );
    }
    return path;
}
 
Example #27
Source File: InputStreamThread.java    From fess with Apache License 2.0 5 votes vote down vote up
public InputStreamThread(final InputStream is, final String charset, final int bufferSize, final Consumer<String> outputCallback) {
    super("InputStreamThread");
    this.bufferSize = bufferSize;
    this.outputCallback = outputCallback;

    try {
        br = new BufferedReader(new InputStreamReader(is, charset));
    } catch (final UnsupportedEncodingException e) {
        throw new FessSystemException(e);
    }
}
 
Example #28
Source File: Id3Decoder.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
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 #29
Source File: UriUtil.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
public static String formUrlEncodeValue(@NonNull String value) {
    Preconditions.checkNotNull(value);
    try {
        return URLEncoder.encode(value, "utf-8");
    } catch (UnsupportedEncodingException ex) {
        // utf-8 should always be supported
        throw new IllegalStateException("Unable to encode using UTF-8");
    }
}
 
Example #30
Source File: UrlUtil.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decode a URI string (according to RFC 2396).
 */
public static final String decode(String s) throws MalformedURLException {
    try {
        return decode(s, "8859_1");
    } catch (UnsupportedEncodingException e) {
        // ISO-Latin-1 should always be available?
        throw new MalformedURLException("ISO-Latin-1 decoder unavailable");
    }
}