Java Examples for org.apache.commons.codec.binary.StringUtils
The following java examples will help you to understand the usage of org.apache.commons.codec.binary.StringUtils. These source code samples are taken from different open source projects.
Example 1
| Project: sosies-generator-master File: StringUtilsTest.java View source code |
@Test(timeout = 1000)
public void testGetBytesIso8859_1_add522() throws UnsupportedEncodingException {
fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testGetBytesIso8859_1_add522");
final String charsetName = "ISO-8859-1";
testGetBytesUnchecked(charsetName);
testGetBytesUnchecked(charsetName);
final byte[] expected = STRING_FIXTURE.getBytes(charsetName);
final byte[] actual = StringUtils.getBytesIso8859_1(STRING_FIXTURE);
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2636, null, 2635, java.util.Arrays.equals(expected, actual));
fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}Example 2
| Project: smart-cms-master File: VelocityGeneratorTest.java View source code |
@Test
public void testVelocityRepGeneration() throws IOException {
TypeRepresentationGenerator generator = new VelocityRepresentationGenerator();
final RepresentationTemplate template = mockery.mock(RepresentationTemplate.class);
WorkspaceAPIImpl impl = new WorkspaceAPIImpl() {
@Override
public RepresentationTemplate getRepresentationTemplate(WorkspaceId id, String name) {
return template;
}
};
impl.setRepresentationGenerators(Collections.singletonMap(TemplateType.VELOCITY, generator));
RepresentationProvider provider = new RepresentationProviderImpl();
final WorkspaceAPI api = impl;
registerBeanFactory(api);
final Content content = mockery.mock(Content.class);
final Field field = mockery.mock(Field.class);
final FieldValue value = mockery.mock(FieldValue.class);
final Map<String, Field> fieldMap = mockery.mock(Map.class);
final ContentType type = mockery.mock(ContentType.class);
final Map<String, RepresentationDef> reps = mockery.mock(Map.class, "repMap");
final RepresentationDef def = mockery.mock(RepresentationDef.class);
mockery.checking(new Expectations() {
{
exactly(1).of(template).getTemplateType();
will(returnValue(TemplateType.VELOCITY));
exactly(1).of(template).getTemplate();
will(returnValue(IOUtils.toByteArray(getClass().getClassLoader().getResourceAsStream("scripts/velocity/test-template.vm"))));
exactly(1).of(template).getName();
will(returnValue(REP_NAME));
exactly(1).of(value).getValue();
will(returnValue(CONTENT));
exactly(1).of(field).getValue();
will(returnValue(value));
exactly(1).of(fieldMap).get(with(Expectations.<String>anything()));
will(returnValue(field));
exactly(1).of(content).getFields();
will(returnValue(fieldMap));
exactly(1).of(content).getContentDefinition();
will(returnValue(type));
final ContentId contentId = mockery.mock(ContentId.class);
exactly(2).of(content).getContentId();
will(returnValue(contentId));
final WorkspaceId wId = mockery.mock(WorkspaceId.class);
exactly(1).of(contentId).getWorkspaceId();
will(returnValue(wId));
exactly(2).of(type).getRepresentationDefs();
will(returnValue(reps));
exactly(2).of(reps).get(with(REP_NAME));
will(returnValue(def));
exactly(1).of(def).getParameters();
will(returnValue(Collections.emptyMap()));
exactly(1).of(def).getMIMEType();
will(returnValue(GroovyGeneratorTest.MIME_TYPE));
final ResourceUri rUri = mockery.mock(ResourceUri.class);
exactly(1).of(def).getResourceUri();
will(returnValue(rUri));
exactly(1).of(rUri).getValue();
will(returnValue("iUri"));
}
});
Representation representation = provider.getRepresentation(REP_NAME, type, content);
Assert.assertNotNull(representation);
Assert.assertEquals(REP_NAME, representation.getName());
Assert.assertEquals(CONTENT, StringUtils.newStringUtf8(representation.getRepresentation()));
Assert.assertEquals(GroovyGeneratorTest.MIME_TYPE, representation.getMimeType());
}Example 3
| Project: smart-generator-engine-master File: ReportConfigServiceImpl.java View source code |
@Override
public void save(ReportConfig reportConfig) {
if (reportConfig.getEmbeddedSourceCode() == null && reportConfig.getCodeOnDemand() == null) {
throw new IllegalArgumentException("No code specified!");
}
if (reportConfig.getEmbeddedSourceCode() != null && (reportConfig.getEmbeddedSourceCode().getCode() == null || StringUtils.isBlank(reportConfig.getEmbeddedSourceCode().getCode().getEmbeddedCode()) || reportConfig.getEmbeddedSourceCode().getCode().getCodeType() == null)) {
throw new IllegalArgumentException("Embedded source code not specified properly!");
}
if (getSchedules(reportConfig, null) == null) {
throw new IllegalArgumentException("No schedules from report!");
}
resetScheduleGeneration(reportConfig);
commonWriteDao.save(reportConfig);
}Example 4
| Project: astyanax-master File: AbstractColumnListMutationImpl.java View source code |
@Override
public ColumnListMutation<C> putCompressedColumn(C columnName, String value, Integer ttl) {
Preconditions.checkNotNull(value, "Can't insert null value");
if (value == null) {
putEmptyColumn(columnName, ttl);
return this;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(StringUtils.getBytesUtf8(value));
gzip.close();
return this.putColumn(columnName, ByteBuffer.wrap(out.toByteArray()), ttl);
} catch (IOException e) {
throw new RuntimeException("Error compressing column " + columnName, e);
}
}Example 5
| Project: couchbasekafka-master File: CBMessageConsumer.java View source code |
/**
* read messages from CB TAP
* @return
* @throws IOException
*/
public void run() {
LOGGER.info("RUNNING Couchbase Consumer");
//If TAP Client is not running.
if (tapClient == null) {
try {
initTapClient();
} catch (com.couchbase.client.vbucket.ConfigurationException e) {
tapClient = null;
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Not able to connect to Couchbase. Will retry in " + ConfigLoader.getProp(Constants.INTERVAL_SEC, Constants.INTERVAL_SEC_DEF) + " seconds.");
}
return;
}
}
//If a valid Kafka producer doesn't exist. Try after 2 minutes
if (!CBKafkaProducer.isValidProducer()) {
LOGGER.info("No Kafka Connection. Retry after " + ConfigLoader.getProp(Constants.INTERVAL_SEC, Constants.INTERVAL_SEC_DEF) + " seconds.");
return;
}
int iReadCounter = 0;
try {
//Keep reading from Tap Client
while (tapClient.hasMoreMessages()) {
//Read message from TAP client
final ResponseMessage resmessage = tapClient.getNextMessage();
if (resmessage != null) {
if (resmessage.getValue() != null) {
iReadCounter++;
//Publish message to Kafka.
CBKafkaProducer.publishMessage(resmessage.getKey(), StringUtils.newStringUtf8(resmessage.getValue()));
if (iReadCounter % 3 == 0) {
iReadCounter = 0;
if (LOGGER.isInfoEnabled())
LOGGER.info("TIME :" + new java.util.Date().getTime());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
if (LOGGER.isErrorEnabled())
LOGGER.error("EXCEPTION. TIME :" + new java.util.Date().getTime());
}
}Example 6
| Project: kodex-master File: Encryptable.java View source code |
protected Encryptable<T> encryptWith(CryptoService crypto) throws SecurityConfigurationException, IOException, ClassNotFoundException {
Preconditions.checkNotNull(crypto);
int total = getBlockCount();
List<BlockCiphertext> ciphertextBlocks = Lists.newArrayListWithCapacity(total);
// encrypt all our plaintext blocks
Iterable<byte[]> plainBlocks = getChunkingStrategy().split(getData());
for (byte[] block : plainBlocks) {
ciphertextBlocks.add(crypto.encrypt(block));
}
Preconditions.checkState(ciphertextBlocks.size() == total, "Block count doesn't match iterable length");
EncryptableBlock[] blocks = new EncryptableBlock[total];
BlockCiphertext encryptedClassName = crypto.encrypt(StringUtils.getBytesUtf8(getClassName()));
for (int i = 0; i < total; ++i) {
BlockCiphertext ciphertext = ciphertextBlocks.get(i);
boolean isLast = i == total - 1;
blocks[i] = new EncryptableBlock(ciphertext, hashFunction.hashBytes(ciphertext.getContents()).asBytes(), i, isLast, encryptedClassName, getChunkingStrategy(), DateTime.now());
}
return new Encryptable<T>(blocks, encryptedClassName, cryptoServiceId);
}Example 7
| Project: ovirt-engine-master File: GetGlusterHookContentQuery.java View source code |
@Override
protected void executeQueryCommand() {
GlusterHookEntity hook = glusterHooksDao.getById(getParameters().getGlusterHookId());
String content = "";
if (getParameters().getGlusterServerId() == null) {
if (hook.getContentType().equals(GlusterHookContentType.TEXT)) {
content = glusterHooksDao.getGlusterHookContent(getParameters().getGlusterHookId());
}
} else {
GlusterServerHook serverHook = glusterHooksDao.getGlusterServerHook(hook.getId(), getParameters().getGlusterServerId());
if (serverHook != null && serverHook.getContentType() == GlusterHookContentType.TEXT) {
VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHookContent, new GlusterHookVDSParameters(getParameters().getGlusterServerId(), hook.getGlusterCommand(), hook.getStage(), hook.getName()));
if (returnValue.getSucceeded()) {
content = (String) returnValue.getReturnValue();
}
}
}
content = StringUtils.newStringUtf8(Base64.decodeBase64(content));
getQueryReturnValue().setReturnValue(content);
}Example 8
| Project: rhizome-master File: TypeReferenceValueMapper.java View source code |
@Override
public V fromBytes(byte[] data) throws MappingException {
try {
return data == null ? null : mapper.readValue(data, reference);
} catch (IOException e) {
logger.error("Unable to unmarshall data from {}, as string: {}", data, StringUtils.newStringUtf8(data), e);
throw new MappingException("Error unmarshalling data.");
}
}Example 9
| Project: zeroth-master File: StringUtilsTest.java View source code |
@Test
public void test() {
String testee = org.apache.commons.lang3.StringUtils.EMPTY;
assertThat(StringUtils.getBytesUnchecked(testee, "UTF-8"), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.getBytesIso8859_1(testee), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.getBytesUsAscii(testee), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.getBytesUtf8(testee), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.getBytesUtf16(testee), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.getBytesUtf16Le(testee), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.getBytesUtf16Be(testee), is(ArrayUtils.EMPTY_BYTE_ARRAY));
assertThat(StringUtils.newString(ArrayUtils.EMPTY_BYTE_ARRAY, "UTF-8"), is(testee));
assertThat(StringUtils.newStringIso8859_1(ArrayUtils.EMPTY_BYTE_ARRAY), is(testee));
assertThat(StringUtils.newStringUsAscii(ArrayUtils.EMPTY_BYTE_ARRAY), is(testee));
assertThat(StringUtils.newStringUtf8(ArrayUtils.EMPTY_BYTE_ARRAY), is(testee));
assertThat(StringUtils.newStringUtf16(ArrayUtils.EMPTY_BYTE_ARRAY), is(testee));
assertThat(StringUtils.newStringUtf16Le(ArrayUtils.EMPTY_BYTE_ARRAY), is(testee));
assertThat(StringUtils.newStringUtf16Be(ArrayUtils.EMPTY_BYTE_ARRAY), is(testee));
}Example 10
| Project: BlinkCoder-master File: QiNiu.java View source code |
public static JSONObject callbackUEditor(String upload_ret) {
JSONObject callback = JSONObject.parseObject(StringUtils.newStringUtf8(Base64.decodeBase64(upload_ret)));
JSONObject json = new JSONObject();
if (callback.containsKey("error")) {
json.put("state", callback.get("error"));
} else {
json.put("original", callback.get("name"));
json.put("url", callback.get("key") + "-v001");
json.put("state", "SUCCESS");
}
return json;
}Example 11
| Project: HTML5-Player-deprecated-master File: LoadUtils.java View source code |
public static ProjectData loadDatafromZipStream(ZipArchiveInputStream zip) throws IOException {
String xml = "";
Map<String, String> images = new HashMap<String, String>();
Map<String, String> sounds = new HashMap<String, String>();
ZipEntry zipEntry;
StringBuilder s = new StringBuilder();
while ((zipEntry = zip.getNextZipEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
CatrobatDebug.debug(zipEntry.getName() + " " + zipEntry.isDirectory() + " " + zipEntry.toString());
if (zipEntry.getName().endsWith(".xml")) {
while ((read = zip.read(buffer, 0, 1024)) >= 0) {
s.append(new String(buffer, 0, read));
}
xml = s.toString();
xml = xml.replaceAll("<url>(.*?)</url>", "<url></url>");
} else if (!zipEntry.getName().endsWith(".nomedia")) {
if (zipEntry.getName().contains("images/")) {
while ((read = zip.read(buffer, 0, 1024)) >= 0) {
baos.write(buffer, 0, read);
}
String base64 = StringUtils.newStringUtf8(Base64.encodeBase64(baos.toByteArray()));
base64 = "data:image/" + LoadUtils.getFileExtension(zipEntry.getName()) + ";base64," + base64;
images.put(zipEntry.getName().replaceFirst("images/", ""), base64);
} else if (zipEntry.getName().contains("sounds/")) {
while ((read = zip.read(buffer, 0, 1024)) >= 0) {
baos.write(buffer, 0, read);
}
String base64 = StringUtils.newStringUtf8(Base64.encodeBase64(baos.toByteArray()));
base64 = "data:audio/" + LoadUtils.getFileExtension(zipEntry.getName()) + ";base64," + base64;
sounds.put(zipEntry.getName().replaceFirst("sounds/", ""), base64);
}
}
}
if (xml == "") {
return null;
}
return new ProjectData(xml, images, sounds);
}Example 12
| Project: kie-wb-common-master File: SVGIconRendererTest.java View source code |
protected void initDataURI(final String header, final InputStream imageStream) throws Exception {
renderer.render(resource);
when(resource.getResource()).thenReturn(dataResource);
when(dataResource.getSafeUri()).thenReturn(safeUri);
StringBuilder sb = new StringBuilder();
sb.append(header);
sb.append(StringUtils.newStringUtf8(Base64.encodeBase64(IOUtils.toByteArray(imageStream))));
when(safeUri.asString()).thenReturn(sb.toString());
}Example 13
| Project: support-tools-master File: VpsDao.java View source code |
public static String sendPost(String url, HashMap<String, String> jSonQuery) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
String urlParameters = "";
Object[] keys = jSonQuery.keySet().toArray();
for (int i = 0; i < keys.length; i++) {
String key = (String) keys[i];
urlParameters += key + "=" + jSonQuery.get(key);
if (!(i == keys.length - 1))
urlParameters += "&";
}
con.setDoOutput(true);
System.out.println("Передаю параметры: " + urlParameters);
OutputStream os = con.getOutputStream();
os.write(StringUtils.getBytesUtf8(urlParameters));
os.flush();
os.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result = in.readLine();
// result = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(result);
byte[] bytes = result.getBytes();
result = new String(bytes, "UTF-8");
System.out.println("Ответ: " + result);
in.close();
return result;
}Example 14
| Project: typhon-master File: AppleRechargingHandler.java View source code |
@Override
public RechargingBO handle(JSONObject json) throws TradeValidatedException {
String uri;
if ("Sandbox".equalsIgnoreCase(json.getString("environment"))) {
uri = SANDBOX_URL;
} else {
uri = VERIFY_URL;
}
CloseableHttpClient hc = HC_BUILDER.build();
HttpPost post = new HttpPost(uri);
List<NameValuePair> nvps = new ArrayList<>();
String receiptStr = json.getString("data");
Matcher m = P.matcher(receiptStr);
m.find();
String signature = m.group(2).replaceAll(" ", "+");
receiptStr = receiptStr.replace(m.group(2), signature);
String receiptData = org.skfiy.typhon.rnsd.Base64.encodeBytes(receiptStr.getBytes());
JSONObject receiptJson = new JSONObject();
receiptJson.put("receipt-data", receiptData);
try {
post.setEntity(new StringEntity(receiptJson.toJSONString(), ContentType.APPLICATION_JSON));
CloseableHttpResponse resp = hc.execute(post);
String str = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
JSONObject result = JSON.parseObject(str);
if (result.getIntValue("status") != 0) {
throw new TradeValidatedException("success", "no verify");
}
JSONObject receipt = result.getJSONObject("receipt");
// result
Recharging recharging = new Recharging();
recharging.setTradeId(receipt.getString("transaction_id"));
recharging.setPlatform(Platform.apple.getLabel());
String callbackInfo = StringUtils.newStringUtf8(Base64.decodeBase64(json.getString("callbackInfo")));
JSONObject extra = JSON.parseObject(callbackInfo);
recharging.setUid(extra.getString("uid"));
recharging.setRegion(extra.getString("region"));
recharging.setGoods(extra.getString("goods"));
LOG.debug("{}", extra);
recharging.setAmount(extra.getInteger("goods"));
recharging.setCreationTime(System.currentTimeMillis() / 1000);
recharging.setChannel(Platform.apple.getLabel());
return (new RechargingBO(recharging, "success"));
} catch (Exception ex) {
throw new TradeValidatedException("success", ex.getMessage());
} finally {
try {
hc.close();
} catch (IOException ex) {
}
}
}Example 15
| Project: automately-core-master File: ApiHandler.java View source code |
@Override
public void handle(HttpServerRequest req) {
// Set the content type firstx
req.response().setContentType("application/json");
/**
* Begin Authorization
*/
User mUser = null;
boolean authenticated = false;
if (req.headers().contains(HttpHeaders.Names.AUTHORIZATION)) {
String authString = req.headers().get(HttpHeaders.Names.AUTHORIZATION);
if (authString.split(" ").length > 1) {
authString = authString.split(" ")[1];
String decodedAuth = org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.decode(authString));
if (decodedAuth != null) {
if (decodedAuth.split(":").length > 1) {
String username = decodedAuth.split(":")[0].trim();
String key = decodedAuth.split(":")[1].trim();
if (!username.equals("") && !key.equals("") && UserData.getUserByUsername(username) != null) {
User user = UserData.getUserByUsername(username);
if (user != null) {
if (UserData.validateUserKey(user, key)) {
mUser = user;
authenticated = true;
}
}
}
}
}
}
}
// Default Unauthorized if we are not authenticated
if (!authenticated && secure) {
if (!handleUnauthorized(req)) {
req.response().putHeader(HttpHeaders.Names.WWW_AUTHENTICATE, "Basic realm=\"username and api key required\"");
errorResponse(req, "Unauthorized", "You are unauthorized to make this request", 401);
return;
}
}
final User finalUser = mUser;
try {
handleAuthorized(req, finalUser);
} catch (Exception e) {
errorResponse(req, "API Error", e.getMessage(), 500);
}
}Example 16
| Project: cas-master File: AcceptUsersAuthenticationHandler.java View source code |
@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);
}Example 17
| Project: commafeed-master File: FeedFetcher.java View source code |
public FetchedFeed fetch(String feedUrl, boolean extractFeedUrlFromHtml, String lastModified, String eTag, Date lastPublishedDate, String lastContentHash) throws FeedException, ClientProtocolException, IOException, NotModifiedException {
log.debug("Fetching feed {}", feedUrl);
FetchedFeed fetchedFeed = null;
int timeout = 20000;
HttpResult result = getter.getBinary(feedUrl, lastModified, eTag, timeout);
byte[] content = result.getContent();
try {
fetchedFeed = parser.parse(result.getUrlAfterRedirect(), content);
} catch (FeedException e) {
if (extractFeedUrlFromHtml) {
String extractedUrl = extractFeedUrl(StringUtils.newStringUtf8(result.getContent()), feedUrl);
if (org.apache.commons.lang3.StringUtils.isNotBlank(extractedUrl)) {
feedUrl = extractedUrl;
result = getter.getBinary(extractedUrl, lastModified, eTag, timeout);
content = result.getContent();
fetchedFeed = parser.parse(result.getUrlAfterRedirect(), content);
} else {
throw e;
}
} else {
throw e;
}
}
if (content == null) {
throw new IOException("Feed content is empty.");
}
String hash = DigestUtils.sha1Hex(content);
if (lastContentHash != null && hash != null && lastContentHash.equals(hash)) {
log.debug("content hash not modified: {}", feedUrl);
throw new NotModifiedException("content hash not modified");
}
if (lastPublishedDate != null && fetchedFeed.getFeed().getLastPublishedDate() != null && lastPublishedDate.getTime() == fetchedFeed.getFeed().getLastPublishedDate().getTime()) {
log.debug("publishedDate not modified: {}", feedUrl);
throw new NotModifiedException("publishedDate not modified");
}
Feed feed = fetchedFeed.getFeed();
feed.setLastModifiedHeader(result.getLastModifiedSince());
feed.setEtagHeader(FeedUtils.truncate(result.getETag(), 255));
feed.setLastContentHash(hash);
fetchedFeed.setFetchDuration(result.getDuration());
fetchedFeed.setUrlAfterRedirect(result.getUrlAfterRedirect());
return fetchedFeed;
}Example 18
| Project: gocd-master File: DigestObjectPoolsTest.java View source code |
@Test
public void shouldResetDigestForFutureUsage() {
DigestObjectPools.DigestOperation operation = new DigestObjectPools.DigestOperation() {
public String perform(MessageDigest digest) throws IOException {
digest.update(org.apache.commons.codec.binary.StringUtils.getBytesUtf8("foo"));
return Hex.encodeHexString(digest.digest());
}
};
String shaFirst = pools.computeDigest(DigestObjectPools.SHA_256, operation);
String shaSecond = pools.computeDigest(DigestObjectPools.SHA_256, operation);
assertThat(shaFirst, is(shaSecond));
}Example 19
| Project: hudson-perforce-plugin-master File: PerforcePasswordEncryptor.java View source code |
public String encryptString(String toEncrypt) {
if (toEncrypt == null || toEncrypt.trim().length() == 0)
return "";
SecretKey key = desKeyFromString(keyString);
Cipher cipher = desCipherForModeWithKey(Cipher.ENCRYPT_MODE, key);
byte[] encryptedtext = null;
try {
encryptedtext = cipher.doFinal(toEncrypt.getBytes());
} catch (IllegalBlockSizeException ibse) {
System.err.println(ibse);
} catch (BadPaddingException bpe) {
System.err.println(bpe);
}
String encodedString = StringUtils.newStringUtf8(Base64.encodeBase64(encryptedtext, false));
return ENCRYPTION_PREFIX + encodedString;
}Example 20
| Project: hudson_plugins-master File: PerforcePasswordEncryptor.java View source code |
public String encryptString(String toEncrypt) {
if (toEncrypt == null || toEncrypt.trim().length() == 0)
return "";
SecretKey key = desKeyFromString(keyString);
Cipher cipher = desCipherForModeWithKey(Cipher.ENCRYPT_MODE, key);
byte[] encryptedtext = null;
try {
encryptedtext = cipher.doFinal(toEncrypt.getBytes());
} catch (IllegalBlockSizeException ibse) {
System.err.println(ibse);
} catch (BadPaddingException bpe) {
System.err.println(bpe);
}
String encodedString = StringUtils.newStringUtf8(Base64.encodeBase64(encryptedtext, false));
return ENCRYPTION_PREFIX + encodedString;
}Example 21
| Project: perforce-plugin-master File: PerforcePasswordEncryptor.java View source code |
@Nonnull
public String encryptString(@CheckForNull String toEncrypt) {
if (toEncrypt == null || toEncrypt.trim().length() == 0)
return "";
SecretKey key = desKeyFromString(keyString);
Cipher cipher = desCipherForModeWithKey(Cipher.ENCRYPT_MODE, key);
byte[] encryptedtext = null;
try {
encryptedtext = cipher.doFinal(toEncrypt.getBytes());
} catch (IllegalBlockSizeException ibse) {
System.err.println(ibse);
} catch (BadPaddingException bpe) {
System.err.println(bpe);
}
String encodedString = StringUtils.newStringUtf8(Base64.encodeBase64(encryptedtext, false));
return ENCRYPTION_PREFIX + encodedString;
}Example 22
| Project: rce-master File: DefaultEncryption.java View source code |
@Override
public String encrypt(String text, Key key) {
String errorMessage = "encrypting text failed";
try {
Cipher cipher = Cipher.getInstance(algorithm.getName());
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(text.getBytes());
byte[] encoded = Base64.encodeBase64(encrypted);
return StringUtils.newStringUtf8(encoded);
} catch (NoSuchAlgorithmException e) {
LOG.error(errorMessage, e);
return null;
} catch (NoSuchPaddingException e) {
LOG.error(errorMessage, e);
return null;
} catch (InvalidKeyException e) {
LOG.error(errorMessage, e);
return null;
} catch (IllegalBlockSizeException e) {
LOG.error(errorMessage, e);
return null;
} catch (BadPaddingException e) {
LOG.error(errorMessage, e);
return null;
}
}Example 23
| Project: SinrelLauncherEngine-Dev-master File: AES.java View source code |
// Private methods
public static String encryptAESBase64String(String text, byte[] key) throws GeneralSecurityException {
SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, getIVSpec());
byte[] padded = padByteArray(StringUtils.getBytesUtf8(text));
byte[] encrypted = cipher.doFinal(padded);
return Base64.encodeBase64URLSafeString(encrypted);
}Example 24
| Project: smart-user-master File: Utils.java View source code |
public static String readStringInUTF8(DataInput in) throws IOException, UnsupportedEncodingException {
int allocationBlockSize = 2000;
int capacity = allocationBlockSize;
int length = 0;
ByteBuffer buffer = ByteBuffer.allocate(allocationBlockSize);
boolean notEof = true;
while (notEof) {
try {
buffer.put(in.readByte());
if (++length >= capacity) {
capacity += allocationBlockSize;
buffer.limit(capacity);
}
} catch (EOFException ex) {
notEof = false;
}
}
String string = StringUtils.newStringUtf8(Arrays.copyOf(buffer.array(), length));
return string;
}Example 25
| Project: cloudify-master File: PrivateEC2CloudifyDriver.java View source code |
private void setPrivateEc2Template() throws CloudProvisioningException {
if (!management) {
// not management. check if a specific template was set for this service
this.privateEc2Template = cfnTemplatePerService.get(this.serviceName);
if (this.privateEc2Template != null) {
logger.fine("Found service-specific template for service: " + serviceName);
return;
}
}
String cfnTemplateFileName = null;
File cloudDirectory = null;
if (management) {
ComputeTemplate computeTemplate = this.getManagerComputeTemplate();
cfnTemplateFileName = (String) computeTemplate.getCustom().get("cfnManagerTemplate");
if (StringUtils.isBlank(cfnTemplateFileName)) {
throw new CloudProvisioningException("cfnManagerTemplate value not set on management template");
}
cloudDirectory = new ProvisioningContextAccess().getManagementProvisioiningContext().getCloudFile().getParentFile();
} else {
logger.fine("Using template: " + cloudTemplateName);
ComputeTemplate computeTemplate = cloud.getCloudCompute().getTemplates().get(cloudTemplateName);
cfnTemplateFileName = (String) computeTemplate.getCustom().get("cfnTemplate");
if (StringUtils.isBlank(cfnTemplateFileName)) {
throw new CloudProvisioningException("cfnTemplate value not set on template: " + cloudTemplateName);
}
cloudDirectory = new ProvisioningContextAccess().getProvisioiningContext().getCloudFile().getParentFile();
}
try {
logger.fine("using template: " + cfnTemplateFileName + " from directory: " + cloudDirectory);
this.cloud.getCustom().put("###CLOUD_DIRECTORY###", cloudDirectory);
this.privateEc2Template = this.getPrivateEc2TemplateFromFile(cloudDirectory, cfnTemplateFileName);
} catch (Exception e) {
throw new CloudProvisioningException("Failed to read template from file : " + cfnTemplateFileName + ", reported error: " + e.getMessage(), e);
}
}Example 26
| Project: dianping-open-sdk-master File: ApiTool.java View source code |
public static String sign(String appKey, String secret, Map<String, String> paramMap) {
// 对å?‚æ•°å??进行å—典排åº?
String[] keyArray = paramMap.keySet().toArray(new String[0]);
Arrays.sort(keyArray);
// 拼接有åº?çš„å?‚æ•°å??-值串
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(appKey);
for (String key : keyArray) {
stringBuilder.append(key).append(paramMap.get(key));
}
stringBuilder.append(secret);
String codes = stringBuilder.toString();
// SHA-1ç¼–ç ?, 这里使用的是Apache
// codec,å?³å?¯èŽ·å¾—ç¾å??(shaHex()ä¼šé¦–å…ˆå°†ä¸æ–‡è½¬æ?¢ä¸ºUTF8ç¼–ç ?ç„¶å?Žè¿›è¡Œsha1计算,使用其他的工具包请注æ„?UTF8ç¼–ç ?转æ?¢)
/*
* 以下sha1ç¾å??代ç ?效果ç‰å?Œ byte[] sha =
* org.apache.commons.codec.digest.DigestUtils
* .sha(org.apache.commons.codec
* .binary.StringUtils.getBytesUtf8(codes)); String sign =
* org.apache.commons
* .codec.binary.Hex.encodeHexString(sha).toUpperCase();
*/
String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
return sign;
}Example 27
| Project: differ-master File: UserManager.java View source code |
private String getPasswordSalt() {
try {
SecureRandom saltGen = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[64];
saltGen.nextBytes(salt);
return StringUtils.newStringUtf8(salt);
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Unable to find SHA1PRNG provider to generate salts.");
e.printStackTrace();
}
return null;
}Example 28
| Project: jetty-session-hbase-master File: SessionDataId.java View source code |
@Override
public void readExternal(DataInput input) throws IOException, ClassNotFoundException {
String idString = readStringInUTF8(input);
if (logger.isInfoEnabled()) {
logger.info("Trying to parse session data id: " + idString);
}
if (org.apache.commons.lang.StringUtils.isBlank(idString)) {
throw new IOException("No content!");
}
String[] params = idString.split(":");
if (params == null || params.length != 3) {
throw new IOException("Object should have been in the format id:canonicalpath:virtualhost");
}
setInClusterId(params[0]);
setCanonicalContextPath(params[1]);
setVirtualHost(params[2]);
}Example 29
| Project: sakai-cle-master File: BaseExternalCalendarSubscriptionService.java View source code |
protected String getUniqueIdBasedOnFields(String displayName, String description, String type, String location) {
StringBuffer key = new StringBuffer();
key.append(displayName + description + type + location);
String id = null;
int n = 0;
boolean unique = false;
while (!unique) {
byte[] bytes = key.toString().getBytes();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(bytes);
bytes = digest.digest();
id = getHexStringFromBytes(bytes);
} catch (NoSuchAlgorithmException e) {
byte[] encoded = Base64.encodeBase64(bytes);
id = StringUtils.newStringUtf8(encoded);
}
if (!m_storage.containsKey(id))
unique = true;
else
key.append(n++);
}
return id;
}Example 30
| Project: smart-event-hub-master File: Utils.java View source code |
public static String readStringInUTF8(DataInput in) throws IOException, UnsupportedEncodingException {
int allocationBlockSize = 2000;
int capacity = allocationBlockSize;
int length = 0;
ByteBuffer buffer = ByteBuffer.allocate(allocationBlockSize);
boolean notEof = true;
while (notEof) {
try {
buffer.put(in.readByte());
if (++length >= capacity) {
capacity += allocationBlockSize;
buffer.limit(capacity);
}
} catch (EOFException ex) {
notEof = false;
}
}
String string = StringUtils.newStringUtf8(Arrays.copyOf(buffer.array(), length));
return string;
}Example 31
| Project: commons-codec-master File: RFC1522Codec.java View source code |
/**
* 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();
}Example 32
| Project: External-Projects-master File: RFC1522Codec.java View source code |
/**
* 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();
}Example 33
| Project: gwt-commons-codec-master File: Sha2Crypt.java View source code |
/**
* Generates a libc6 crypt() compatible "$5$" or "$6$" SHA2 based hash value.
* <p>
* This is a nearly line by line conversion of the original C function. The numbered comments are from the algorithm
* description, the short C-style ones from the original C code and the ones with "Remark" from me.
* <p>
* See {@link Crypt#crypt(String, String)} for details.
*
* @param keyBytes
* plaintext to hash
* @param salt
* real salt value without prefix or "rounds="
* @param saltPrefix
* either $5$ or $6$
* @param blocksize
* a value that differs between $5$ and $6$
* @param algorithm
* {@link MessageDigest} algorithm identifier string
* @return complete hash value including prefix and salt
* @throws IllegalArgumentException
* if the given salt is <code>null</code> or does not match the allowed pattern
* @throws IllegalArgumentException
* when a {@link NoSuchAlgorithmException} is caught
* @see MessageDigestAlgorithms
*/
private static String sha2Crypt(final byte[] keyBytes, final String salt, final String saltPrefix, final int blocksize, final String algorithm) {
final int keyLen = keyBytes.length;
// Extracts effective salt and the number of rounds from the given salt.
int rounds = ROUNDS_DEFAULT;
boolean roundsCustom = false;
if (salt == null) {
throw new IllegalArgumentException("Salt must not be null");
}
final MatchResult m = SALT_PATTERN.exec(salt);
if (m == null) {
throw new IllegalArgumentException("Invalid salt value: " + salt);
}
if (m.getGroup(3) != null) {
rounds = Integer.parseInt(m.getGroup(3));
rounds = Math.max(ROUNDS_MIN, Math.min(ROUNDS_MAX, rounds));
roundsCustom = true;
}
final String saltString = m.getGroup(4);
final byte[] saltBytes = StringUtils.getBytesUtf8(saltString);
final int saltLen = saltBytes.length;
// 1. start digest A
// Prepare for the real work.
MessageDigest ctx = DigestUtils.getDigest(algorithm);
// 2. the password string is added to digest A
/*
* Add the key string.
*/
ctx.update(keyBytes);
// 3. the salt string is added to digest A. This is just the salt string
// itself without the enclosing '$', without the magic salt_prefix $5$ and
// $6$ respectively and without the rounds=<N> specification.
//
// NB: the MD5 algorithm did add the $1$ salt_prefix. This is not deemed
// necessary since it is a constant string and does not add security
// and /possibly/ allows a plain text attack. Since the rounds=<N>
// specification should never be added this would also create an
// inconsistency.
/*
* The last part is the salt string. This must be at most 16 characters and it ends at the first `$' character
* (for compatibility with existing implementations).
*/
ctx.update(saltBytes);
// 4. start digest B
/*
* Compute alternate sha512 sum with input KEY, SALT, and KEY. The final result will be added to the first
* context.
*/
MessageDigest altCtx = DigestUtils.getDigest(algorithm);
// 5. add the password to digest B
/*
* Add key.
*/
altCtx.update(keyBytes);
// 6. add the salt string to digest B
/*
* Add salt.
*/
altCtx.update(saltBytes);
// 7. add the password again to digest B
/*
* Add key again.
*/
altCtx.update(keyBytes);
// 8. finish digest B
/*
* Now get result of this (32 bytes) and add it to the other context.
*/
byte[] altResult = altCtx.digest();
// 9. For each block of 32 or 64 bytes in the password string (excluding
// the terminating NUL in the C representation), add digest B to digest A
/*
* Add for any character in the key one byte of the alternate sum.
*/
/*
* (Remark: the C code comment seems wrong for key length > 32!)
*/
int cnt = keyBytes.length;
while (cnt > blocksize) {
ctx.update(altResult, 0, blocksize);
cnt -= blocksize;
}
// 10. For the remaining N bytes of the password string add the first
// N bytes of digest B to digest A
ctx.update(altResult, 0, cnt);
// 11. For each bit of the binary representation of the length of the
// password string up to and including the highest 1-digit, starting
// from to lowest bit position (numeric value 1):
//
// a) for a 1-digit add digest B to digest A
//
// b) for a 0-digit add the password string
//
// NB: this step differs significantly from the MD5 algorithm. It
// adds more randomness.
/*
* Take the binary representation of the length of the key and for every 1 add the alternate sum, for every 0
* the key.
*/
cnt = keyBytes.length;
while (cnt > 0) {
if ((cnt & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(keyBytes);
}
cnt >>= 1;
}
// 12. finish digest A
/*
* Create intermediate result.
*/
altResult = ctx.digest();
// 13. start digest DP
/*
* Start computation of P byte sequence.
*/
altCtx = DigestUtils.getDigest(algorithm);
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= keyLen; i++) {
altCtx.update(keyBytes);
}
// 15. finish digest DP
/*
* Finish the digest.
*/
byte[] tempResult = altCtx.digest();
// 16. produce byte sequence P of the same length as the password where
//
// a) for each block of 32 or 64 bytes of length of the password string
// the entire digest DP is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DP
/*
* Create byte sequence P.
*/
final byte[] pBytes = new byte[keyLen];
int cp = 0;
while (cp < keyLen - blocksize) {
System.arraycopy(tempResult, 0, pBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, pBytes, cp, keyLen - cp);
// 17. start digest DS
/*
* Start computation of S byte sequence.
*/
altCtx = DigestUtils.getDigest(algorithm);
/*
* For every character in the password add the entire password.
*/
for (int i = 1; i <= 16 + (altResult[0] & 0xff); i++) {
altCtx.update(saltBytes);
}
// 19. finish digest DS
/*
* Finish the digest.
*/
tempResult = altCtx.digest();
// 20. produce byte sequence S of the same length as the salt string where
//
// a) for each block of 32 or 64 bytes of length of the salt string
// the entire digest DS is used
//
// b) for the remaining N (up to 31 or 63) bytes use the first N
// bytes of digest DS
/*
* Create byte sequence S.
*/
// Remark: The salt is limited to 16 chars, how does this make sense?
final byte[] sBytes = new byte[saltLen];
cp = 0;
while (cp < saltLen - blocksize) {
System.arraycopy(tempResult, 0, sBytes, cp, blocksize);
cp += blocksize;
}
System.arraycopy(tempResult, 0, sBytes, cp, saltLen - cp);
/*
* Repeatedly run the collected hash value through sha512 to burn CPU cycles.
*/
for (int i = 0; i <= rounds - 1; i++) {
// a) start digest C
/*
* New context.
*/
ctx = DigestUtils.getDigest(algorithm);
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(pBytes, 0, keyLen);
} else {
ctx.update(altResult, 0, blocksize);
}
/*
* Add salt for numbers not divisible by 3.
*/
if (i % 3 != 0) {
ctx.update(sBytes, 0, saltLen);
}
/*
* Add key for numbers not divisible by 7.
*/
if (i % 7 != 0) {
ctx.update(pBytes, 0, keyLen);
}
/*
* Add key or last result.
*/
if ((i & 1) != 0) {
ctx.update(altResult, 0, blocksize);
} else {
ctx.update(pBytes, 0, keyLen);
}
// h) finish digest C.
/*
* Create intermediate result.
*/
altResult = ctx.digest();
}
// 22. Produce the output string. This is an ASCII string of the maximum
// size specified above, consisting of multiple pieces:
//
// a) the salt salt_prefix, $5$ or $6$ respectively
//
// b) the rounds=<N> specification, if one was present in the input
// salt string. A trailing '$' is added in this case to separate
// the rounds specification from the following text.
//
// c) the salt string truncated to 16 characters
//
// d) a '$' character
/*
* Now we can construct the result string. It consists of three parts.
*/
final StringBuilder buffer = new StringBuilder(saltPrefix);
if (roundsCustom) {
buffer.append(ROUNDS_PREFIX);
buffer.append(rounds);
buffer.append("$");
}
buffer.append(saltString);
buffer.append("$");
if (blocksize == 32) {
B64.b64from24bit(altResult[0], altResult[10], altResult[20], 4, buffer);
B64.b64from24bit(altResult[21], altResult[1], altResult[11], 4, buffer);
B64.b64from24bit(altResult[12], altResult[22], altResult[2], 4, buffer);
B64.b64from24bit(altResult[3], altResult[13], altResult[23], 4, buffer);
B64.b64from24bit(altResult[24], altResult[4], altResult[14], 4, buffer);
B64.b64from24bit(altResult[15], altResult[25], altResult[5], 4, buffer);
B64.b64from24bit(altResult[6], altResult[16], altResult[26], 4, buffer);
B64.b64from24bit(altResult[27], altResult[7], altResult[17], 4, buffer);
B64.b64from24bit(altResult[18], altResult[28], altResult[8], 4, buffer);
B64.b64from24bit(altResult[9], altResult[19], altResult[29], 4, buffer);
B64.b64from24bit((byte) 0, altResult[31], altResult[30], 3, buffer);
} else {
B64.b64from24bit(altResult[0], altResult[21], altResult[42], 4, buffer);
B64.b64from24bit(altResult[22], altResult[43], altResult[1], 4, buffer);
B64.b64from24bit(altResult[44], altResult[2], altResult[23], 4, buffer);
B64.b64from24bit(altResult[3], altResult[24], altResult[45], 4, buffer);
B64.b64from24bit(altResult[25], altResult[46], altResult[4], 4, buffer);
B64.b64from24bit(altResult[47], altResult[5], altResult[26], 4, buffer);
B64.b64from24bit(altResult[6], altResult[27], altResult[48], 4, buffer);
B64.b64from24bit(altResult[28], altResult[49], altResult[7], 4, buffer);
B64.b64from24bit(altResult[50], altResult[8], altResult[29], 4, buffer);
B64.b64from24bit(altResult[9], altResult[30], altResult[51], 4, buffer);
B64.b64from24bit(altResult[31], altResult[52], altResult[10], 4, buffer);
B64.b64from24bit(altResult[53], altResult[11], altResult[32], 4, buffer);
B64.b64from24bit(altResult[12], altResult[33], altResult[54], 4, buffer);
B64.b64from24bit(altResult[34], altResult[55], altResult[13], 4, buffer);
B64.b64from24bit(altResult[56], altResult[14], altResult[35], 4, buffer);
B64.b64from24bit(altResult[15], altResult[36], altResult[57], 4, buffer);
B64.b64from24bit(altResult[37], altResult[58], altResult[16], 4, buffer);
B64.b64from24bit(altResult[59], altResult[17], altResult[38], 4, buffer);
B64.b64from24bit(altResult[18], altResult[39], altResult[60], 4, buffer);
B64.b64from24bit(altResult[40], altResult[61], altResult[19], 4, buffer);
B64.b64from24bit(altResult[62], altResult[20], altResult[41], 4, buffer);
B64.b64from24bit((byte) 0, (byte) 0, altResult[63], 2, buffer);
}
/*
* Clear the buffer for the intermediate result so that people attaching to processes or reading core dumps
* cannot get any information.
*/
// Is there a better way to do this with the JVM?
Arrays.fill(tempResult, (byte) 0);
Arrays.fill(pBytes, (byte) 0);
Arrays.fill(sBytes, (byte) 0);
ctx.reset();
altCtx.reset();
Arrays.fill(keyBytes, (byte) 0);
Arrays.fill(saltBytes, (byte) 0);
return buffer.toString();
}Example 34
| Project: tor-research-framework-master File: DescriptorExample.java View source code |
// gho's router - request permission before using
//public static String DIRECTORY_SERVER_ADDRESS = "37.187.247.150";
//public static String DIRECTORY_SERVER_PORT = "9030";
// Fallback to a random directory server if either of these are null
// TODO: implement default port 9030?
//public static String DIRECTORY_SERVER_ADDRESS = null;
//public static String DIRECTORY_SERVER_PORT = null;
public static void main(String[] args) {
// Let's only retry twice - we really don't want to get picked up as a DoS attack
// TODO: we could do this much better with a setter method - on the class or on the object?
Consensus.MAX_TRIES = 3;
Consensus con = Consensus.getConsensus();
TreeMap<String, OnionRouter> orMap = new TreeMap<>();
TreeSet<String> requestFingerprintList = new TreeSet<>();
Boolean debugPrintedReply = false;
// Create a map with ROUTER_COUNT random routers with FLAGS, eliminating duplicates
// If there are fewer than ROUTER_COUNT routers with FLAGS, use them all
TreeMap<String, OnionRouter> allWithFlags = con.getORsWithFlag(FLAGS);
if (allWithFlags.size() <= ROUTER_COUNT) {
orMap = allWithFlags;
} else {
while (orMap.size() < ROUTER_COUNT) {
OnionRouter router = con.getRandomORWithFlag(FLAGS);
// But this logic is clearer.
if (!orMap.containsKey(router.identityhash))
orMap.put(router.identityhash, router);
}
}
/*
This code is terribly slow for more than around 10 routers, as it launches a request for every one.
No wonder multiple fingerprints are permitted in a single request!
This code is obsolete and may not work any more.
*/
/*
System.out.println("Retrieve authority descriptors in separate requests");
System.out.println("===================================================");
System.out.println("Retrieving single authority descriptors with optimistic compression...");
for (OnionRouter or: ors.values()) {
try {
String descriptor = con.getRouterDescriptor(or.identityhash);
if (descriptor.startsWith("router ")) {
System.out.println("Successfully retrieved descriptor for fingerprint: " + or.identityhash);
} else {
System.err.println("Consistency checks failed on descriptor for fingerprint: " + or.identityhash);
System.err.println(descriptor);
}
} catch (IOException e) {
System.err.println("IO Error attempting to retrieve single descriptor for fingerprint: " + or.identityhash
+ "\n Error: " + e.toString());
}
}
*/
System.out.println("Retrieve authority descriptors in one request");
System.out.println("=============================================");
System.out.println("Retrieving multiple authority descriptors with optimistic compression...");
// Concatenate the identity hashes together, using "+" as a separator
String fingerprintURLFragment = null;
for (String identityFingerprint : orMap.keySet()) {
// Only for requesting consensuses via an (potentially truncated) authority fingerprint
//String requestFingerprint = StringUtils.left(identityFingerprint, TRUNCATE_FINGERPRINT_CHAR_LENGTH);
String requestFingerprint = null;
if (useConsensusRouters) {
requestFingerprint = identityFingerprint;
}
// Flip a coin to decide whether to replace the fingerprint with a random hex string
if (useRandomHexRouters && (TorCrypto.rnd.nextBoolean() || requestFingerprint == null)) {
byte[] randomHexBytes = new byte[FINGERPRINT_BYTE_LENGTH];
TorCrypto.rnd.nextBytes(randomHexBytes);
// converts to lowercase by default
requestFingerprint = Hex.encodeHexString(randomHexBytes);
// Flip a coin to decide whether to uppercase it
if (TorCrypto.rnd.nextBoolean())
requestFingerprint = requestFingerprint.toUpperCase();
}
// Flip a coin to decide whether to replace the fingerprint with random binary bytes
if (useRandomByteRouters && (TorCrypto.rnd.nextBoolean() || requestFingerprint == null)) {
// Though the name is a little counter-intuitive, in this particular instance
// we want one byte for every character in the fingerprint
byte[] randomBinaryBytes = new byte[FINGERPRINT_CHAR_LENGTH];
TorCrypto.rnd.nextBytes(randomBinaryBytes);
// Because we need to convert bytes to a Charset, then to a URL,
// our ability to manipulate what tor sees is limited by the Java APIs.
// They do an awful lot of sanity checking.
// This code is as close as we can get to sending random binary data to tor,
// without writing a basic HTTP client ourselves.
// And it is hard to replicate requests using binary
// by copying and pasting from various terminals or logs
requestFingerprint = org.apache.commons.codec.binary.StringUtils.newStringIso8859_1(randomBinaryBytes);
}
if (requestFingerprint != null) {
// only record real router fingerprints, not garbage
if (requestFingerprint.equals(identityFingerprint))
requestFingerprintList.add(requestFingerprint);
if (fingerprintURLFragment == null) {
fingerprintURLFragment = requestFingerprint;
} else {
fingerprintURLFragment += "+" + requestFingerprint;
}
}
}
// Now try to retrieve them in a single request
// Either:
// - the InflaterInputStream handles a "concatenated list of zlib-compressed objects" transparently, or
// - few servers send a "concatenated list of zlib-compressed objects"
// (instead choosing a "zlib-compressed concatenated list of objects")
String descriptorReply = null;
try {
if (DIRECTORY_SERVER_ADDRESS != null && DIRECTORY_SERVER_PORT != null) {
// Connect to a specified directory (cache)
// Note: this disables automatic retries
descriptorReply = con.getRouterDescriptor(fingerprintURLFragment, DIRECTORY_SERVER_ADDRESS, DIRECTORY_SERVER_PORT);
} else {
// Connect to a random directory (cache)
// Note: using multiple, random caches may make errors harder to reproduce
descriptorReply = con.getRouterDescriptor(fingerprintURLFragment);
}
System.out.println("Requested descriptors: " + URLUtil.URLEncode(fingerprintURLFragment));
} catch (IOException e) {
System.err.println("IO Error attempting to retrieve descriptor list for " + String.valueOf(orMap.size()) + " fingerprints: " + URLUtil.URLEncode(fingerprintURLFragment) + "\n Error: " + e.toString());
}
// Print what we wanted, what we got, and a comparison
if (descriptorReply != null) {
int descriptorCount = 0;
String descriptorLines[] = descriptorReply.split("\n");
TreeSet<String> replyFingerprints = new TreeSet<>();
for (String line : descriptorLines) {
String fp = null;
// The descriptor fingerprints can have an "opt " in front of them
if (line.startsWith("fingerprint ")) {
fp = line.substring(("fingerprint ").length());
} else if (line.startsWith("opt fingerprint ")) {
fp = line.substring(("opt fingerprint ").length());
} else if (line.startsWith("router ")) {
descriptorCount++;
}
if (fp != null) {
// Match the consensus fingerprints, which are lowercase and contain no whitespace
fp = StringUtils.deleteWhitespace(fp);
fp = fp.toLowerCase();
if (!replyFingerprints.contains(fp))
replyFingerprints.add(fp);
else
System.err.println("Duplicate fingerprint: " + fp + " in reply.");
}
}
// Do our descriptors appear valid, and did we get the right number of them?
if (descriptorReply.startsWith("router ") && descriptorCount == orMap.size()) {
System.out.println("Downloaded " + String.valueOf(descriptorCount) + " descriptors for fingerprints: " + URLUtil.URLEncode(fingerprintURLFragment));
} else {
System.err.println();
System.err.println("Downloaded " + String.valueOf(descriptorCount) + " descriptors for " + String.valueOf(orMap.size()) + " fingerprints: " + URLUtil.URLEncode(fingerprintURLFragment));
//System.err.println();
// this is often so long that it is larger than the IntelliJ console buffer
//System.err.println(descriptors);
//debugPrintedReply = true;
}
if (!requestFingerprintList.equals(replyFingerprints)) {
if (!debugPrintedReply) {
//System.err.println();
//System.err.println(descriptors);
//debugPrintedReply = true;
}
System.err.println();
// Print what we wanted and what we got
for (String requestFingerprint : requestFingerprintList) System.err.println("Requested fingerprint: " + requestFingerprint + ".");
System.err.println();
for (String replyFingerprint : replyFingerprints) System.err.println("Received fingerprint: " + replyFingerprint + ".");
System.err.println();
// Now list missing and extra fingerprints
TreeSet<String> missingInReply = new TreeSet<>(requestFingerprintList);
missingInReply.removeAll(replyFingerprints);
for (String missingFingerprint : missingInReply) System.err.println("Missing fingerprint: " + missingFingerprint + ". Requested, but not in reply.");
TreeSet<String> extraInReply = new TreeSet<>(replyFingerprints);
extraInReply.removeAll(requestFingerprintList);
for (String extraFingerprint : extraInReply) System.err.println("Extra fingerprint: " + extraFingerprint + ". Not requested, but provided in reply.");
// This is error-prone, as fingerprints are space-separated in descriptors
for (String line : descriptorLines) {
for (String fingerprint : missingInReply) {
// fingerprints are already lowercase
String fragment = StringUtils.left(fingerprint, 4);
if (line.toLowerCase().contains(fragment)) {
System.err.println("Missing fingerprint: " + fingerprint + " fragment " + fragment + " found in descriptor line: " + line);
}
}
for (String fingerprint : extraInReply) {
// fingerprints are already lowercase
String fragment = StringUtils.left(fingerprint, 4);
if (line.toLowerCase().contains(fragment)) {
System.err.println("Extra fingerprint: " + fingerprint + " fragment " + fragment + " found in descriptor line: " + line);
}
}
}
// Pull up OnionRouter details for missing and extra routers
for (String fingerprint : missingInReply) {
OnionRouter router = con.routers.get(fingerprint);
if (router != null) {
System.err.println("Missing fingerprint: " + fingerprint + " found router: " + router.toString());
}
}
for (String fingerprint : extraInReply) {
OnionRouter router = con.routers.get(fingerprint);
if (router != null) {
System.err.println("Extra fingerprint: " + fingerprint + " found router: " + router.toString());
}
}
}
}
}Example 35
| Project: android-sync-master File: RFC1522Codec.java View source code |
/**
* Applies an RFC 1522 compliant encoding scheme to the given string of text with the
* given charset. 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 enconding.
*
* @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 conidition during the Encoding
* process.
* @throws UnsupportedEncodingException thrown if charset is not supported
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
protected String encodeText(final String text, final String charset) throws EncoderException, UnsupportedEncodingException {
if (text == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(getEncoding());
buffer.append(SEP);
byte[] rawdata = doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawdata));
buffer.append(POSTFIX);
return buffer.toString();
}Example 36
| Project: Area-master File: RFC1522Codec.java View source code |
/**
* 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;
}
StringBuilder buffer = new StringBuilder();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(this.getEncoding());
buffer.append(SEP);
byte[] rawData = this.doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawData));
buffer.append(POSTFIX);
return buffer.toString();
}Example 37
| Project: baasbox-master File: ScriptsDao.java View source code |
public String decode(String toDecode) {
String toReturn = "";
switch(this) {
case BASE64:
byte[] decoded = Base64.decodeBase64(toDecode);
toReturn = StringUtils.newStringUtf8(decoded);
}
BaasBoxLogger.debug("Decode new script sent in {}. Input: {} Output: {}", BASE64, toDecode, toReturn);
return toReturn;
}Example 38
| Project: bugvm-master File: RFC1522Codec.java View source code |
/**
* 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();
}Example 39
| Project: bytecode-viewer-master File: RFC1522Codec.java View source code |
/**
* 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();
}Example 40
| Project: GT-FHIR-master File: Authorization.java View source code |
// Belows are for out-of-band authorization to support Smart on FHIR internal communications.
// This is not Smart on FHIR standard. This is to support Smart on FHIR's authorization server.
public boolean asBasicAuth(HttpServletRequest request) {
String authString = request.getHeader("Authorization");
if (authString == null)
return false;
System.out.println("asBasicAuth auth header:" + authString);
// Not a basic Auth
if (authString.regionMatches(0, "Basic", 0, 5) == false)
return false;
String credentialString = StringUtils.newStringUtf8(Base64.decodeBase64(authString.substring(6)));
if (credentialString == null)
return false;
String[] credential = credentialString.trim().split(":");
if (credential.length != 2)
return false;
userId = credential[0];
password = credential[1];
System.out.println("asBasicAuth:" + userId + ":" + password);
if (userId.equalsIgnoreCase(clientId) && password.equalsIgnoreCase(clientSecret))
return true;
else
return false;
}Example 41
| Project: h2o-2-master File: VM.java View source code |
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);
}
}Example 42
| Project: jwebsocket-master File: RFC1522Codec.java View source code |
/**
* Applies an RFC 1522 compliant encoding scheme to the given string of text with the
* given charset. 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 enconding.
*
* @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 conidition during the Encoding
* process.
* @throws UnsupportedEncodingException thrown if charset is not supported
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
protected String encodeText(final String text, final String charset) throws EncoderException, UnsupportedEncodingException {
if (text == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(getEncoding());
buffer.append(SEP);
byte[] rawdata = doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawdata));
buffer.append(POSTFIX);
return buffer.toString();
}Example 43
| Project: keypad.io-master File: RFC1522Codec.java View source code |
/**
* 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();
}Example 44
| Project: Leap_Guitar-master File: RFC1522Codec.java View source code |
/**
* Applies an RFC 1522 compliant encoding scheme to the given string of text with the
* given charset. 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 enconding.
*
* @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 conidition during the Encoding
* process.
* @throws UnsupportedEncodingException thrown if charset is not supported
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
protected String encodeText(final String text, final String charset) throws EncoderException, UnsupportedEncodingException {
if (text == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(getEncoding());
buffer.append(SEP);
byte[] rawdata = doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawdata));
buffer.append(POSTFIX);
return buffer.toString();
}Example 45
| Project: MIDIBridge-master File: RFC1522Codec.java View source code |
/**
* Applies an RFC 1522 compliant encoding scheme to the given string of text with the
* given charset. 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 enconding.
*
* @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 conidition during the Encoding
* process.
* @throws UnsupportedEncodingException thrown if charset is not supported
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
protected String encodeText(final String text, final String charset) throws EncoderException, UnsupportedEncodingException {
if (text == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(getEncoding());
buffer.append(SEP);
byte[] rawdata = doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawdata));
buffer.append(POSTFIX);
return buffer.toString();
}Example 46
| Project: MineClipse-Project-master File: RFC1522Codec.java View source code |
/**
* 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;
}
StringBuilder buffer = new StringBuilder();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(this.getEncoding());
buffer.append(SEP);
byte[] rawData = this.doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawData));
buffer.append(POSTFIX);
return buffer.toString();
}Example 47
| Project: phonegap-simjs-master File: RFC1522Codec.java View source code |
/**
* Applies an RFC 1522 compliant encoding scheme to the given string of text with the
* given charset. 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 enconding.
*
* @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 conidition during the Encoding
* process.
* @throws UnsupportedEncodingException thrown if charset is not supported
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
protected String encodeText(final String text, final String charset) throws EncoderException, UnsupportedEncodingException {
if (text == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(getEncoding());
buffer.append(SEP);
byte[] rawdata = doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawdata));
buffer.append(POSTFIX);
return buffer.toString();
}Example 48
| Project: Shocky-master File: ModuleTwitter.java View source code |
public String getAccessToken(boolean useCache) {
if (useCache && Data.config.exists("twitter-accesstoken"))
return Data.config.getString("twitter-accesstoken");
String key = Data.config.getString("twitter-consumerkey");
String secret = Data.config.getString("twitter-consumersecret");
if (key.isEmpty() || secret.isEmpty())
return null;
HTTPQuery q;
try {
q = HTTPQuery.create("https://api.twitter.com/oauth2/token", HTTPQuery.Method.POST);
} catch (MalformedURLException e1) {
return null;
}
try {
String credentials = String.format("%s:%s", URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(secret, "UTF-8"));
q.connect(true, true);
q.setHeaderProperty("Authorization", "Basic " + Base64.encodeBase64String(StringUtils.getBytesUtf8(credentials)));
q.setHeaderProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
q.write("grant_type=client_credentials");
JSONObject json = new JSONObject(q.readWhole());
if (!json.getString("token_type").contentEquals("bearer"))
return null;
String token = json.getString("access_token");
Data.config.set("twitter-accesstoken", token);
return token;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
q.close();
}
return null;
}Example 49
| Project: spec_burp_hmac_extender-master File: RFC1522Codec.java View source code |
/**
* 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;
}
StringBuilder buffer = new StringBuilder();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(this.getEncoding());
buffer.append(SEP);
byte[] rawData = this.doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawData));
buffer.append(POSTFIX);
return buffer.toString();
}Example 50
| Project: x3d-aether-master File: RFC1522Codec.java View source code |
/**
* Applies an RFC 1522 compliant encoding scheme to the given string of text with the
* given charset. 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 enconding.
*
* @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 conidition during the Encoding
* process.
* @throws UnsupportedEncodingException thrown if charset is not supported
*
* @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
*/
protected String encodeText(final String text, final String charset) throws EncoderException, UnsupportedEncodingException {
if (text == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
buffer.append(PREFIX);
buffer.append(charset);
buffer.append(SEP);
buffer.append(getEncoding());
buffer.append(SEP);
byte[] rawdata = doEncoding(text.getBytes(charset));
buffer.append(StringUtils.newStringUsAscii(rawdata));
buffer.append(POSTFIX);
return buffer.toString();
}Example 51
| Project: xwiki-platform-master File: DefaultPresentationBuilderTest.java View source code |
private Answer<Document> returnMatchingDocument(final String content, final Document document) {
return new Answer<Document>() {
@Override
public Document answer(InvocationOnMock invocation) throws Throwable {
Reader reader = invocation.getArgument(0);
return StringUtils.equals(content, IOUtils.toString(reader)) ? document : null;
}
};
}Example 52
| Project: apiman-master File: AuthenticationFilter.java View source code |
/**
* Parses the Authorization request header into a username and password.
* @param authHeader the auth header
*/
private Creds parseAuthorizationBasic(String authHeader) {
String userpassEncoded = authHeader.substring(6);
String data = StringUtils.newStringUtf8(Base64.decodeBase64(userpassEncoded));
int sepIdx = data.indexOf(':');
if (sepIdx > 0) {
String username = data.substring(0, sepIdx);
String password = data.substring(sepIdx + 1);
return new Creds(username, password);
} else {
return new Creds(data, null);
}
}Example 53
| Project: hapi-fhir-master File: FhirResourceDaoValueSetDstu2.java View source code |
private ca.uhn.fhir.jpa.dao.IFhirResourceDaoValueSet.ValidateCodeResult validateCodeIsInContains(List<ExpansionContains> contains, String theSystem, String theCode, CodingDt theCoding, CodeableConceptDt theCodeableConcept) {
for (ExpansionContains nextCode : contains) {
ca.uhn.fhir.jpa.dao.IFhirResourceDaoValueSet.ValidateCodeResult result = validateCodeIsInContains(nextCode.getContains(), theSystem, theCode, theCoding, theCodeableConcept);
if (result != null) {
return result;
}
String system = nextCode.getSystem();
String code = nextCode.getCode();
if (isNotBlank(theCode)) {
if (theCode.equals(code) && (isBlank(theSystem) || theSystem.equals(system))) {
return new ValidateCodeResult(true, "Validation succeeded", nextCode.getDisplay());
}
} else if (theCoding != null) {
if (StringUtils.equals(system, theCoding.getSystem()) && StringUtils.equals(code, theCoding.getCode())) {
return new ValidateCodeResult(true, "Validation succeeded", nextCode.getDisplay());
}
} else {
for (CodingDt next : theCodeableConcept.getCoding()) {
if (StringUtils.equals(system, next.getSystem()) && StringUtils.equals(code, next.getCode())) {
return new ValidateCodeResult(true, "Validation succeeded", nextCode.getDisplay());
}
}
}
}
return null;
}Example 54
| Project: jsontoken-master File: JsonTokenTest.java View source code |
public void testPublicKey() throws Exception {
RsaSHA256Signer signer = new RsaSHA256Signer("google.com", "key1", privateKey);
JsonToken token = new JsonToken(signer, clock);
token.setParam("bar", 15);
token.setParam("foo", "some value");
token.setExpiration(clock.now().withDurationAdded(60, 1));
String tokenString = token.serializeAndSign();
assertNotNull(token.toString());
JsonTokenParser parser = new JsonTokenParser(clock, locators, new IgnoreAudience());
token = parser.verifyAndDeserialize(tokenString);
assertEquals("google.com", token.getIssuer());
assertEquals(15, token.getParamAsPrimitive("bar").getAsLong());
assertEquals("some value", token.getParamAsPrimitive("foo").getAsString());
// now test what happens if we tamper with the token
JsonObject payload = new JsonParser().parse(StringUtils.newStringUtf8(Base64.decodeBase64(tokenString.split(Pattern.quote("."))[1]))).getAsJsonObject();
payload.remove("bar");
payload.addProperty("bar", 14);
String payloadString = new Gson().toJson(payload);
String[] parts = tokenString.split("\\.");
parts[1] = Base64.encodeBase64URLSafeString(payloadString.getBytes());
assertEquals(3, parts.length);
String tamperedToken = parts[0] + "." + parts[1] + "." + parts[2];
try {
token = parser.verifyAndDeserialize(tamperedToken);
fail("verification should have failed");
} catch (SignatureException e) {
}
}Example 55
| Project: jstore-struts2-mybatis3-master File: PasswordHash.java View source code |
private String cryptPrivate(String userPass, String hashPass) {
String output = "*0";
if (output.equals(hashPass.substring(0, 2)))
output = "*1";
if (!"$P$".equals(hashPass.substring(0, 3)))
return output;
int countLog2 = this.itoa64.indexOf(hashPass.charAt(3));
logger.debug("--- cryptPrivate() countLog2=" + countLog2);
if (countLog2 < 7 || countLog2 > 30)
return output;
int count = 1 << countLog2;
String salt = hashPass.substring(4, 12);
logger.debug("-- salt: " + salt);
if (salt.length() != 8)
return output;
byte[] hash = DigestUtils.md5(salt + userPass);
//logger.debug("-- md5( salt +userPass):encode64: "+this.encode64( hash, 16));
do {
hash = DigestUtils.md5(StringUtils.newStringUtf8(hash) + userPass);
//hash = DigestUtils.md5( StringUtils.newStringUsAscii( hash) + userPass);
//hash = DigestUtils.md5Hex( hash + userPass);
//logger.debug("-- md5( hash +userPass): "+ Hex.encodeHexString(hash));
//logger.debug("-- md5( hash +userPass):encode64: "+this.encode64( hash, 16));
} while (--count > 0);
output = hashPass.substring(0, 12);
output += this.encode64(hash, 16);
return output;
}Example 56
| Project: nifi-master File: TestPutEmail.java View source code |
@Test
public void testOutgoingMessageAttachment() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "test@apache.org");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.ATTACH_FILE, "true");
runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
runner.setProperty(PutEmail.TO, "recipient@apache.org");
runner.enqueue("Some text".getBytes());
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("test@apache.org", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("recipient@apache.org", message.getRecipients(RecipientType.TO)[0].toString());
assertTrue(message.getContent() instanceof MimeMultipart);
final MimeMultipart multipart = (MimeMultipart) message.getContent();
final BodyPart part = multipart.getBodyPart(0);
final InputStream is = part.getDataHandler().getInputStream();
final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
assertEquals("Message Body", decodedText);
final BodyPart attachPart = multipart.getBodyPart(1);
final InputStream attachIs = attachPart.getDataHandler().getInputStream();
final String text = IOUtils.toString(attachIs, "UTF-8");
assertEquals("Some text", text);
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}Example 57
| Project: Collide-master File: EditSessions.java View source code |
/**
* Sends the contents of a file to the requester. The files will be served out of the
* FileEditSession if the contents are being edited, otherwise they will simply be
* served from disk.
*/
@Override
public void handle(Message<JsonObject> event) {
JsonArray resourceIdArr = event.body.getArray("resourceIds");
Object[] resourceIds = resourceIdArr.toArray();
String resourceId = (String) resourceIds[0];
String currentPath = stripLeadingSlash(request.getPath());
FileEditSession editSession = editSessions.get(resourceId);
// Create the DTO for the file contents response. We will build it up later in the
// method.
String mimeType = MimeTypes.guessMimeType(currentPath, false);
FileContentsImpl fileContentsDto = FileContentsImpl.make().setMimeType(mimeType).setPath(currentPath);
if (editSession == null) {
// We need to start a new edit session.
String text = "";
File file = new File(currentPath);
try {
text = Files.toString(file, Charsets.UTF_8);
} catch (IOException e) {
logger.error(String.format("Failed to read text contents for path [%s]", currentPath));
sendContent(message, currentPath, null, false);
return;
}
if (provisionEditSession) {
// Provision a new edit session and fall through.
editSession = new FileEditSessionImpl(resourceId, currentPath, text, null, logger);
editSessions.put(resourceId, editSession);
// Update the last opened file.
vertx.eventBus().send("workspace.setLastOpenedFile", new JsonObject().putString("resourceId", resourceId));
} else {
// Just send the contents as they were read from disk and return.
String dataBase64 = MimeTypes.looksLikeImage(mimeType) ? StringUtils.newStringUtf8(Base64.encodeBase64(text.getBytes())) : null;
fileContentsDto.setContents(dataBase64).setContentType(dataBase64 == null ? ContentType.UNKNOWN_BINARY : ContentType.IMAGE);
sendContent(message, currentPath, fileContentsDto, true);
return;
}
}
// Populate file contents response Dto with information from the edit session.
fileContentsDto.setFileEditSessionKey(resourceId).setCcRevision(editSession.getDocument().getCcRevision()).setContents(editSession.getContents()).setContentType(ContentType.TEXT);
// Extract the contents from the edit session before sending.
sendContent(message, currentPath, fileContentsDto, true);
}Example 58
| Project: MOEAFramework-master File: ResultFileWriter.java View source code |
/**
* 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 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();
}
}
}Example 59
| Project: MOHEA-master File: ResultFileWriter.java View source code |
/**
* 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 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();
}
}
}Example 60
| Project: nutch-master File: IndexerMapReduce.java View source code |
public static void initMRJob(Path crawlDb, Path linkDb, Collection<Path> segments, JobConf job, boolean addBinaryContent) {
LOG.info("IndexerMapReduce: crawldb: {}", crawlDb);
if (linkDb != null)
LOG.info("IndexerMapReduce: linkdb: {}", linkDb);
for (final Path segment : segments) {
LOG.info("IndexerMapReduces: adding segment: {}", segment);
FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.FETCH_DIR_NAME));
FileInputFormat.addInputPath(job, new Path(segment, CrawlDatum.PARSE_DIR_NAME));
FileInputFormat.addInputPath(job, new Path(segment, ParseData.DIR_NAME));
FileInputFormat.addInputPath(job, new Path(segment, ParseText.DIR_NAME));
if (addBinaryContent) {
FileInputFormat.addInputPath(job, new Path(segment, Content.DIR_NAME));
}
}
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
if (linkDb != null) {
Path currentLinkDb = new Path(linkDb, LinkDb.CURRENT_NAME);
try {
if (currentLinkDb.getFileSystem(job).exists(currentLinkDb)) {
FileInputFormat.addInputPath(job, currentLinkDb);
} else {
LOG.warn("Ignoring linkDb for indexing, no linkDb found in path: {}", linkDb);
}
} catch (IOException e) {
LOG.warn("Failed to use linkDb ({}) for indexing: {}", linkDb, org.apache.hadoop.util.StringUtils.stringifyException(e));
}
}
job.setInputFormat(SequenceFileInputFormat.class);
job.setMapperClass(IndexerMapReduce.class);
job.setReducerClass(IndexerMapReduce.class);
job.setOutputFormat(IndexerOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setMapOutputValueClass(NutchWritable.class);
job.setOutputValueClass(NutchWritable.class);
}Example 61
| Project: projectforge-webapp-master File: NumberHelper.java View source code |
/**
* Extracts the phone number of the given string. All characters of the set "+-/()." and white spaces will be deleted and +## will be
* replaced by 00##. Example: +49 561 / 316793-0 -> 00495613167930 <br/>
* Ignores any characters after the first occurence of ':' or any letter.
* @param str
* @param countryPrefix If country prefix is given, for all numbers beginning with the country prefix the country prefix will be replaced
* by 0. Example: ("+49 561 / 316793-0", "+49") -> 05613167930; ("+39 123456", "+49") -> 0039123456.
* @return
*/
public static String extractPhonenumber(String str, final String countryPrefix) {
if (str == null) {
return null;
}
str = str.trim();
final StringBuffer buf = new StringBuffer();
if (StringUtils.isNotEmpty(countryPrefix) == true && str.startsWith(countryPrefix) == true) {
buf.append('0');
str = str.substring(countryPrefix.length());
} else if (str.length() > 3 && str.charAt(0) == '+' && Character.isDigit(str.charAt(1)) == true && Character.isDigit(str.charAt(2)) == true) {
buf.append("00");
buf.append(str.charAt(1));
buf.append(str.charAt(2));
str = str.substring(3);
}
for (int i = 0; i < str.length(); i++) {
final char ch = str.charAt(i);
if (Character.isDigit(str.charAt(i)) == true) {
buf.append(ch);
} else if (Character.isWhitespace(ch) == true) {
// continue.
} else if (ALLOWED_PHONE_NUMBER_CHARS.indexOf(ch) < 0) {
break;
}
}
return buf.toString();
}Example 62
| Project: BWS-Samples-master File: SampleBwsClient.java View source code |
/*******************************************************************************************************************
*
* Get the encoded username required to authenticate user to BWS.
*
* @param username
* A string containing the username to encode.
* @param authenticator
* The authenticator.
* @return Returns a string containing the encoded username if successful, and a null message string otherwise.
*
*******************************************************************************************************************
*/
public static String getEncodedUserName(String username, Authenticator authenticator) {
final String METHOD_NAME = "getEncodedUserName()";
final String BWS_API_NAME = "_bwsUtil.getEncodedUsername()";
logMessage("Entering %s", METHOD_NAME);
String returnValue = null;
GetEncodedUsernameRequest request = new GetEncodedUsernameRequest();
request.setMetadata(REQUEST_METADATA);
request.setUsername(username);
request.setOrgUid(REQUEST_METADATA.getOrganizationUid());
request.setAuthenticator(authenticator);
CredentialType credentialType = new CredentialType();
credentialType.setPASSWORD(true);
credentialType.setValue("PASSWORD");
request.setCredentialType(credentialType);
GetEncodedUsernameResponse response = null;
try {
logRequest(BWS_API_NAME);
response = _bwsUtil.getEncodedUsername(request);
logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
} catch (WebServiceException e) {
logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
throw e;
}
if (response.getReturnStatus().getCode().equals("SUCCESS")) {
returnValue = response.getEncodedUsername();
} else {
logMessage("Error Message: \"%s\"", response.getReturnStatus().getMessage());
}
if (Base64.isBase64(returnValue)) {
logMessage("Decoded value of encoded username \"%s\"", StringUtils.newStringUtf8(Base64.decodeBase64(returnValue)));
} else {
logMessage("Value of encoded username \"%s\"", returnValue);
}
logMessage("Exiting %s", METHOD_NAME);
return returnValue;
}Example 63
| Project: debop4j-master File: StringTool.java View source code |
/**
* 문ìž?ì—´ì?´ 멀티바ì?´íЏ (한글,ì?¼ì–´,중êµì–´ 등 2ë°”ì?´íЏ ì?´ìƒ?ì?˜ 언어) ì?¸ê°€ 확ì?¸í•œë‹¤.
*
* @param str 문�열
* @return 멀티바�트 언어�면 true, 아니면 false
*/
public static boolean isMultiByteString(final String str) {
if (isWhiteSpace(str))
return false;
try {
byte[] bytes = StringUtils.getBytesUsAscii(str.substring(0, Math.min(2, str.length())));
return isMultiByteString(bytes);
} catch (Exception e) {
log.error("멀티바�트 문�열�지 확�하는� 실패했습니다. str=" + ellipsisChar(str, 24), e);
return false;
}
}Example 64
| Project: femr-master File: MedicationDatabaseSeeder.java View source code |
private void seedConceptPrescriptionAdministrations() {
List<? extends IConceptPrescriptionAdministration> administrations = conceptPrescriptionAdministrationRepository.findAll(ConceptPrescriptionAdministration.class);
List<ConceptPrescriptionAdministration> conceptPrescriptionAdministrationsToAdd = new ArrayList<>();
if (administrations != null) {
ConceptPrescriptionAdministration conceptPrescriptionAdministration;
if (!containConceptPrescriptionAdministration(administrations, "alt")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("alt");
conceptPrescriptionAdministration.setDailyModifier(0.5f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "BID")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("BID");
conceptPrescriptionAdministration.setDailyModifier(2f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "BIW")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("BIW");
conceptPrescriptionAdministration.setDailyModifier(0.2857f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "CID")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("CID");
conceptPrescriptionAdministration.setDailyModifier(5f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "HS")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("HS");
conceptPrescriptionAdministration.setDailyModifier(1f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q12h")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q12h");
conceptPrescriptionAdministration.setDailyModifier(2f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q24h")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q24h");
conceptPrescriptionAdministration.setDailyModifier(1f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q4-6h")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q4-6h");
conceptPrescriptionAdministration.setDailyModifier(5f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q4h")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q4h");
conceptPrescriptionAdministration.setDailyModifier(6f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q6h")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q6h");
conceptPrescriptionAdministration.setDailyModifier(4f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q8h")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q8h");
conceptPrescriptionAdministration.setDailyModifier(3f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "qAM")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("qAM");
conceptPrescriptionAdministration.setDailyModifier(1f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "qd")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("qd");
conceptPrescriptionAdministration.setDailyModifier(1f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "qHS")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("qHS");
conceptPrescriptionAdministration.setDailyModifier(1f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "QID")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("QID");
conceptPrescriptionAdministration.setDailyModifier(4f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q5min")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q5min");
conceptPrescriptionAdministration.setDailyModifier(288f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "qOd")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("qOd");
conceptPrescriptionAdministration.setDailyModifier(0.5f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "qPM")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("qPM");
conceptPrescriptionAdministration.setDailyModifier(1f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "q week")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("q week");
conceptPrescriptionAdministration.setDailyModifier(0.142857f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "TID")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("TID");
conceptPrescriptionAdministration.setDailyModifier(3f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
if (!containConceptPrescriptionAdministration(administrations, "TIW")) {
conceptPrescriptionAdministration = new ConceptPrescriptionAdministration();
conceptPrescriptionAdministration.setName("TIW");
conceptPrescriptionAdministration.setDailyModifier(0.42857f);
conceptPrescriptionAdministrationsToAdd.add(conceptPrescriptionAdministration);
}
//a whole bunch of if statements to fix the problem with the daily modifier turning to 0 when navigating through evolutions
for (IConceptPrescriptionAdministration existingConceptPrescriptionAdministrations : administrations) {
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "alt") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(0.5f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "BID") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(2f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "BIW") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(0.2857f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "CID") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(5f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "HS") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(1f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q12h") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(2f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q24h") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(1f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q4-6h") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(5f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q4h") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(6f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q6h") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(4f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q8h") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(3f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "qAM") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(1f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "qd") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(1f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "qHS") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(1f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "QID") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(4f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q5min") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(288f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "qOd") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(0.5f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "qPM") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(1f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "q week") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(0.142857f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "TID") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(3f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
if (StringUtils.equals(existingConceptPrescriptionAdministrations.getName(), "TIW") && existingConceptPrescriptionAdministrations.getDailyModifier() == 0.00) {
existingConceptPrescriptionAdministrations.setDailyModifier(0.42857f);
conceptPrescriptionAdministrationRepository.update((ConceptPrescriptionAdministration) existingConceptPrescriptionAdministrations);
}
}
conceptPrescriptionAdministrationRepository.createAll(conceptPrescriptionAdministrationsToAdd);
}
}Example 65
| Project: google-http-java-client-master File: StringUtils.java View source code |
/** * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result * into a new byte array. * * @param string the String to encode, may be <code>null</code> * @return encoded bytes, or <code>null</code> if the input string was <code>null</code> * @throws IllegalStateException Thrown when the charset is missing, which should be never * according the the Java specification. * @see <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/nio/charset/Charset.html" * >Standard charsets</a> * @see org.apache.commons.codec.binary.StringUtils#getBytesUtf8(String) * @since 1.8 */ public static byte[] getBytesUtf8(String string) { return org.apache.commons.codec.binary.StringUtils.getBytesUtf8(string); }
Example 66
| Project: zooterrain-master File: DataMessage.java View source code |
public String getDataBase64Encoded() {
return StringUtils.newStringUtf8(Base64.encodeBase64(rawData, false));
}Example 67
| Project: jmetrik-master File: JmetrikPassword.java View source code |
public String encodePassword(String pw) {
byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(pw));
String encodedContent = StringUtils.newStringUtf8(encodedBytes);
return encodedContent;
}Example 68
| Project: motherbrain-master File: ContainerWrapper.java View source code |
public void writeFile(String internalPath, String contents) throws ContainerException {
_delegate.writeFile(internalPath, StringUtils.getBytesUtf8(contents));
}Example 69
| Project: discord.jar-master File: AccountManagerImpl.java View source code |
@Override
public void setAvatar(InputStream is) throws IOException {
updateLocalVars();
this.avatar = "data:image/jpeg;base64," + StringUtils.newStringUtf8(Base64.encodeBase64(IOUtils.toByteArray(is), false));
updateEdits();
}Example 70
| Project: beakerx-master File: RastersSerializer.java View source code |
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();
}Example 71
| Project: ews-java-api-master File: IFunctionsTest.java View source code |
@Test
public void testBase64Encoder() {
final byte[] value = StringUtils.getBytesUtf8("123");
final IFunctions.Base64Encoder f = IFunctions.Base64Encoder.INSTANCE;
Assert.assertEquals(Base64.encodeBase64String(value), f.func(value));
}Example 72
| Project: incubator-blur-master File: Base64.java View source code |
/**
* Serialize to Base64 as a String, non-chunked.
*/
public static String encodeBase64String(byte[] data) {
/*
* Based on implementation of this same name function in commons-codec 1.5+.
* in commons-codec 1.4, the second param sets chunking to true.
*/
return StringUtils.newStringUtf8(org.apache.commons.codec.binary.Base64.encodeBase64(data, false));
}Example 73
| Project: build-info-master File: ArtifactoryHttpClient.java View source code |
public static String encodeUrl(String unescaped) {
byte[] rawdata = URLCodec.encodeUrl(URI.allowed_query, org.apache.commons.codec.binary.StringUtils.getBytesUtf8(unescaped));
return org.apache.commons.codec.binary.StringUtils.newStringUsAscii(rawdata);
}Example 74
| Project: AndroidFire-master File: DESBase64Util.java View source code |
/**
* 先对消æ?¯ä½“进行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 "";
}Example 75
| Project: BaseMoudle-master File: DESBase64Util.java View source code |
/**
* 先对消æ?¯ä½“进行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 "";
}Example 76
| Project: gibson-master File: EventUtils.java View source code |
private static void append(MessageDigest md, String value) {
append(md, StringUtils.getBytesUtf8(value));
}Example 77
| Project: cogroo4-master File: SecurityUtil.java View source code |
public String encode(byte[] key) {
return StringUtils.newStringUtf8(Base64.encodeBase64(key, false));
}Example 78
| Project: ics-openvpn-master File: DigestUtils.java View source code |
/**
* Calls {@link StringUtils#getBytesUtf8(String)}
*
* @param data
* the String to encode
* @return encoded bytes
*/
private static byte[] getBytesUtf8(String data) {
return StringUtils.getBytesUtf8(data);
}Example 79
| Project: milano-master File: MilanoTool.java View source code |
/* ** Getters ** */
/**
* Get the Base64 representation of this MilanoTool.
*
* @return A Base64 encoded string.
*/
public String getBase64() {
if (base64 == null) {
base64 = StringUtils.newStringUtf8(Base64.encodeBase64(typeMetadata.toByteArray()));
}
return base64;
}Example 80
| Project: resource-manager-master File: StringUtility.java View source code |
public static String responseAsString(HttpResponseWrapper response) {
return StringUtils.newStringUtf8(response.getContent());
}Example 81
| Project: scheduling-master File: StringUtility.java View source code |
public static String responseAsString(HttpResponseWrapper response) {
return StringUtils.newStringUtf8(response.getContent());
}Example 82
| Project: hive-master File: ThriftHttpServlet.java View source code |
private String[] getAuthHeaderTokens(HttpServletRequest request, String authType) throws HttpAuthenticationException {
String authHeaderBase64 = getAuthHeader(request, authType);
String authHeaderString = StringUtils.newStringUtf8(Base64.decodeBase64(authHeaderBase64.getBytes()));
String[] creds = authHeaderString.split(":");
return creds;
}Example 83
| Project: AirCastingAndroidClient-master File: Base64.java View source code |
/**
* Encodes binary data using the base64 algorithm into 76 character blocks separated by CRLF.
*
* @param binaryData
* binary data to encode
* @return String containing Base64 characters.
* @since 1.4
*/
public static String encodeBase64String(byte[] binaryData) {
return StringUtils.newStringUtf8(encodeBase64(binaryData, true));
}