Java Code Examples for java.io.UnsupportedEncodingException

The following examples show how to use java.io.UnsupportedEncodingException. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: development   Source File: RevenueCalculatorBean.java    License: 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 2
Source Project: hsweb-framework   Source File: OAuth2ClientController.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: java-slack-sdk   Source File: SlackRequestParserTest.java    License: MIT License 6 votes vote down vote up
@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 4
Source Project: netbeans   Source File: DockerAction.java    License: 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 5
Source Project: iBeebo   Source File: Utility.java    License: 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 6
Source Project: p4ic4idea   Source File: ClientSystemFileCommands.java    License: 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 7
Source Project: imsdk-android   Source File: RichEditor.java    License: 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 8
Source Project: barcodescanner-lib-aar   Source File: Encoder.java    License: 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 9
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 10
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 11
Source Project: dragonwell8_jdk   Source File: LdapURL.java    License: 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 12
Source Project: development   Source File: AESEncrypter.java    License: 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 13
Source Project: TelePlus-Android   Source File: Id3Decoder.java    License: 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 14
Source Project: openjdk-jdk8u   Source File: Perf.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 15
Source Project: JavaTutorial   Source File: LineEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@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 16
Source Project: zaproxy-plugin   Source File: ZAProxy.java    License: MIT License 5 votes vote down vote up
/**
 * 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 17
Source Project: openjdk-8   Source File: PerfDataType.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 18
Source Project: smarthome   Source File: JsonStorageService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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 19
Source Project: jdk1.8-source-analysis   Source File: ToHTMLStream.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 20
Source Project: pulsar   Source File: WebTargets.java    License: Apache License 2.0 5 votes vote down vote up
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 21
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 22
Source Project: freeiot-android   Source File: DevicesApi.java    License: MIT License 5 votes vote down vote up
/**
 * 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 23
Source Project: j2objc   Source File: UnicodeRegex.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 24
Source Project: spiracle   Source File: FileUrlServlet.java    License: Apache License 2.0 5 votes vote down vote up
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 25
Source Project: scada   Source File: DocDownloadAction.java    License: MIT License 5 votes vote down vote up
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 26
@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 27
Source Project: Tomcat8-Source-Read   Source File: URLEncoder.java    License: MIT License 5 votes vote down vote up
/**
 * 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 Project: distributedlog   Source File: ZKSessionLock.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 Project: PoseidonX   Source File: Bytes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 Project: swellrt   Source File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}