public static String getSubjectIdentification( Row row ) { String name = row.getAs( "Defendant Name" ); String gender = row.getAs( "Gender" ); String race = row.getAs( "Race" ); String dob = row.getAs( "DOB" ); StringBuilder sb = new StringBuilder(); sb .append( encoder.encodeToString( StringUtils.getBytesUtf8( name ) ) ) .append( "|" ) .append( encoder.encodeToString( StringUtils.getBytesUtf8( gender ) ) ) .append( "|" ) .append( encoder.encodeToString( StringUtils.getBytesUtf8( race ) ) ) .append( "|" ) .append( encoder.encodeToString( StringUtils.getBytesUtf8( dob ) ) ); return sb.toString(); }
@Override protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential, final String originalPassword) throws GeneralSecurityException, PreventedException { if (this.users == null || this.users.isEmpty()) { throw new FailedLoginException("No user can be accepted because none is defined"); } final String username = credential.getUsername(); final String cachedPassword = this.users.get(username); if (cachedPassword == null) { LOGGER.debug("[{}] was not found in the map.", username); throw new AccountNotFoundException(username + " not found in backing map."); } if (!StringUtils.equals(credential.getPassword(), cachedPassword)) { throw new FailedLoginException(); } final List<MessageDescriptor> list = new ArrayList<>(); return createHandlerResult(credential, this.principalFactory.createPrincipal(username), list); }
private void initializeAwsAuthorizationData(String region) throws SdkClientException { final Regions awsRegion = Regions.fromName(region); AmazonECR ecr = AmazonECRClientBuilder.standard().withRegion(awsRegion).build(); GetAuthorizationTokenResult authTokenResult = ecr.getAuthorizationToken( new GetAuthorizationTokenRequest() ); AuthorizationData authData = authTokenResult.getAuthorizationData().get(0); String[] userAuthData = StringUtils.newStringUtf8(Base64.decodeBase64( authData.getAuthorizationToken()) ).split(":"); registryUsername = userAuthData[0]; registryPassword = userAuthData[1]; registryUrl = authData.getProxyEndpoint(); }
public JWTDecoder(String jwt, EncodeType encodeType) throws Exception { parts = TokenUtils.splitToken(jwt); final JWTParser converter = new JWTParser(); String headerJson = null; String payloadJson = null; switch (encodeType) { case Base16: headerJson = URLDecoder.decode(new String(Hex.decodeHex(parts[0])), "UTF-8"); payloadJson = URLDecoder.decode(new String(Hex.decodeHex(parts[1])), "UTF-8"); break; case Base32: Base32 base32 = new Base32(); headerJson = URLDecoder.decode(new String(base32.decode(parts[0]), "UTF-8")); payloadJson = URLDecoder.decode(new String(base32.decode(parts[1]), "UTF-8")); break; case Base64: headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0])); payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1])); break; } header = converter.parseHeader(headerJson); payload = converter.parsePayload(payloadJson); }
@Profile("kubernetes") @Bean /* * Load the CloudantClient from the Kubernetes Secrets file. * This method is only loaded when the kubernetes profile is activated */ public CloudantClient client() throws IOException { String secrets = readKubeSecretsFiles(); String secretsJson = StringUtils.newStringUtf8(Base64.decodeBase64(secrets)); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<String, Object>(); // convert JSON string to Map map = mapper.readValue(secretsJson, new TypeReference<Map<String, String>>(){}); String username = (String) map.get("username"); String password = (String) map.get("password"); String url = "http://" + map.get("username") + ".cloudant.com"; return ClientBuilder.url(new URL(url)) .username(username) .password(password) .build(); }
/** * Applies an RFC 1522 compliant encoding scheme to the given string of text with the given charset. * <p> * This method constructs the "encoded-word" header common to all the RFC 1522 codecs and then invokes * {@link #doEncoding(byte [])} method of a concrete class to perform the specific encoding. * * @param text * a string to encode * @param charset * a charset to be used * @return RFC 1522 compliant "encoded-word" * @throws EncoderException * thrown if there is an error condition during the Encoding process. * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> */ protected String encodeText(final String text, final Charset charset) throws EncoderException { if (text == null) { return null; } final StringBuilder buffer = new StringBuilder(); buffer.append(PREFIX); buffer.append(charset); buffer.append(SEP); buffer.append(this.getEncoding()); buffer.append(SEP); final byte [] rawData = this.doEncoding(text.getBytes(charset)); buffer.append(StringUtils.newStringUsAscii(rawData)); buffer.append(POSTFIX); return buffer.toString(); }
/** * DES算法,加密 * * @param data 待加密字符串 * @param key 加密私钥,长度不能够小于8位 * @return 加密后字符串 * @throws Exception */ public static String desEncode(String key, String data) { if (data == null) return null; try { DESKeySpec dks = new DESKeySpec(StringUtils.getBytesUtf8(key)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //key的长度不能够小于8位字节 Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(StringUtils.getBytesUtf8("12345678")); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); byte[] bytes = cipher.doFinal(StringUtils.getBytesUtf8(data)); return Hex.encodeHexString(bytes); } catch (Exception e) { throw new RuntimeException("des加密失败", e); } }
/** * DES算法,解密 * * @param data 待解密字符串 * @param key 解密私钥,长度不能够小于8位 * @return 解密后的字符串 * @throws Exception 异常 */ public static String desDecode(String key, String data) { if (data == null) return null; try { DESKeySpec dks = new DESKeySpec(StringUtils.getBytesUtf8(key)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //key的长度不能够小于8位字节 Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(StringUtils.getBytesUtf8("12345678")); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec); byte[] bytes = Hex.decodeHex(data.toCharArray()); return StringUtils.newStringUtf8(cipher.doFinal(bytes)); } catch (Exception e) { throw new RuntimeException("des解密失败", e); } }
@Test public void zoneTestTest() throws Exception { final String ZONETestDateInBRST = "2014-12-31T23:59:59-02:00"; // arbitrary zone, BRST=Brazil, better if not local. final String ZONETestDateInZulu = "2015-01-01T01:59:59Z"; final String ZONETestDateInET = "2014-12-31T20:59:59-05:00"; TemporalInstant instant = new TemporalInstantRfc3339(DateTime.parse(ZONETestDateInBRST)); Assert.assertEquals("Test our test Zulu, ET strings.", ZONETestDateInET, DateTime.parse(ZONETestDateInZulu).withZone(DateTimeZone.forID("-05:00")).toString(ISODateTimeFormat.dateTimeNoMillis())); Assert.assertEquals("Test our test BRST,Zulu strings.", ZONETestDateInZulu, DateTime.parse(ZONETestDateInBRST).withZone(DateTimeZone.UTC).toString(ISODateTimeFormat.dateTimeNoMillis())); Assert.assertTrue("Key must be normalized to time zone Zulu: "+instant.getAsKeyString(), instant.getAsKeyString().endsWith("Z")); Assert.assertEquals("Key must be normalized from BRST -02:00", ZONETestDateInZulu, instant.getAsKeyString()); Assert.assertArrayEquals(StringUtils.getBytesUtf8(instant.getAsKeyString()), instant.getAsKeyBytes()); Assert.assertTrue( "Ignore original time zone.", ! ZONETestDateInBRST.equals( instant.getAsReadable(DateTimeZone.forID("-07:00")))); Assert.assertEquals( "Use original time zone.", ZONETestDateInBRST, instant.getAsDateTime().toString(TemporalInstantRfc3339.FORMATTER)); Assert.assertEquals( "Time at specified time zone.", ZONETestDateInET, instant.getAsReadable(DateTimeZone.forID("-05:00"))); instant = new TemporalInstantRfc3339(DateTime.parse(ZONETestDateInZulu)); Assert.assertEquals("expect a time with specified time zone.", ZONETestDateInET, instant.getAsReadable(DateTimeZone.forID("-05:00"))); }
/** * Returns the Base64 encoded serialized string representing the variable. * * @param variable the variable to serialize * @return the Base64 encoded serialized string representing the variable * @throws java.io.IOException if the variable count not be serialized */ private String serialize(Variable variable) throws IOException { ObjectOutputStream oos = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(variable); //encode without calling Base64#encodeBase64String as versions //prior to 1.5 chunked the output byte[] encoding = Base64.encodeBase64(baos.toByteArray(), false); return StringUtils.newStringUtf8(encoding); } finally { if (oos != null) { oos.close(); } } }
protected String encodeText(String text, String charset) /* 15: */ throws EncoderException, UnsupportedEncodingException /* 16: */ { /* 17: 84 */ if (text == null) { /* 18: 85 */ return null; /* 19: */ } /* 20: 87 */ StringBuffer buffer = new StringBuffer(); /* 21: 88 */ buffer.append("=?"); /* 22: 89 */ buffer.append(charset); /* 23: 90 */ buffer.append('?'); /* 24: 91 */ buffer.append(getEncoding()); /* 25: 92 */ buffer.append('?'); /* 26: 93 */ byte[] rawdata = doEncoding(text.getBytes(charset)); /* 27: 94 */ buffer.append(StringUtils.newStringUsAscii(rawdata)); /* 28: 95 */ buffer.append("?="); /* 29: 96 */ return buffer.toString(); /* 30: */ }
@Override public String encode() { StringBuilder sb = new StringBuilder(); sb.append(keyMethod); sb.append(':'); sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(key, false))); if (lifetime > 0) { sb.append('|'); sb.append(lifetime); } if (mkiLength > 0) { sb.append('|'); sb.append(mki); sb.append(':'); sb.append(mkiLength); } return sb.toString(); }
/** * Issues a HTTP Get request to the provided url and returns the response * @param requestUrl the request url * @return the response * @throws IOException if there are problems with the http get request. */ byte[] httpGet(String requestUrl) throws IOException { GetMethod getMethod = new GetMethod(requestUrl); try { int responseCode = this.httpClient.executeMethod(getMethod); LOGGER.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl); byte[] response = getMethod.getResponseBody(); if (responseCode != HttpStatus.SC_OK) { throw new SamzaException( String.format("Received response code: %s for get request on: %s, with message: %s.", responseCode, requestUrl, StringUtils.newStringUtf8(response))); } return response; } finally { getMethod.releaseConnection(); } }
/** * This method initiates http get request on the request url and returns the * response returned from the http get. * @param requestUrl url on which the http get request has to be performed. * @return the http get response. * @throws IOException if there are problems with the http get request. */ private byte[] httpGet(String requestUrl) throws IOException { GetMethod getMethod = new GetMethod(requestUrl); try { int responseCode = httpClient.executeMethod(getMethod); LOG.debug("Received response code: {} for the get request on the url: {}", responseCode, requestUrl); byte[] response = getMethod.getResponseBody(); if (responseCode != HttpStatus.SC_OK) { throw new SamzaException(String.format("Received response code: %s for get request on: %s, with message: %s.", responseCode, requestUrl, StringUtils.newStringUtf8(response))); } return response; } finally { getMethod.releaseConnection(); } }
public static byte[] deflate(final String data) throws SCSException { final byte[] toDeflate = StringUtils.getBytesUtf8(data); final Deflater deflater = new Deflater(); final byte[] tmp = new byte[4096]; deflater.setInput(toDeflate); deflater.finish(); final int outSize = deflater.deflate(tmp); if(!deflater.finished()) { throw new SCSException("Can not deflate session data. Data is too large."); } deflater.end(); final byte[] out = new byte[outSize]; System.arraycopy(tmp, 0, out, 0, outSize); return out; }
private String encryptSecure(final byte[] salt, final String plainPassword, final String algorithm) throws NoSuchAlgorithmException, InvalidKeySpecException { int deriverdKeyLenght = Algorithm.SUPPORTED_ALGORITHMS_AND_KEY_LENGTHS.get(algorithm); KeySpec spec = new PBEKeySpec(plainPassword.toCharArray(), salt, iterationCount, deriverdKeyLenght); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); byte[] passwordDigest = secretKeyFactory.generateSecret(spec).getEncoded(); byte[] passwordDigestBase64 = Base64.encodeBase64(passwordDigest); String passwordDigestBase64StringUTF8 = StringUtils.newStringUtf8(passwordDigestBase64); byte[] saltBase64 = Base64.encodeBase64(salt); String saltBase64StringUTF8 = StringUtils.newStringUtf8(saltBase64); return SEPARATOR_START + algorithm + SEPARATOR_END + SEPARATOR_START + saltBase64StringUTF8 + SEPARATOR_END + passwordDigestBase64StringUTF8; }
protected String decodeText(String paramString) throws DecoderException, UnsupportedEncodingException { if (paramString == null) return null; if ((!paramString.startsWith("=?")) || (!paramString.endsWith("?="))) throw new DecoderException("RFC 1522 violation: malformed encoded content"); int i = -2 + paramString.length(); int j = paramString.indexOf('?', 2); if (j == i) throw new DecoderException("RFC 1522 violation: charset token not found"); String str1 = paramString.substring(2, j); if (str1.equals("")) throw new DecoderException("RFC 1522 violation: charset not specified"); int k = j + 1; int m = paramString.indexOf('?', k); if (m == i) throw new DecoderException("RFC 1522 violation: encoding token not found"); String str2 = paramString.substring(k, m); if (!getEncoding().equalsIgnoreCase(str2)) throw new DecoderException("This codec cannot decode " + str2 + " encoded content"); int n = m + 1; return new String(doDecoding(StringUtils.getBytesUsAscii(paramString.substring(n, paramString.indexOf('?', n)))), str1); }
/** * Applies an RFC 1522 compliant encoding scheme to the given string of text with the given charset. * <p> * This method constructs the "encoded-word" header common to all the RFC 1522 codecs and then invokes * {@link #doEncoding(byte [])} method of a concrete class to perform the specific encoding. * * @param text * a string to encode * @param charset * a charset to be used * @return RFC 1522 compliant "encoded-word" * @throws EncoderException * thrown if there is an error condition during the Encoding process. * @see <a href="http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html">Standard charsets</a> */ protected String encodeText(final String text, final Charset charset) throws EncoderException { if (text == null) { return null; } final StringBuilder buffer = new StringBuilder(); buffer.append(PREFIX); buffer.append(charset); buffer.append(SEP); buffer.append(this.getEncoding()); buffer.append(SEP); final byte [] rawData = this.doEncoding(StringUtils.getBytesUnchecked(text, charset.name())); buffer.append(StringUtils.newStringUsAscii(rawData)); buffer.append(POSTFIX); return buffer.toString(); }
@Test public void testSha1UpdateWithString(){ final String d1 = "C'est un homme qui rentre dans un café, et plouf"; final String d2 = "C'est un homme, c'est qu'une tête, on lui offre un cadeau: 'oh... encore un chapeau!'"; MessageDigest messageDigest = DigestUtils.getSha1Digest(); messageDigest.update(StringUtils.getBytesUtf8(d1)); messageDigest.update(StringUtils.getBytesUtf8(d2)); final String expectedResult = Hex.encodeHexString(messageDigest.digest()); messageDigest = DigestUtils.getSha1Digest(); DigestUtils.updateDigest(messageDigest, d1); DigestUtils.updateDigest(messageDigest, d2); final String actualResult = Hex.encodeHexString(messageDigest.digest()); assertEquals(expectedResult, actualResult); }
@SuppressWarnings("deprecation") // deliberate tests of deprecated code @Test public void testShaUpdateWithString(){ final String d1 = "C'est un homme qui rentre dans un café, et plouf"; final String d2 = "C'est un homme, c'est qu'une tête, on lui offre un cadeau: 'oh... encore un chapeau!'"; MessageDigest messageDigest = DigestUtils.getShaDigest(); messageDigest.update(StringUtils.getBytesUtf8(d1)); messageDigest.update(StringUtils.getBytesUtf8(d2)); final String expectedResult = Hex.encodeHexString(messageDigest.digest()); messageDigest = DigestUtils.getShaDigest(); DigestUtils.updateDigest(messageDigest, d1); DigestUtils.updateDigest(messageDigest, d2); final String actualResult = Hex.encodeHexString(messageDigest.digest()); assertEquals(expectedResult, actualResult); }
static String write(Serializable s) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(s); return StringUtils.newStringUtf8(Base64.encodeBase64(bos.toByteArray(), false)); } finally { out.close(); bos.close(); } } catch( Exception ex ) { throw Log.errRTExcept(ex); } }
@Override public Object decrypt(String data) { String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':'); // String[] splitData = data.split(":"); if (splitData.length != 2) { return null; } else { if (splitData[0].equals("ESTRING")) { return StringUtils.newStringUtf8(decryptToBytes(splitData[1])); } else if (splitData[0].equals("EBOOL")) { return decryptBinary(splitData[1], Boolean.class); } else if (splitData[0].equals("EINT")) { return decryptBinary(splitData[1], Integer.class); } else if (splitData[0].equals("ELONG")) { return decryptBinary(splitData[1], Long.class); } else if (splitData[0].equals("EDOUBLE")) { return decryptBinary(splitData[1], Double.class); } else { return null; } } }
/** * 先对消息体进行BASE64解码再进行DES解码 * @param info * @return */ public static String decodeInfo(String info) { info = info.replace("/add*/", "+"); byte[] temp = base64Decode(info); try { byte[] buf = decrypt(temp, KEY.getBytes(ENCODING)); return StringUtils.newStringUtf8(buf); } catch (Exception e) { e.printStackTrace(); } return ""; }
/** * 先对消息体进行BASE64解码再进行DES解码 * * @param info * @return */ public static String decodeInfo(String info) { byte[] temp = base64Decode(info); try { byte[] buf = decrypt(temp, KEY.getBytes(ENCODING)); return StringUtils.newStringUtf8(buf); } catch (Exception e) { e.printStackTrace(); } return ""; }
@Override public void setAvatar(InputStream is) throws IOException { updateLocalVars(); this.avatar = "data:image/jpeg;base64," + StringUtils.newStringUtf8(Base64.encodeBase64(IOUtils.toByteArray (is), false)); updateEdits(); }
@Override public void writeNode ( final DataNode node ) { final String data; if ( node != null && node.getData () != null ) { data = StringUtils.newStringUtf8 ( Base64.encodeBase64 ( node.getData (), true ) ); } else { data = null; } logger.debug ( "Write data node: {} -> {}", node, data ); this.accessor.doWithConnection ( new CommonConnectionTask<Void> () { @Override protected Void performTask ( final ConnectionContext connectionContext ) throws Exception { connectionContext.setAutoCommit ( false ); deleteNode ( connectionContext, node.getId () ); insertNode ( connectionContext, node, data ); connectionContext.commit (); return null; } } ); }
@Override public void saveState ( final IMemento memento ) { super.saveState ( memento ); if ( memento == null ) { return; } final Resource resource = new XMIResourceFactoryImpl ().createResource ( null ); resource.getContents ().add ( this.configuration ); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); final Map<?, ?> options = new HashMap<Object, Object> (); try { resource.save ( outputStream, options ); final IMemento child = memento.createChild ( CHILD_CONFIGURATION ); child.putTextData ( StringUtils.newStringUtf8 ( Base64.encodeBase64 ( outputStream.toByteArray (), true ) ) ); } catch ( final Exception e ) { StatusManager.getManager ().handle ( StatusHelper.convertStatus ( Activator.PLUGIN_ID, e ), StatusManager.LOG ); } }
private String encode(String s) { return Base64.encodeBase64String(StringUtils.getBytesUtf8(s)); }
private String Bytes2Base64(byte[] bytes, String format) { StringBuilder sb = new StringBuilder(); if (format != null) sb.append("data:image/" + format + ";base64,"); else sb.append("data:image/png;base64,"); sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(bytes, false))); return sb.toString(); }
@Override public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException { try { if(status.isExists()) { delete.delete(Collections.singletonList(renamed), connectionCallback, callback); } final String fileid = new DriveFileidProvider(session).getFileid(file, new DisabledListProgressListener()); if(!StringUtils.equals(file.getName(), renamed.getName())) { // Rename title final File properties = new File(); properties.setName(renamed.getName()); properties.setMimeType(status.getMime()); session.getClient().files().update(fileid, properties). setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")).execute(); } // Retrieve the existing parents to remove final StringBuilder previousParents = new StringBuilder(); final File reference = session.getClient().files().get(fileid) .setFields("parents") .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")) .execute(); for(String parent : reference.getParents()) { previousParents.append(parent); previousParents.append(','); } // Move the file to the new folder session.getClient().files().update(fileid, null) .setAddParents(new DriveFileidProvider(session).getFileid(renamed.getParent(), new DisabledListProgressListener())) .setRemoveParents(previousParents.toString()) .setFields("id, parents") .setSupportsTeamDrives(PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")) .execute(); return new Path(renamed.getParent(), renamed.getName(), renamed.getType(), new PathAttributes(renamed.attributes()).withVersionId(fileid)); } catch(IOException e) { throw new DriveExceptionMappingService().map("Cannot rename {0}", e, file); } }
public HttpClient addPreemptiveAuthorizationHeaders() { if (preemptiveAuth && username != null && password != null && request != null) { // https://issues.apache.org/jira/browse/CODEC-89 Using this instead of encodeBase64String, as some versions of apache-commons have chunking enabled by default String credentials = StringUtils.newStringUtf8(Base64.encodeBase64((username + ":" + password).getBytes(StandardCharsets.UTF_8), false)); request.setHeader("Authorization", String.format("Basic %s", credentials)); } return this; }
public CustomJWToken(String token) { final String[] parts = splitToken(token); try { headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0])); payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1])); checkRegisteredClaims(payloadJson); } catch (NullPointerException e) { ConsoleOut.output("The UTF-8 Charset isn't initialized ("+e.getMessage()+")"); } signature = Base64.decodeBase64(parts[2]); }
public static boolean isValidJWT(String token){ if(org.apache.commons.lang.StringUtils.countMatches(token, ".")!=2){ return false; } try { JWT.decode(token); return true; } catch (JWTDecodeException exception){ } return false; }
/** * Applies an RFC 1522 compliant decoding scheme to the given string of text. * <p> * This method processes the "encoded-word" header common to all the RFC 1522 codecs and then invokes * {@link #doEncoding(byte [])} method of a concrete class to perform the specific decoding. * * @param text * a string to decode * @return A new decoded String or <code>null</code> if the input is <code>null</code>. * @throws DecoderException * thrown if there is an error condition during the decoding process. * @throws UnsupportedEncodingException * thrown if charset specified in the "encoded-word" header is not supported */ protected String decodeText(final String text) throws DecoderException, UnsupportedEncodingException { if (text == null) { return null; } if (!text.startsWith(PREFIX) || !text.endsWith(POSTFIX)) { throw new DecoderException("RFC 1522 violation: malformed encoded content"); } final int terminator = text.length() - 2; int from = 2; int to = text.indexOf(SEP, from); if (to == terminator) { throw new DecoderException("RFC 1522 violation: charset token not found"); } final String charset = text.substring(from, to); if (charset.equals("")) { throw new DecoderException("RFC 1522 violation: charset not specified"); } from = to + 1; to = text.indexOf(SEP, from); if (to == terminator) { throw new DecoderException("RFC 1522 violation: encoding token not found"); } final String encoding = text.substring(from, to); if (!getEncoding().equalsIgnoreCase(encoding)) { throw new DecoderException("This codec cannot decode " + encoding + " encoded content"); } from = to + 1; to = text.indexOf(SEP, from); byte[] data = StringUtils.getBytesUsAscii(text.substring(from, to)); data = doDecoding(data); return new String(data, charset); }
@RequestMapping(method = RequestMethod.PUT) public MediaMetadataDto update(@RequestBody MediaMetadataDto mediaMetadataDto) { MediaMetadata mediaMetadataFromDb; if (mediaMetadataDto.getUuid() == null || (mediaMetadataFromDb = mediaService.get(mediaMetadataDto.getUuid())) == null) { throw new ResourceNotFoundException("A valid uuid is required to edit a bundle."); } // Check Validation of MediaMetadataDto validator.validate(mediaMetadataDto, null); // Additionnal Validations if (MediaMetadata.hasFile(mediaMetadataDto.getMediaType()) && !StringUtils.equals(mediaMetadataFromDb.getUrl(), mediaMetadataDto.getUrl())) { throw new IllegalArgumentException("You can set the URL if the media has a file."); } // Mapper MediaMetadata meta = mapper.fromDto(mediaMetadataDto); // Save or update media Media media = Media .builder() .metadata(meta) .build(); mediaService.update(media); // Get generated Uuid mediaMetadataDto.setUuid(media.getMetadata().getUuid()); return mediaMetadataDto; }
protected String encodeText(String text, Charset charset) throws EncoderException { if (text == null) { return null; } StringBuilder buffer = new StringBuilder(); buffer.append(PREFIX); buffer.append(charset); buffer.append(SEP); buffer.append(getEncoding()); buffer.append(SEP); buffer.append(StringUtils.newStringUsAscii(doEncoding(text.getBytes(charset)))); buffer.append(POSTFIX); return buffer.toString(); }
protected String decodeText(String text) throws DecoderException, UnsupportedEncodingException { if (text == null) { return null; } if (text.startsWith(PREFIX) && text.endsWith(POSTFIX)) { int terminator = text.length() - 2; int to = text.indexOf(63, 2); if (to == terminator) { throw new DecoderException("RFC 1522 violation: charset token not found"); } String charset = text.substring(2, to); if (charset.equals("")) { throw new DecoderException("RFC 1522 violation: charset not specified"); } int from = to + 1; to = text.indexOf(63, from); if (to == terminator) { throw new DecoderException("RFC 1522 violation: encoding token not found"); } String encoding = text.substring(from, to); if (getEncoding().equalsIgnoreCase(encoding)) { from = to + 1; return new String(doDecoding(StringUtils.getBytesUsAscii(text.substring(from, text.indexOf(63, from)))), charset); } throw new DecoderException("This codec cannot decode " + encoding + " encoded content"); } throw new DecoderException("RFC 1522 violation: malformed encoded content"); }