Java Code Examples for java.io.UnsupportedEncodingException#getMessage()

The following examples show how to use java.io.UnsupportedEncodingException#getMessage() . 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: AmforeasRestClient.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
public Optional<AmforeasResponse> add (String resource, List<NameValuePair> params) {
    final URI url = this.build(String.format(resource_path, root, alias, resource)).orElseThrow();
    final HttpPost req = new HttpPost(url);
    req.addHeader(this.accept);
    req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);

    try {
        req.setEntity(new UrlEncodedFormEntity(params));
    } catch (UnsupportedEncodingException e) {
        final String msg = "Failed to encode form body " + e.getMessage();
        l.error(msg);
        return Optional.of(new ErrorResponse(resource, Response.Status.BAD_REQUEST, msg));
    }

    return this.execute(req);
}
 
Example 2
Source File: DateraUtil.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private static String executeApiRequest(DateraObject.DateraConnection conn, HttpRequest apiReq)
        throws DateraObject.DateraError {

    // Get the token first
    String authToken = null;
    try {
        authToken = login(conn);
    } catch (UnsupportedEncodingException e) {
        throw new CloudRuntimeException("Unable to login to Datera " + e.getMessage());
    }

    if (authToken == null) {
        throw new CloudRuntimeException("Unable to login to Datera: error getting auth token ");
    }

    apiReq.addHeader(HEADER_AUTH_TOKEN, authToken);

    return executeHttp(conn, apiReq);
}
 
Example 3
Source File: AbstractClient.java    From tencentcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
private String getCanonicalQueryString(HashMap<String, String> params, String method)
    throws TencentCloudSDKException {
  if (method != null && method.equals(HttpProfile.REQ_POST)) {
    return "";
  }
  StringBuilder queryString = new StringBuilder("");
  for (Map.Entry<String, String> entry : params.entrySet()) {
    String v;
    try {
      v = URLEncoder.encode(entry.getValue(), "UTF8");
    } catch (UnsupportedEncodingException e) {
      throw new TencentCloudSDKException("UTF8 is not supported." + e.getMessage());
    }
    queryString.append("&").append(entry.getKey()).append("=").append(v);
  }
  return queryString.toString().substring(1);
}
 
Example 4
Source File: MD5.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
public static String getStringMD5(String value) {
    if (value == null || value.trim().length() < 1) {
        return null;
    }
    try {
        return getMD5(value.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 5
Source File: CarreraProducerBase.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public Result sendByCharset(String topic, String body, String charsetName, String key, String... tags) {
    try {
        return sendMessage(buildMessage(topic, CarreraConfig.PARTITION_RAND, 0, body.getBytes(charsetName), key, tags));
    } catch (UnsupportedEncodingException e) {
        return new Result(CHARSET_ENCODING_EXCEPTION, e.getMessage());
    }
}
 
Example 6
Source File: HazelcastMQJmsMessage.java    From hazelcastmq with Apache License 2.0 5 votes vote down vote up
@Override
public void setJMSCorrelationIDAsBytes(byte[] correlationID)
    throws JMSException {
  try {
    setJMSCorrelationID(new String(correlationID, "UTF-8"));
  }
  catch (UnsupportedEncodingException ex) {
    throw new JMSException("Unable to convert bytes to correlation ID: "
        + ex.getMessage());
  }
}
 
Example 7
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Utility function for creating a new StringEntity and wrapping any errors
 * as a SdkClientException.
 *
 * @param s The string contents of the returned HTTP entity.
 * @return A new StringEntity with the specified contents.
 */
public static HttpEntity newStringEntity(String s) {
    try {
        return new StringEntity(s);
    } catch (UnsupportedEncodingException e) {
        throw new SdkClientException("Unable to create HTTP entity: " + e.getMessage(), e);
    }
}
 
Example 8
Source File: EagleServiceGroupByQueryRequest.java    From eagle with Apache License 2.0 5 votes vote down vote up
public String getQueryParameterString(String service) throws EagleServiceClientException {
	if (pageSize <= 0) {
		throw new EagleServiceClientException("pageSize can't be less than 1, pageSize: " + pageSize);
	}
	try {
		final String query = getQuery();
		final StringBuilder sb = new StringBuilder();
		// query
		sb.append("query=").append(service).append(URLEncoder.encode(query, "UTF-8"));
		// startRowkey
		if (startRowkey != null) {
			sb.append("&startRowkey=").append(startRowkey);
		}
		// pageSize
		sb.append("&pageSize=").append(this.pageSize);
		if (startTime != null || endTime != null) {
			sb.append("&startTime=").append(URLEncoder.encode(startTime, "UTF-8"));
			sb.append("&endTime=").append(URLEncoder.encode(endTime, "UTF-8"));
		}
		
		// metricName
		if(metricName != null){
			sb.append("&metricName=" + metricName);
		}
		
		if (intervalMin != 0) {
			sb.append("&timeSeries=true&intervalmin=" + intervalMin);
		}
		return sb.toString();
	} catch (UnsupportedEncodingException e) {
		throw new EagleServiceClientException("Got an UnsupportedEncodingException" + e.getMessage(), e);
	}
}
 
Example 9
Source File: URL.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static String decode(String value) {
    if (value == null || value.length() == 0) { 
        return "";
    }
    try {
        return URLDecoder.decode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 10
Source File: JBZipFile.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve a String from the given bytes using the encoding set
 * for this ZipFile.
 *
 * @param bytes the byte array to transform
 * @return String obtained by using the given encoding
 * @throws ZipException if the encoding cannot be recognized.
 */
String getString(byte[] bytes) throws ZipException {
  if (encoding == null) {
    return new String(bytes);
  }
  else {
    try {
      return new String(bytes, encoding);
    }
    catch (UnsupportedEncodingException uee) {
      throw new ZipException(uee.getMessage());
    }
  }
}
 
Example 11
Source File: ContextHelper.java    From EpubParser with Apache License 2.0 5 votes vote down vote up
static String encodeToUtf8(String stringToEncode) throws ReadingException {

		String encodedString = null;

		try {
			encodedString = URLDecoder.decode(stringToEncode, "UTF-8"); // Charset.forName("UTF-8").name()
			encodedString = URLEncoder.encode(encodedString, "UTF-8").replace("+", "%20"); // Charset.forName("UTF-8").name()
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new ReadingException("UnsupportedEncoding while encoding, " + stringToEncode + ", : " + e.getMessage());
		}

		return encodedString;
	}
 
Example 12
Source File: CassandraDataHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private String base64EncodeByteBuffer(ByteBuffer byteBuffer) throws ODataServiceFault {
    byte[] data = byteBuffer.array();
    byte[] base64Data = Base64.encodeBase64(data);
    try {
        return new String(base64Data, DBConstants.DEFAULT_CHAR_SET_TYPE);
    } catch (UnsupportedEncodingException e) {
        throw new ODataServiceFault(e, "Error in encoding result binary data: " + e.getMessage());
    }
}
 
Example 13
Source File: HashHelper.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
private static byte[] getBytes (final String s) {
	try {
		return s.getBytes("UTF-8");
	}
	catch (UnsupportedEncodingException e) {
		throw new IllegalStateException(e.getMessage(), e);
	}
}
 
Example 14
Source File: OAuthUtils.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
public static String percentEncode(String s) {
    if (s == null) {
        return "";
    }
    try {
        return URLEncoder.encode(s, ENCODING)
            // OAuth encodes some characters differently:
            .replace("+", "%20").replace("*", "%2A")
            .replace("%7E", "~");
        // This could be done faster with more hand-crafted code.
    } catch (UnsupportedEncodingException wow) {
        throw new RuntimeException(wow.getMessage(), wow);
    }
}
 
Example 15
Source File: NtlmPasswordAuthentication.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static byte[] nTOWFv2(String domain, String username, String password)
{
    try {
        MD4 md4 = new MD4();
        md4.update(password.getBytes(SmbConstants.UNI_ENCODING));
        HMACT64 hmac = new HMACT64(md4.digest());
        hmac.update(username.toUpperCase().getBytes(SmbConstants.UNI_ENCODING));
        hmac.update(domain.getBytes(SmbConstants.UNI_ENCODING));
        return hmac.digest();
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException(uee.getMessage());
    }
}
 
Example 16
Source File: HttpRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private HttpRequest(@Nonnull String apiUrl, @Nullable StandardUsernamePasswordCredentials credentials, @Nullable String authHeader) {
    this.client = getHttpClient(apiUrl);
    try {
        if(StringUtils.isBlank(authHeader) && credentials != null) {
            this.authorizationHeader = String.format("Basic %s",
                    Base64.encodeBase64String(String.format("%s:%s", credentials.getUsername(),
                            Secret.toString(credentials.getPassword())).getBytes("UTF-8")));
        }else{
            this.authorizationHeader = authHeader;
        }
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException.UnexpectedErrorException("Failed to create basic auth header: "+e.getMessage(), e);
    }
}
 
Example 17
Source File: Base64.java    From alipay-sdk-java-all with Apache License 2.0 5 votes vote down vote up
public static byte[] decodeBase64String(String base64String) {
    try {
        return Base64.decodeBase64(base64String.getBytes("utf-8"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 18
Source File: Utils.java    From datasync with MIT License 5 votes vote down vote up
/**
 * @param pathToSaveJobFile path to a saved job file
 * @return command with absolute paths to execute job file at given path
 */
public static String getRunJobCommand(String pathToSaveJobFile) {
    String jarPath = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    try {
        jarPath = URLDecoder.decode(jarPath, "UTF-8");
        // Needed correct issue with windows where path includes a leading slash
        if(jarPath.contains(":") && (jarPath.startsWith("/") || jarPath.startsWith("\\"))) {
            jarPath = jarPath.substring(1, jarPath.length());
        }
        //TODO: This may change based on how we implement running metadata jobs from the command line.
        return "java -jar \"" + jarPath + "\" \"" + pathToSaveJobFile + "\"";
    } catch (UnsupportedEncodingException unsupportedEncoding) {
        return "Error getting path to this executeable: " + unsupportedEncoding.getMessage();
    }
}
 
Example 19
Source File: CallableStatementTestSetup.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
protected void setUp()
    throws SQLException {
    Connection con = getConnection();
    // Create the tables, functions and procedures we need.
    Statement stmt = con.createStatement();
    // Create table CSDATA and populate
    stmt.execute("CREATE TABLE CSDATA (ID INT PRIMARY KEY," +
            "BINARYDATA VARCHAR(256) FOR BIT DATA, " +
            "CHARDATA VARCHAR(256))");
    PreparedStatement pStmt = 
        con.prepareStatement("INSERT INTO CSDATA VALUES (?,?,?)");
    pStmt.setInt(1, STRING_BYTES_ID);
    try {
        pStmt.setBytes(2, STRING_BYTES.getBytes("UTF-16BE"));
    } catch (UnsupportedEncodingException uee) {
       SQLException sqle = new SQLException(uee.getMessage());
       sqle.initCause(uee);
       throw sqle;
    }
    pStmt.setString(3, STRING_BYTES);
    pStmt.execute();
    pStmt.setInt(1, SQL_NULL_ID);
    pStmt.setNull(2, Types.VARBINARY);
    pStmt.setNull(3, Types.VARCHAR);
    pStmt.execute();
    pStmt.close();

    // Create function INT_TO_STRING
    stmt.execute("CREATE FUNCTION INT_TO_STRING(INTNUM INT) " +
            "RETURNS VARCHAR(10) " +
            "PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA " +
            "EXTERNAL NAME 'java.lang.Integer.toString'");
    // Create procedure GET_BINARY_DIRECT
    stmt.execute("CREATE PROCEDURE GET_BINARY_DIRECT(IN INSTRING " +
            "VARCHAR(40), OUT OUTBYTES VARCHAR(160) FOR BIT DATA) " +
            "DYNAMIC RESULT SETS 0 " +
            "PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA " +
            "EXTERNAL NAME '" + SOURCECLASS + "getBinaryDirect'");
    // Create function GET_BINARY_DB
    stmt.execute("CREATE FUNCTION GET_BINARY_DB(ID INT) " +
            "RETURNS VARCHAR(256) FOR BIT DATA " +
            "PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA " +
            "EXTERNAL NAME '" + SOURCECLASS + "getBinaryFromDb'");
    // Create function GET_VARCHAR_DB
    stmt.execute("CREATE FUNCTION GET_VARCHAR_DB(ID INT) " +
            "RETURNS VARCHAR(256) " +
            "PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA " +
            "EXTERNAL NAME '" + SOURCECLASS + "getVarcharFromDb'");
    stmt.close();
}
 
Example 20
Source File: PrimaryDataStoreHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public DataStore createPrimaryDataStore(PrimaryDataStoreParameters params) {
    if(params == null)
    {
        throw new InvalidParameterValueException("createPrimaryDataStore: Input params is null, please check");
    }
    StoragePoolVO dataStoreVO = dataStoreDao.findPoolByUUID(params.getUuid());
    if (dataStoreVO != null) {
        throw new CloudRuntimeException("duplicate uuid: " + params.getUuid());
    }
    dataStoreVO = new StoragePoolVO();
    dataStoreVO.setStorageProviderName(params.getProviderName());
    dataStoreVO.setHostAddress(params.getHost());
    dataStoreVO.setPoolType(params.getType());
    dataStoreVO.setPath(params.getPath());
    dataStoreVO.setPort(params.getPort());
    dataStoreVO.setName(params.getName());
    dataStoreVO.setUuid(params.getUuid());
    dataStoreVO.setDataCenterId(params.getZoneId());
    dataStoreVO.setPodId(params.getPodId());
    dataStoreVO.setClusterId(params.getClusterId());
    dataStoreVO.setStatus(StoragePoolStatus.Initialized);
    dataStoreVO.setUserInfo(params.getUserInfo());
    dataStoreVO.setManaged(params.isManaged());
    dataStoreVO.setCapacityIops(params.getCapacityIops());
    dataStoreVO.setCapacityBytes(params.getCapacityBytes());
    dataStoreVO.setUsedBytes(params.getUsedBytes());
    dataStoreVO.setHypervisor(params.getHypervisorType());

    Map<String, String> details = params.getDetails();
    if (params.getType() == StoragePoolType.SMB && details != null) {
        String user = details.get("user");
        String password = details.get("password");
        String domain = details.get("domain");
        String updatedPath = params.getPath();

        if (user == null || password == null) {
            String errMsg = "Missing cifs user and password details. Add them as details parameter.";
            s_logger.warn(errMsg);
            throw new InvalidParameterValueException(errMsg);
        } else {
            try {
                password = DBEncryptionUtil.encrypt(URLEncoder.encode(password, "UTF-8"));
                details.put("password", password);
                updatedPath += "?user=" + user + "&password=" + password + "&domain=" + domain;
            } catch (UnsupportedEncodingException e) {
                throw new CloudRuntimeException("Error while generating the cifs url. " + e.getMessage());
            }
        }

        dataStoreVO.setPath(updatedPath);
    }
    String tags = params.getTags();
    List<String> storageTags = new ArrayList<String>();

    if (tags != null) {
        String[] tokens = tags.split(",");

        for (String tag : tokens) {
            tag = tag.trim();
            if (tag.length() == 0) {
                continue;
            }
            storageTags.add(tag);
        }
    }
    dataStoreVO = dataStoreDao.persist(dataStoreVO, details, storageTags);
    return dataStoreMgr.getDataStore(dataStoreVO.getId(), DataStoreRole.Primary);
}