下面列出了 org.apache.commons.codec.binary.Base64 # encodeBase64 ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Example of how to send a translate to SVF job request.
* Uses the oauth2TwoLegged and twoLeggedCredentials objects that you retrieved previously.
* @param urn - the urn of the file to translate
* @throws com.autodesk.client.ApiException
* @throws Exception
*/
private static Job translateToSVF(String urn) throws ApiException, Exception{
System.out.println("***** Sending Derivative API translate request" );
JobPayload job = new JobPayload();
byte[] urnBase64 = Base64.encodeBase64(urn.getBytes());
JobPayloadInput input = new JobPayloadInput();
input.setUrn(new String(urnBase64));
JobPayloadOutput output = new JobPayloadOutput();
JobPayloadItem formats = new JobPayloadItem();
formats.setType(JobPayloadItem.TypeEnum.SVF);
formats.setViews(Arrays.asList(JobPayloadItem.ViewsEnum._3D));
output.setFormats(Arrays.asList(formats));
job.setInput(input);
job.setOutput(output);
ApiResponse<Job> response = derivativesApi.translate(job,true,oauth2TwoLegged,twoLeggedCredentials);
System.out.println("***** Response for Translating File to SVF: " + response.getData());
return response.getData();
}
@Override
public HttpRequest sign(HttpRequest request, String key, String secret) throws LtiSigningException {
CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
try {
String body = getRequestBody(request);
String bodyHash = new String(Base64.encodeBase64(md.digest(body.getBytes())));
HttpParameters params = new HttpParameters();
params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
signer.setAdditionalParameters(params);
signer.sign(request);
} catch (OAuthMessageSignerException|OAuthExpectationFailedException|OAuthCommunicationException|IOException e) {
throw new LtiSigningException("Exception encountered while singing Lti request...", e);
}
return request;
}
protected String encodeUserData(Map<String, String> map) {
if (map == null || map.size() == 0) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
sb.append(key).append("=").append(value).append(";");
}
}
sb.delete(sb.length() - 1, sb.length());
// UserDataをエンコード
String userData = sb.toString();
userData = new String(Base64.encodeBase64(userData.getBytes()));
return userData;
}
/**
* Place a string into the attribute <tag>of the element <el>, encoded so special characters can be used.
*
* @param el
* The element.
* @param tag
* The attribute name.
* @param value
* The string.
*/
public static void encodeAttribute(Element el, String tag, String value)
{
//KNL-688 avoid a NPE being logged - DH
if (value == null)
{
return;
}
// encode the message body base64, and make it an attribute
try
{
String encoded = new String(Base64.encodeBase64(value.getBytes("UTF-8")),"UTF-8");
el.setAttribute(tag, encoded);
}
catch (Exception e)
{
log.warn("encodeAttribute: " + e);
}
}
/**
* Implementation method for authentication
*/
private String authenticate(Credentials credentials) throws AuthenticationException {
if (!(credentials instanceof EsApiKeyCredentials)) {
throw new AuthenticationException("Incorrect credentials type provided. Expected [" + EsApiKeyCredentials.class.getName()
+ "] but got [" + credentials.getClass().getName() + "]");
}
EsApiKeyCredentials esApiKeyCredentials = ((EsApiKeyCredentials) credentials);
String authString = null;
if (esApiKeyCredentials.getToken() != null && StringUtils.hasText(esApiKeyCredentials.getToken().getName())) {
EsToken token = esApiKeyCredentials.getToken();
String keyComponents = token.getId() + ":" + token.getApiKey();
byte[] base64Encoded = Base64.encodeBase64(keyComponents.getBytes(StringUtils.UTF_8));
String tokenText = new String(base64Encoded, StringUtils.UTF_8);
authString = EsHadoopAuthPolicies.APIKEY + " " + tokenText;
}
return authString;
}
/**
* description 加密 aes cbc模式
*
* @param content 1
* @param encryptKey 2
* @return java.lang.String
*/
public static String aesEncode(String content, String encryptKey) {
try {
SecretKeySpec keySpec = new SecretKeySpec(encryptKey.getBytes(StandardCharsets.UTF_8), "AES");
//根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
//初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(encryptKey.getBytes(StandardCharsets.UTF_8)));
//获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
//根据密码器的初始化方式--加密:将数据加密
byte[] byteAES = cipher.doFinal(byteEncode);
//将加密后的byte[]数据转换为Base64字符串
return new String(Base64.encodeBase64(byteAES),StandardCharsets.UTF_8);
//将字符串返回
} catch (Exception e) {
LOGGER.error("密文加密失败"+e.getMessage(),e);
throw new RuntimeException("密文加密失败");
}
//如果有错就返加null
}
static String encodeFileToBase64Binary(File toEncode) {
byte[] encoded = new byte[0];
try {
encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(toEncode));
} catch (IOException e) {
BHBot.logger.error("Error in encodeFileToBase64Binary", e);
}
return new String(encoded, StandardCharsets.US_ASCII);
}
/**
* Base64编码.
*/
public static String encodeBase64(String input) {
try {
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
} catch (UnsupportedEncodingException e) {
return "";
}
}
private HttpHeaders getUserHttpHeaders(String server, String email, String userPassword) {
byte[] plainCredsBytes = (email + ":" + userPassword).getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
public static String getFinalHmac(String username, String secret, String data) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("HMAC Id =" + username);
logger.debug("HMAC Secret =" + secret);
logger.debug("Data Before HMAC Encoded =" + data);
}
byte[] orginHmac = encode(secret, data);
String firstBase64 = new String(Base64.encodeBase64(orginHmac));
if (logger.isDebugEnabled()) {
logger.debug("HMAC Data with Base64 Encoder =" + firstBase64);
}
String usernameN64 = username + ":" + firstBase64;
if (logger.isDebugEnabled()) {
logger.debug("Username and HMAC Data =" + usernameN64);
}
String secodeBase64 = new String(Base64.encodeBase64(usernameN64.getBytes("UTF-8")));
if (logger.isDebugEnabled()) {
logger.debug("Final Data =" + secodeBase64);
}
String authHeader = HEADER_AUTH_PREFIX + secodeBase64;
if (logger.isDebugEnabled()) {
logger.debug("Authorization Header =" + authHeader);
}
return authHeader;
}
private HttpHeaders getHttpHeaders(String mikronoUser, String mikronoPassword) {
String plainCreds = mikronoPassword.matches("[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}")?(mikronoUser+":"+applicationToken+";"+mikronoPassword):(mikronoUser+":"+mikronoPassword);
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
}
/**
* Base64编码.
*/
public static String encodeBase64(String input) {
try {
return new String(Base64.encodeBase64(input.getBytes(ENCODING)));
} catch (UnsupportedEncodingException e) {
return null;
}
}
@Override
public void serializeBytes(GenericObject rec, String fieldName, byte[] value) {
String str = null;
if(value != null){
byte encoded[] = Base64.encodeBase64(value, true);
try {
str = new String(encoded, "UTF-8");
} catch (UnsupportedEncodingException ignore) { }
}
rec.add(fieldName, str);
}
private String getBase64Credentials(String username, String password) {
String plainCreds = username + ":" + password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
return new String(base64CredsBytes);
}
@Override
public int serialize(int columnIndex, Tuple tuple, OutputStream out, byte[] nullChars)
throws IOException {
byte[] bytes;
int length = 0;
Column col = schema.getColumn(columnIndex);
TajoDataTypes.DataType dataType = col.getDataType();
if (tuple.isBlankOrNull(columnIndex)) {
switch (dataType.getType()) {
case CHAR:
case TEXT:
length = nullChars.length;
out.write(nullChars);
break;
default:
break;
}
return length;
}
switch (dataType.getType()) {
case BOOLEAN:
out.write(tuple.getBool(columnIndex) ? trueBytes : falseBytes);
length = trueBytes.length;
break;
case CHAR:
int size = dataType.getLength() - tuple.size(columnIndex);
if (size < 0){
throw new ValueTooLongForTypeCharactersException(dataType.getLength());
}
byte[] pad = new byte[size];
bytes = tuple.getBytes(columnIndex);
out.write(bytes);
out.write(pad);
length = bytes.length + pad.length;
break;
case TEXT:
case BIT:
case INT2:
case INT4:
case INT8:
case FLOAT4:
case FLOAT8:
case DATE:
case INTERVAL:
bytes = tuple.getTextBytes(columnIndex);
length = bytes.length;
out.write(bytes);
break;
case TIME:
bytes = tuple.getTextBytes(columnIndex);
length = bytes.length;
out.write(bytes);
break;
case TIMESTAMP:
// UTC to table timezone
bytes = TimestampDatum.asChars(
tuple.getTimeDate(columnIndex), tableTimezone, false).getBytes(Bytes.UTF8_CHARSET);
length = bytes.length;
out.write(bytes);
break;
case BLOB:
bytes = Base64.encodeBase64(tuple.getBytes(columnIndex), false);
length = bytes.length;
out.write(bytes, 0, length);
break;
case PROTOBUF:
ProtobufDatum protobuf = (ProtobufDatum) tuple.getProtobufDatum(columnIndex);
byte[] protoBytes = protobufJsonFormat.printToString(protobuf.get()).getBytes(Bytes.UTF8_CHARSET);
length = protoBytes.length;
out.write(protoBytes, 0, protoBytes.length);
break;
case NULL_TYPE:
default:
break;
}
return length;
}
/**
* Update the Environment details in DB
* Updated Code to include changes for K8s Credentials & URL
* Updated UPDATE_ENVIRONMENT_BASIC, UPDATE_ENVIRONMENT_MARATHON_CRED queries.
* Added new query UPDATE_ENVIRONMENT_K8S_CRED
*/
public void updateEnvironment(Environment environment) {
String marathonUrl = null;
String k8sUrl = null;
if (environment.getEnvironmentId() == 0) {
throw new IllegalArgumentException("Environment cannot be null");
}
if(environment.getMarathonUrl() != null && !environment.getMarathonUrl().isEmpty()){
marathonUrl = environment.getMarathonUrl();
}
if(environment.getK8sUrl() != null && !environment.getK8sUrl().isEmpty()){
k8sUrl = environment.getK8sUrl();
}
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Query query = null;
if (environment.getMarathonUserName() == null || environment.getMarathonUserName().equals("")) {
query = session.createQuery(HQLConstants.UPDATE_ENVIRONMENT_BASIC).setString("environmentDesc", environment.getEnvironmentDesc())
.setString("marathonUrl", marathonUrl).setString("k8sUrl", k8sUrl).setInteger("envLock", environment.getEnvLock()).setInteger("dispOrdr", environment.getDisplayOrder())
.setInteger("environmentId", environment.getEnvironmentId());
query.executeUpdate();
} else {
String marathonCredStr = environment.getMarathonUserName() + ":" + environment.getMarathonPassword();
String marathonCred = new String(Base64.encodeBase64(marathonCredStr.getBytes()));
query = session.createQuery(HQLConstants.UPDATE_ENVIRONMENT_MARATHON_CRED)
.setString("environmentDesc", environment.getEnvironmentDesc()).setString("marathonUrl", marathonUrl)
.setString("k8sUrl", k8sUrl)
.setInteger("envLock", environment.getEnvLock())
.setString("marathonCred", marathonCred)
.setInteger("dispOrdr", environment.getDisplayOrder())
.setInteger("environmentId", environment.getEnvironmentId());
query.executeUpdate();
}
if(environment.getK8sUserName() == null || environment.getK8sUserName().equals("")) {
query = session.createQuery(HQLConstants.UPDATE_ENVIRONMENT_BASIC).setString("environmentDesc", environment.getEnvironmentDesc())
.setString("marathonUrl", marathonUrl).setString("k8sUrl", k8sUrl).setInteger("envLock", environment.getEnvLock()).setInteger("dispOrdr", environment.getDisplayOrder())
.setInteger("environmentId", environment.getEnvironmentId());
query.executeUpdate();
}
else {
String k8sCredStr = environment.getK8sUserName() + ":" + environment.getK8sPassword();
String k8sCred = new String(Base64.encodeBase64(k8sCredStr.getBytes()));
query = session.createQuery(HQLConstants.UPDATE_ENVIRONMENT_K8S_CRED).setString("environmentDesc", environment.getEnvironmentDesc()).setString("marathonUrl", marathonUrl)
.setString("k8sUrl", k8sUrl)
.setString("marathonUrl", marathonUrl)
.setInteger("envLock", environment.getEnvLock())
.setString("k8sCred", k8sCred)
.setInteger("dispOrdr", environment.getDisplayOrder())
.setInteger("environmentId", environment.getEnvironmentId());
query.executeUpdate();
}
tx.commit();
session.close();
}
protected static List<Object> rowsToCSVNew( RowMetaInterface meta, List<Object[]> rows ) throws KettleException {
List<Object> results = new ArrayList<>( 2 );
boolean needsBase64;
CharsetEncoder encoder = Charset.forName( "US-ASCII" ).newEncoder();
Charset utf8 = Charset.forName( "UTF-8" );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedOutputStream buf = new BufferedOutputStream( bos );
// header row
StringBuilder builder = new StringBuilder();
int i = 0;
for ( ValueMetaInterface v : meta.getValueMetaList() ) {
String name = quote( v.getName() );
builder.append( i > 0 ? "," : "" ).append( name );
i++;
}
builder.append( "\n" );
// We look for non-ascii characters and, if found, encode to ascii base64 first. For some reason,
// encoding directly to utf-8 on the Java side (Mac OS X; Java 8) causes the python utf-8 decoder to hang
// when there are non-ascii characters (such as in Mayagüez) present. Encoding to base64 first, then decoding
// this on the python side seems to fix the issue.
needsBase64 = !encoder.canEncode( builder.toString() );
try {
buf.write( builder.toString().getBytes( utf8 ) );
for ( Object[] row : rows ) {
builder.setLength( 0 );
for ( i = 0; i < meta.size(); i++ ) {
String value;
ValueMetaInterface vm = meta.getValueMeta( i );
if ( row[i] == null || Const.isEmpty( vm.getString( row[i] ) ) ) {
value = "?";
} else {
//switch ( meta.getValueMetaList().get( i ).getType() ) {
switch ( vm.getType() ) {
case ValueMetaInterface.TYPE_NUMBER:
case ValueMetaInterface.TYPE_INTEGER:
case ValueMetaInterface.TYPE_BIGNUMBER:
value = vm.getString( row[i] );
break;
case ValueMetaInterface.TYPE_DATE:
int offset = TZ.getOffset( vm.getDate( row[i] ).getTime() );
value = "" + ( vm.getDate( row[i] ).getTime() + offset );
break;
case ValueMetaInterface.TYPE_TIMESTAMP:
offset = TZ.getOffset( vm.getDate( row[i] ).getTime() );
value = "" + ( vm.getDate( row[i] ).getTime() + offset );
break;
case ValueMetaInterface.TYPE_BOOLEAN:
value = "" + ( vm.getBoolean( row[i] ) ? "1" : "0" );
break;
// TODO throw an exception for Serializable/Binary
default:
value = quote( vm.getString( row[i] ) );
}
}
builder.append( i > 0 ? "," : "" ).append( value );
}
builder.append( "\n" );
if ( !needsBase64 ) {
needsBase64 = !encoder.canEncode( builder.toString() );
}
buf.write( builder.toString().getBytes( utf8 ) );
}
buf.flush();
buf.close();
} catch ( IOException e ) {
throw new KettleException( e );
}
byte[] bytes = bos.toByteArray();
if ( needsBase64 ) {
bytes = Base64.encodeBase64( bytes );
}
results.add( bytes );
results.add( needsBase64 );
return results;
}
private static String getAuthHeader(String userName, String password) {
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}
public Result viewableRegister(
String viewableURN,
String region,
boolean compressedURN,
String rootFileName,
boolean test,
boolean force
)
throws IOException,
URISyntaxException
{
String scope[] = { SCOPE_DATA_CREATE, SCOPE_DATA_READ, SCOPE_DATA_WRITE };
ResultAuthentication authResult = authenticate( scope );
if( authResult.isError() )
{
return authResult;
}
viewableURN = new String( Base64.encodeBase64( viewableURN.getBytes() ) );
JSONObject j_input = new JSONObject();
j_input.put( KEY_URN, viewableURN );
if( compressedURN )
{
j_input.put( KEY_COMPRESSED_URN, true );
if( rootFileName != null && rootFileName.length() > 0 )
{
j_input.put( KEY_ROOT_FILENAME, rootFileName );
}
}
JSONObject j_destination = new JSONObject();
j_destination.put( KEY_REGION, region );
JSONObject j_format = new JSONObject();
j_format.put( KEY_TYPE, "svf" );
JSONArray j_views = new JSONArray();
j_views.add( "2d" );
j_views.add( "3d" );
j_format.put( KEY_VIEWS, j_views );
JSONArray j_formats = new JSONArray();
j_formats.add( j_format );
JSONObject j_output = new JSONObject();
j_output.put( KEY_DESTINATION, j_destination );
j_output.put( KEY_FORMATS, j_formats );
JSONObject j_obj = new JSONObject();
j_obj.put( KEY_INPUT, j_input );
j_obj.put( KEY_OUTPUT, j_output );
String jStr = j_obj.toString();
String frag = makeURN( API_VIEWING, PATT_VIEW_REGISTER, null );
URI uri = new URI( _protocol, null, lookupHostname(), _port, frag , null, null );
URL url = new URL( uri.toASCIIString() );
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod( "POST" );
authResult.setAuthHeader( connection );
connection.setRequestProperty( "Accept", "Application/json" );
connection.setRequestProperty( "Content-Length", "" + jStr.length() );
if( force )
{
connection.setRequestProperty( "x-ads-force", "true" );
}
if( test )
{
connection.setRequestProperty( "x-ads-test", "true" );
}
connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );
connection.setDoOutput( true );
OutputStream os = null;
try
{
os = connection.getOutputStream();
os.write(jStr.getBytes(Charset.forName("UTF-8")));
}
finally
{
if( os != null ) os.close();
}
return new Result( connection );
}
/**
* The SASL username for an encrypted handshake consists of the keyId,
* blockPoolId, and nonce with the first two encoded as Strings, and the third
* encoded using Base64. The fields are each separated by a single space.
*
* @param encryptionKey the encryption key to encode as a SASL username.
* @return encoded username containing keyId, blockPoolId, and nonce
*/
private static String getUserNameFromEncryptionKey(
DataEncryptionKey encryptionKey) {
return encryptionKey.keyId + NAME_DELIMITER +
encryptionKey.blockPoolId + NAME_DELIMITER +
new String(Base64.encodeBase64(encryptionKey.nonce, false), Charsets.UTF_8);
}