_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q164700 | Metrics.time | train | public static Context time(String appid, Class<?> clazz, String... names) {
String className = getClassName(clazz);
Timer systemTimer = getTimer(SYSTEM_METRICS_NAME, className, names);
Timer appTimer = appid == null || appid.isEmpty() ? null : getTimer(appid, className, names);
return new Context(systemTimer, appTimer);
} | java | {
"resource": ""
} |
q164701 | Metrics.counter | train | public static Counter counter(String appid, Class<?> clazz, String... names) {
String className = getClassName(clazz);
return getCounter(App.isRoot(appid) ? SYSTEM_METRICS_NAME : appid, className, names);
} | java | {
"resource": ""
} |
q164702 | FacebookAuthFilter.getOrCreateUser | train | @SuppressWarnings("unchecked")
public UserAuthentication getOrCreateUser(App app, String accessToken) throws IOException {
UserAuthentication userAuth = null;
User user = new User();
if (accessToken != null) {
String ctype = null;
HttpEntity respEntity = null;
CloseableHttpResponse resp2 = null;
try {
HttpGet profileGet = new HttpGet(PROFILE_URL + accessToken);
resp2 = httpclient.execute(profileGet);
respEntity = resp2.getEntity();
ctype = resp2.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
} catch (Exception e) {
logger.warn("Facebook auth request failed: GET " + PROFILE_URL + accessToken, e);
}
if (respEntity != null && Utils.isJsonType(ctype)) {
Map<String, Object> profile = jreader.readValue(respEntity.getContent());
if (profile != null && profile.containsKey("id")) {
String fbId = (String) profile.get("id");
String email = (String) profile.get("email");
String name = (String) profile.get("name");
user.setAppid(getAppid(app));
user.setIdentifier(Config.FB_PREFIX.concat(fbId));
user.setEmail(email);
user = User.readUserForIdentifier(user);
if (user == null) {
//user is new
user = new User();
user.setActive(true);
user.setAppid(getAppid(app));
user.setEmail(StringUtils.isBlank(email) ? fbId + "@facebook.com" : email);
user.setName(StringUtils.isBlank(name) ? "No Name" : name);
user.setPassword(Utils.generateSecurityToken());
user.setPicture(getPicture(fbId));
user.setIdentifier(Config.FB_PREFIX.concat(fbId));
String id = user.create();
if (id == null) {
throw new AuthenticationServiceException("Authentication failed: cannot create new user.");
}
} else {
String picture = getPicture(fbId);
boolean update = false;
if (!StringUtils.equals(user.getPicture(), picture)) {
user.setPicture(picture);
update = true;
}
if (!StringUtils.isBlank(email) && !StringUtils.equals(user.getEmail(), email)) {
user.setEmail(email);
update = true;
}
if (update) {
user.update();
}
}
userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
}
EntityUtils.consumeQuietly(respEntity);
}
}
return SecurityUtils.checkIfActive(userAuth, user, false);
} | java | {
"resource": ""
} |
q164703 | SecurityUtils.getAuthenticatedUser | train | public static User getAuthenticatedUser(Authentication auth) {
User user = null;
if (auth != null && auth.isAuthenticated() && auth.getPrincipal() instanceof AuthenticatedUserDetails) {
user = ((AuthenticatedUserDetails) auth.getPrincipal()).getUser();
}
return user;
} | java | {
"resource": ""
} |
q164704 | SecurityUtils.getAuthenticatedApp | train | public static App getAuthenticatedApp() {
App app = null;
if (SecurityContextHolder.getContext().getAuthentication() != null) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth.isAuthenticated() && auth.getPrincipal() instanceof App) {
app = (App) auth.getPrincipal();
}
}
return app;
} | java | {
"resource": ""
} |
q164705 | SecurityUtils.checkImplicitAppPermissions | train | public static boolean checkImplicitAppPermissions(App app, ParaObject object) {
if (app != null && object != null) {
return isNotAnApp(object.getType()) || app.getId().equals(object.getId()) || app.isRootApp();
}
return false;
} | java | {
"resource": ""
} |
q164706 | SecurityUtils.checkIfUserCanModifyObject | train | public static boolean checkIfUserCanModifyObject(App app, ParaObject object) {
User user = SecurityUtils.getAuthenticatedUser();
if (user != null && app != null && object != null) {
if (app.permissionsContainOwnKeyword(user, object)) {
return user.canModify(object);
}
}
return true; // skip
} | java | {
"resource": ""
} |
q164707 | SecurityUtils.clearSession | train | public static void clearSession(HttpServletRequest req) {
SecurityContextHolder.clearContext();
if (req != null) {
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate();
}
}
} | java | {
"resource": ""
} |
q164708 | SecurityUtils.isValidJWToken | train | public static boolean isValidJWToken(String secret, SignedJWT jwt) {
try {
if (secret != null && jwt != null) {
JWSVerifier verifier = new MACVerifier(secret);
if (jwt.verify(verifier)) {
Date referenceTime = new Date();
JWTClaimsSet claims = jwt.getJWTClaimsSet();
Date expirationTime = claims.getExpirationTime();
Date notBeforeTime = claims.getNotBeforeTime();
boolean expired = expirationTime == null || expirationTime.before(referenceTime);
boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime);
return !(expired || notYetValid);
}
}
} catch (JOSEException e) {
logger.warn(null, e);
} catch (ParseException ex) {
logger.warn(null, ex);
}
return false;
} | java | {
"resource": ""
} |
q164709 | SecurityUtils.generateJWToken | train | public static SignedJWT generateJWToken(User user, App app) {
if (app != null) {
try {
Date now = new Date();
JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
String userSecret = "";
claimsSet.issueTime(now);
claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
claimsSet.notBeforeTime(now);
claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
claimsSet.claim(Config._APPID, app.getId());
if (user != null) {
claimsSet.subject(user.getId());
userSecret = user.getTokenSecret();
}
JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
signedJWT.sign(signer);
return signedJWT;
} catch (JOSEException e) {
logger.warn("Unable to sign JWT: {}.", e.getMessage());
}
}
return null;
} | java | {
"resource": ""
} |
q164710 | SecurityUtils.getNextRefresh | train | private static long getNextRefresh(long tokenValiditySec) {
long interval = Config.JWT_REFRESH_INTERVAL_SEC;
// estimate when the next token refresh should be
// usually every hour, or halfway until the time it expires
if (tokenValiditySec < (2 * interval)) {
interval = (tokenValiditySec / 2);
}
return System.currentTimeMillis() + (interval * 1000);
} | java | {
"resource": ""
} |
q164711 | SecurityUtils.getOAuthKeysForApp | train | public static String[] getOAuthKeysForApp(App app, String prefix) {
prefix = StringUtils.removeEnd(prefix + "", Config.SEPARATOR);
String appIdKey = prefix + "_app_id";
String secretKey = prefix + "_secret";
String[] keys = new String[]{"", ""};
if (app != null) {
Map<String, Object> settings = app.getSettings();
if (settings.containsKey(appIdKey) && settings.containsKey(secretKey)) {
keys[0] = settings.get(appIdKey) + "";
keys[1] = settings.get(secretKey) + "";
} else if (app.isRootApp()) {
keys[0] = Config.getConfigParam(appIdKey, "");
keys[1] = Config.getConfigParam(secretKey, "");
}
}
return keys;
} | java | {
"resource": ""
} |
q164712 | SecurityUtils.getLdapSettingsForApp | train | public static Map<String, String> getLdapSettingsForApp(App app) {
Map<String, String> ldapSettings = new HashMap<>();
if (app != null) {
ldapSettings.put("security.ldap.server_url", "ldap://localhost:8389/");
ldapSettings.put("security.ldap.active_directory_domain", "");
ldapSettings.put("security.ldap.base_dn", "dc=springframework,dc=org");
ldapSettings.put("security.ldap.bind_dn", "");
ldapSettings.put("security.ldap.bind_pass", "");
ldapSettings.put("security.ldap.user_search_base", "");
ldapSettings.put("security.ldap.user_search_filter", "(cn={0})");
ldapSettings.put("security.ldap.user_dn_pattern", "uid={0},ou=people");
ldapSettings.put("security.ldap.password_attribute", "userPassword");
//ldapSettings.put("security.ldap.compare_passwords", "false"); //don't remove comment
Map<String, Object> settings = app.getSettings();
for (Map.Entry<String, String> entry : ldapSettings.entrySet()) {
if (settings.containsKey(entry.getKey())) {
entry.setValue(settings.get(entry.getKey()) + "");
} else if (app.isRootApp()) {
entry.setValue(Config.getConfigParam(entry.getKey(), entry.getValue()));
}
}
}
return ldapSettings;
} | java | {
"resource": ""
} |
q164713 | SecurityUtils.getSettingForApp | train | public static String getSettingForApp(App app, String key, String defaultValue) {
if (app != null) {
Map<String, Object> settings = app.getSettings();
if (settings.containsKey(key)) {
return String.valueOf(settings.getOrDefault(key, defaultValue));
} else if (app.isRootApp()) {
return Config.getConfigParam(key, defaultValue);
}
}
return defaultValue;
} | java | {
"resource": ""
} |
q164714 | SecurityUtils.checkIfActive | train | public static UserAuthentication checkIfActive(UserAuthentication userAuth, User user, boolean throwException) {
if (userAuth == null || user == null || user.getIdentifier() == null) {
if (throwException) {
throw new BadCredentialsException("Bad credentials.");
} else {
logger.debug("Bad credentials. {}", userAuth);
return null;
}
} else if (!user.getActive()) {
if (throwException) {
throw new LockedException("Account " + user.getId() + " (" + user.getAppid() + "/" +
user.getIdentifier() + ") is locked.");
} else {
logger.warn("Account {} ({}/{}) is locked.", user.getId(), user.getAppid(), user.getIdentifier());
return null;
}
}
return userAuth;
} | java | {
"resource": ""
} |
q164715 | SecurityUtils.isValidSignature | train | public static boolean isValidSignature(HttpServletRequest incoming, String secretKey) {
if (incoming == null || StringUtils.isBlank(secretKey)) {
return false;
}
String auth = incoming.getHeader(HttpHeaders.AUTHORIZATION);
String givenSig = StringUtils.substringAfter(auth, "Signature=");
String sigHeaders = StringUtils.substringBetween(auth, "SignedHeaders=", ",");
String credential = StringUtils.substringBetween(auth, "Credential=", ",");
String accessKey = StringUtils.substringBefore(credential, "/");
if (StringUtils.isBlank(auth)) {
givenSig = incoming.getParameter("X-Amz-Signature");
sigHeaders = incoming.getParameter("X-Amz-SignedHeaders");
credential = incoming.getParameter("X-Amz-Credential");
accessKey = StringUtils.substringBefore(credential, "/");
}
Set<String> headersUsed = new HashSet<>(Arrays.asList(sigHeaders.split(";")));
Map<String, String> headers = new HashMap<>();
for (Enumeration<String> e = incoming.getHeaderNames(); e.hasMoreElements();) {
String head = e.nextElement().toLowerCase();
if (headersUsed.contains(head)) {
headers.put(head, incoming.getHeader(head));
}
}
Map<String, String> params = new HashMap<>();
for (Map.Entry<String, String[]> param : incoming.getParameterMap().entrySet()) {
params.put(param.getKey(), param.getValue()[0]);
}
String path = incoming.getRequestURI();
String endpoint = StringUtils.removeEndIgnoreCase(incoming.getRequestURL().toString(), path);
String httpMethod = incoming.getMethod();
InputStream entity;
try {
entity = new BufferedRequestWrapper(incoming).getInputStream();
if (entity.available() <= 0) {
entity = null;
}
} catch (IOException ex) {
logger.error(null, ex);
entity = null;
}
Signer signer = new Signer();
Map<String, String> sig = signer.sign(httpMethod, endpoint, path, headers, params, entity, accessKey, secretKey);
String auth2 = sig.get(HttpHeaders.AUTHORIZATION);
String recreatedSig = StringUtils.substringAfter(auth2, "Signature=");
return StringUtils.equals(givenSig, recreatedSig);
} | java | {
"resource": ""
} |
q164716 | Para.initialize | train | public static void initialize() {
if (isInitialized) {
return;
}
isInitialized = true;
printLogo();
try {
logger.info("--- Para.initialize() [{}] ---", Config.ENVIRONMENT);
for (InitializeListener initListener : INIT_LISTENERS) {
if (initListener != null) {
initListener.onInitialize();
logger.debug("Executed {}.onInitialize().", initListener.getClass().getName());
}
}
logger.info("Instance #{} initialized.", Config.WORKER_ID);
} catch (Exception e) {
logger.error("Failed to initialize Para.", e);
}
} | java | {
"resource": ""
} |
q164717 | Para.destroy | train | public static void destroy() {
try {
logger.info("--- Para.destroy() ---");
for (DestroyListener destroyListener : DESTROY_LISTENERS) {
if (destroyListener != null) {
destroyListener.onDestroy();
logger.debug("Executed {}.onDestroy().", destroyListener.getClass().getName());
}
}
if (!EXECUTOR.isShutdown()) {
EXECUTOR.shutdown();
EXECUTOR.awaitTermination(60, TimeUnit.SECONDS);
}
if (!SCHEDULER.isShutdown()) {
SCHEDULER.shutdown();
SCHEDULER.awaitTermination(60, TimeUnit.SECONDS);
}
} catch (Exception e) {
logger.error("Failed to destroy Para.", e);
}
} | java | {
"resource": ""
} |
q164718 | Para.setup | train | public static Map<String, String> setup() {
return newApp(Config.getRootAppIdentifier(), Config.APP_NAME, false, false);
} | java | {
"resource": ""
} |
q164719 | Para.newApp | train | public static Map<String, String> newApp(String appid, String name, boolean sharedTable, boolean sharedIndex) {
Map<String, String> creds = new TreeMap<>();
creds.put("message", "All set!");
if (StringUtils.isBlank(appid)) {
return creds;
}
App app = new App(appid);
if (!app.exists()) {
app.setName(name);
app.setSharingTable(sharedTable);
app.setSharingIndex(sharedIndex);
app.setActive(true);
String id = app.create();
if (id != null) {
logger.info("Created {} app '{}', sharingTable = {}, sharingIndex = {}.",
app.isRootApp() ? "root" : "new", app.getAppIdentifier(), sharedTable, sharedIndex);
creds.putAll(app.getCredentials());
creds.put("message", "Save the secret key - it is shown only once!");
} else {
logger.error("Failed to create app '{}'!", appid);
creds.put("message", "Error - app was not created.");
}
}
return creds;
} | java | {
"resource": ""
} |
q164720 | LanguageUtils.readLanguage | train | public Map<String, String> readLanguage(String appid, String langCode) {
if (StringUtils.isBlank(langCode) || langCode.equals(getDefaultLanguageCode())) {
return getDefaultLanguage(appid);
} else if (langCode.length() > 2 && !ALL_LOCALES.containsKey(langCode)) {
return readLanguage(appid, langCode.substring(0, 2));
} else if (LANG_CACHE.containsKey(langCode)) {
return LANG_CACHE.get(langCode);
}
// load language map from file
Map<String, String> lang = readLanguageFromFile(appid, langCode);
if (lang == null || lang.isEmpty()) {
// or try to load from DB
lang = new TreeMap<String, String>(getDefaultLanguage(appid));
Sysprop s = dao.read(appid, keyPrefix.concat(langCode));
if (s != null && !s.getProperties().isEmpty()) {
Map<String, Object> loaded = s.getProperties();
for (Map.Entry<String, String> entry : lang.entrySet()) {
if (loaded.containsKey(entry.getKey())) {
lang.put(entry.getKey(), String.valueOf(loaded.get(entry.getKey())));
} else {
lang.put(entry.getKey(), entry.getValue());
}
}
}
LANG_CACHE.put(langCode, lang);
}
return Collections.unmodifiableMap(lang);
} | java | {
"resource": ""
} |
q164721 | LanguageUtils.writeLanguage | train | public void writeLanguage(String appid, String langCode, Map<String, String> lang, boolean writeToDatabase) {
if (lang == null || lang.isEmpty() || StringUtils.isBlank(langCode) || !ALL_LOCALES.containsKey(langCode)) {
return;
}
writeLanguageToFile(appid, langCode, lang);
if (writeToDatabase) {
// this will overwrite a saved language map!
Sysprop s = new Sysprop(keyPrefix.concat(langCode));
Map<String, String> dlang = getDefaultLanguage(appid);
for (Map.Entry<String, String> entry : dlang.entrySet()) {
String key = entry.getKey();
if (lang.containsKey(key)) {
s.addProperty(key, lang.get(key));
} else {
s.addProperty(key, entry.getValue());
}
}
dao.create(appid, s);
}
} | java | {
"resource": ""
} |
q164722 | LanguageUtils.getProperLocale | train | public Locale getProperLocale(String langCode) {
if (StringUtils.startsWith(langCode, "zh")) {
if ("zh_tw".equalsIgnoreCase(langCode)) {
return Locale.TRADITIONAL_CHINESE;
} else {
return Locale.SIMPLIFIED_CHINESE;
}
}
String lang = StringUtils.substring(langCode, 0, 2);
lang = (StringUtils.isBlank(lang) || !ALL_LOCALES.containsKey(lang)) ? "en" : lang.trim().toLowerCase();
return ALL_LOCALES.get(lang);
} | java | {
"resource": ""
} |
q164723 | LanguageUtils.getDefaultLanguage | train | public Map<String, String> getDefaultLanguage(String appid) {
if (!LANG_CACHE.containsKey(getDefaultLanguageCode())) {
logger.info("Default language map not set, loading English.");
Map<String, String> deflang = readLanguageFromFile(appid, getDefaultLanguageCode());
if (deflang != null && !deflang.isEmpty()) {
LANG_CACHE.put(getDefaultLanguageCode(), deflang);
return Collections.unmodifiableMap(deflang);
}
}
return Collections.unmodifiableMap(LANG_CACHE.get(getDefaultLanguageCode()));
} | java | {
"resource": ""
} |
q164724 | LanguageUtils.setDefaultLanguage | train | public void setDefaultLanguage(Map<String, String> deflang) {
if (deflang != null && !deflang.isEmpty()) {
LANG_CACHE.put(getDefaultLanguageCode(), deflang);
}
} | java | {
"resource": ""
} |
q164725 | LanguageUtils.readAllTranslationsForKey | train | public List<Translation> readAllTranslationsForKey(String appid, String locale, String key, Pager pager) {
Map<String, Object> terms = new HashMap<>(2);
terms.put("thekey", key);
terms.put("locale", locale);
return search.findTerms(appid, Utils.type(Translation.class), terms, true, pager);
} | java | {
"resource": ""
} |
q164726 | LanguageUtils.getApprovedTransKeys | train | public Set<String> getApprovedTransKeys(String appid, String langCode) {
HashSet<String> approvedTransKeys = new HashSet<>();
if (StringUtils.isBlank(langCode)) {
return approvedTransKeys;
}
for (Map.Entry<String, String> entry : readLanguage(appid, langCode).entrySet()) {
if (!getDefaultLanguage(appid).get(entry.getKey()).equals(entry.getValue())) {
approvedTransKeys.add(entry.getKey());
}
}
return approvedTransKeys;
} | java | {
"resource": ""
} |
q164727 | LanguageUtils.getTranslationProgressMap | train | public Map<String, Integer> getTranslationProgressMap(String appid) {
if (dao == null) {
return Collections.emptyMap();
}
Sysprop progress;
if (langProgressCache.getProperties().isEmpty()) {
progress = dao.read(appid, progressKey);
if (progress != null) {
langProgressCache = progress;
}
} else {
progress = langProgressCache;
}
Map<String, Integer> progressMap = new HashMap<>(ALL_LOCALES.size());
boolean isMissing = progress == null;
if (isMissing) {
progress = new Sysprop(progressKey);
progress.addProperty(getDefaultLanguageCode(), 100);
}
for (String langCode : ALL_LOCALES.keySet()) {
Object percent = progress.getProperties().get(langCode);
if (percent != null && percent instanceof Number) {
progressMap.put(langCode, (Integer) percent);
} else {
progressMap.put(langCode, 0);
}
}
if (isMissing) {
dao.create(appid, progress);
langProgressCache = progress;
}
return progressMap;
} | java | {
"resource": ""
} |
q164728 | LanguageUtils.approveTranslation | train | public boolean approveTranslation(String appid, String langCode, String key, String value) {
if (StringUtils.isBlank(langCode) || key == null || value == null || getDefaultLanguageCode().equals(langCode)) {
return false;
}
Sysprop s = dao.read(appid, keyPrefix.concat(langCode));
boolean create = false;
if (s == null) {
create = true;
s = new Sysprop(keyPrefix.concat(langCode));
s.setAppid(appid);
}
s.addProperty(key, value);
if (create) {
dao.create(appid, s);
} else {
dao.update(appid, s);
}
if (LANG_CACHE.containsKey(langCode)) {
LANG_CACHE.get(langCode).put(key, value);
}
updateTranslationProgressMap(appid, langCode, PLUS);
return true;
} | java | {
"resource": ""
} |
q164729 | LanguageUtils.disapproveTranslation | train | public boolean disapproveTranslation(String appid, String langCode, String key) {
if (StringUtils.isBlank(langCode) || key == null || getDefaultLanguageCode().equals(langCode)) {
return false;
}
Sysprop s = dao.read(appid, keyPrefix.concat(langCode));
if (s != null) {
String value = getDefaultLanguage(appid).get(key);
s.addProperty(key, value);
dao.update(appid, s);
if (LANG_CACHE.containsKey(langCode)) {
LANG_CACHE.get(langCode).put(key, value);
}
updateTranslationProgressMap(appid, langCode, MINUS);
return true;
}
return false;
} | java | {
"resource": ""
} |
q164730 | LanguageUtils.updateTranslationProgressMap | train | private void updateTranslationProgressMap(String appid, String langCode, int value) {
if (dao == null || getDefaultLanguageCode().equals(langCode)) {
return;
}
double defsize = getDefaultLanguage(appid).size();
double approved = value;
Map<String, Integer> progress = getTranslationProgressMap(appid);
Integer percent = progress.get(langCode);
if (value == PLUS) {
approved = Math.round(percent * (defsize / 100) + 1);
} else if (value == MINUS) {
approved = Math.round(percent * (defsize / 100) - 1);
}
int allowedUntranslated = defsize > 10 ? 5 : 0;
// allow 3 identical words per language (i.e. Email, etc)
if (approved >= defsize - allowedUntranslated) {
approved = defsize;
}
if (((int) defsize) == 0) {
progress.put(langCode, 0);
} else {
progress.put(langCode, (int) ((approved / defsize) * 100));
}
Sysprop updatedProgress = new Sysprop(progressKey);
for (Map.Entry<String, Integer> entry : progress.entrySet()) {
updatedProgress.addProperty(entry.getKey(), entry.getValue());
}
langProgressCache = updatedProgress;
if (percent < 100 && !percent.equals(progress.get(langCode))) {
dao.create(appid, updatedProgress);
}
} | java | {
"resource": ""
} |
q164731 | UserAuthentication.getAuthorities | train | public Collection<? extends GrantedAuthority> getAuthorities() {
if (principal == null) {
return Collections.emptyList();
}
return Collections.unmodifiableCollection(principal.getAuthorities());
} | java | {
"resource": ""
} |
q164732 | SimpleAuthenticationSuccessHandler.isRestRequest | train | protected boolean isRestRequest(HttpServletRequest request) {
return RestRequestMatcher.INSTANCE.matches(request) || AjaxRequestMatcher.INSTANCE.matches(request);
} | java | {
"resource": ""
} |
q164733 | SimpleUserService.loadUserByUsername | train | public UserDetails loadUserByUsername(String ident) {
User user = new User();
// check if the cookie has an appid prefix
// and load user from the corresponding app
if (StringUtils.contains(ident, "/")) {
String[] parts = ident.split("/");
user.setAppid(parts[0]);
ident = parts[1];
}
user.setIdentifier(ident);
user = loadUser(user);
if (user == null) {
throw new UsernameNotFoundException(ident);
}
return new AuthenticatedUserDetails(user);
} | java | {
"resource": ""
} |
q164734 | SimpleUserService.loadUserDetails | train | public UserDetails loadUserDetails(OpenIDAuthenticationToken token) {
if (token == null) {
return null;
}
User user = new User();
user.setIdentifier(token.getIdentityUrl());
user = loadUser(user);
if (user == null) {
// create new OpenID user
String email = "email@domain.com";
String firstName = null, lastName = null, fullName = null;
List<OpenIDAttribute> attributes = token.getAttributes();
for (OpenIDAttribute attribute : attributes) {
if (attribute.getName().equals("email")) {
email = attribute.getValues().get(0);
}
if (attribute.getName().equals("firstname")) {
firstName = attribute.getValues().get(0);
}
if (attribute.getName().equals("lastname")) {
lastName = attribute.getValues().get(0);
}
if (attribute.getName().equals("fullname")) {
fullName = attribute.getValues().get(0);
}
}
if (fullName == null) {
if (firstName == null) {
firstName = "No";
}
if (lastName == null) {
lastName = "Name";
}
fullName = firstName.concat(" ").concat(lastName);
}
user = new User();
user.setActive(true);
user.setEmail(email);
user.setName(fullName);
user.setPassword(Utils.generateSecurityToken());
user.setIdentifier(token.getIdentityUrl());
String id = user.create();
if (id == null) {
throw new BadCredentialsException("Authentication failed: cannot create new user.");
}
}
return new AuthenticatedUserDetails(user);
} | java | {
"resource": ""
} |
q164735 | SecurityConfig.configure | train | @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
OpenIDAuthenticationProvider openidProvider = new OpenIDAuthenticationProvider();
openidProvider.setAuthenticationUserDetailsService(new SimpleUserService());
auth.authenticationProvider(openidProvider);
RememberMeAuthenticationProvider rmeProvider = new RememberMeAuthenticationProvider(Config.APP_SECRET_KEY);
auth.authenticationProvider(rmeProvider);
JWTAuthenticationProvider jwtProvider = new JWTAuthenticationProvider();
auth.authenticationProvider(jwtProvider);
LDAPAuthenticationProvider ldapProvider = new LDAPAuthenticationProvider();
auth.authenticationProvider(ldapProvider);
} | java | {
"resource": ""
} |
q164736 | SecurityConfig.configure | train | @Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().requestMatchers(IgnoredRequestMatcher.INSTANCE);
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
web.httpFirewall(firewall);
//web.debug(true);
} | java | {
"resource": ""
} |
q164737 | SecurityConfig.configure | train | @Override
protected void configure(HttpSecurity http) throws Exception {
ConfigObject protectedResources = Config.getConfig().getObject("security.protected");
ConfigValue apiSec = Config.getConfig().getValue("security.api_security");
boolean enableRestFilter = apiSec != null && Boolean.TRUE.equals(apiSec.unwrapped());
String signinPath = Config.getConfigParam("security.signin", "/signin");
String signoutPath = Config.getConfigParam("security.signout", "/signout");
String accessDeniedPath = Config.getConfigParam("security.access_denied", "/403");
String signoutSuccessPath = Config.getConfigParam("security.signout_success", signinPath);
// If API security is disabled don't add the API endpoint to the list of protected resources
if (enableRestFilter) {
http.authorizeRequests().requestMatchers(RestRequestMatcher.INSTANCE);
}
parseProtectedResources(http, protectedResources);
if (Config.getConfigBoolean("security.csrf_protection", true)) {
http.csrf().requireCsrfProtectionMatcher(CsrfProtectionRequestMatcher.INSTANCE).
csrfTokenRepository(csrfTokenRepository);
} else {
http.csrf().disable();
}
http.sessionManagement().enableSessionUrlRewriting(false);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
http.sessionManagement().sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
http.exceptionHandling().authenticationEntryPoint(new SimpleAuthenticationEntryPoint(signinPath));
http.exceptionHandling().accessDeniedHandler(new SimpleAccessDeniedHandler(accessDeniedPath));
http.requestCache().requestCache(new SimpleRequestCache());
http.logout().logoutUrl(signoutPath).logoutSuccessUrl(signoutSuccessPath);
http.rememberMe().rememberMeServices(rememberMeServices);
registerAuthFilters(http);
if (enableRestFilter) {
if (jwtFilter != null) {
jwtFilter.setAuthenticationManager(authenticationManager());
http.addFilterBefore(jwtFilter, RememberMeAuthenticationFilter.class);
}
RestAuthFilter restFilter = new RestAuthFilter();
http.addFilterAfter(restFilter, JWTRestfulAuthFilter.class);
}
} | java | {
"resource": ""
} |
q164738 | Constraint.matches | train | public static boolean matches(Class<? extends Annotation> anno, String consName) {
return VALIDATORS.get(anno).equals(consName);
} | java | {
"resource": ""
} |
q164739 | Constraint.fromAnnotation | train | public static Constraint fromAnnotation(Annotation anno) {
if (anno instanceof Min) {
return min(((Min) anno).value());
} else if (anno instanceof Max) {
return max(((Max) anno).value());
} else if (anno instanceof Size) {
return size(((Size) anno).min(), ((Size) anno).max());
} else if (anno instanceof Digits) {
return digits(((Digits) anno).integer(), ((Digits) anno).fraction());
} else if (anno instanceof Pattern) {
return pattern(((Pattern) anno).regexp());
} else {
return new Constraint(VALIDATORS.get(anno.annotationType()),
simplePayload(VALIDATORS.get(anno.annotationType()))) {
public boolean isValid(Object actualValue) {
return true;
}
};
}
} | java | {
"resource": ""
} |
q164740 | Constraint.simplePayload | train | static Map<String, Object> simplePayload(final String name) {
if (name == null) {
return null;
}
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("message", MSG_PREFIX + name);
return payload;
} | java | {
"resource": ""
} |
q164741 | Constraint.required | train | public static Constraint required() {
return new Constraint("required", simplePayload("required")) {
public boolean isValid(Object actualValue) {
return !(actualValue == null || StringUtils.isBlank(actualValue.toString()));
}
};
} | java | {
"resource": ""
} |
q164742 | Constraint.min | train | public static Constraint min(final Number min) {
return new Constraint("min", minPayload(min)) {
public boolean isValid(Object actualValue) {
return actualValue == null || (actualValue instanceof Number && min != null &&
min.longValue() <= ((Number) actualValue).longValue());
}
};
} | java | {
"resource": ""
} |
q164743 | Constraint.max | train | public static Constraint max(final Number max) {
return new Constraint("max", maxPayload(max)) {
public boolean isValid(Object actualValue) {
return actualValue == null || (actualValue instanceof Number && max != null &&
max.longValue() >= ((Number) actualValue).longValue());
}
};
} | java | {
"resource": ""
} |
q164744 | Constraint.pattern | train | public static Constraint pattern(final Object regex) {
return new Constraint("pattern", patternPayload(regex)) {
public boolean isValid(Object actualValue) {
if (actualValue != null) {
if (regex != null && regex instanceof String) {
if (!(actualValue instanceof String) || !((String) actualValue).matches((String) regex)) {
return false;
}
}
}
return true;
}
};
} | java | {
"resource": ""
} |
q164745 | Constraint.email | train | public static Constraint email() {
return new Constraint("email", simplePayload("email")) {
public boolean isValid(Object actualValue) {
if (actualValue != null) {
if (!(actualValue instanceof String) || !Utils.isValidEmail((String) actualValue)) {
return false;
}
}
return true;
}
};
} | java | {
"resource": ""
} |
q164746 | Constraint.truthy | train | public static Constraint truthy() {
return new Constraint("true", simplePayload("true")) {
public boolean isValid(Object actualValue) {
if (actualValue != null) {
if ((actualValue instanceof Boolean && !((Boolean) actualValue))
|| (actualValue instanceof String && !Boolean.parseBoolean((String) actualValue))) {
return false;
}
}
return true;
}
};
} | java | {
"resource": ""
} |
q164747 | Constraint.url | train | public static Constraint url() {
return new Constraint("url", simplePayload("url")) {
public boolean isValid(Object actualValue) {
if (actualValue != null) {
if (!Utils.isValidURL(actualValue.toString())) {
return false;
}
}
return true;
}
};
} | java | {
"resource": ""
} |
q164748 | Constraint.build | train | public static Constraint build(String cname, Map<String, Object> payload) {
if (cname != null && payload != null) {
if ("min".equals(cname) && payload.containsKey("value")) {
return min(NumberUtils.toLong(payload.get("value") + "", 0));
} else if ("max".equals(cname) && payload.containsKey("value")) {
return max(NumberUtils.toLong(payload.get("value") + "", Config.DEFAULT_LIMIT));
} else if ("size".equals(cname) && payload.containsKey("min") && payload.containsKey("max")) {
return size(NumberUtils.toLong(payload.get("min") + "", 0),
NumberUtils.toLong(payload.get("max") + "", Config.DEFAULT_LIMIT));
} else if ("digits".equals(cname) && payload.containsKey("integer") && payload.containsKey("fraction")) {
return digits(NumberUtils.toLong(payload.get("integer") + "", 0),
NumberUtils.toLong(payload.get("fraction") + "", 0));
} else if ("pattern".equals(cname) && payload.containsKey("value")) {
return pattern(payload.get("value"));
} else {
return SIMPLE_CONSTRAINTS.get(cname);
}
}
return null;
} | java | {
"resource": ""
} |
q164749 | AuthenticatedUserDetails.getAuthorities | train | @JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
if (user.isAdmin()) {
return Collections.singleton(new SimpleGrantedAuthority(Roles.ADMIN.toString()));
} else if (user.isModerator()) {
return Collections.singleton(new SimpleGrantedAuthority(Roles.MOD.toString()));
} else {
return Collections.singleton(new SimpleGrantedAuthority(Roles.USER.toString()));
}
} | java | {
"resource": ""
} |
q164750 | ParaObjectUtils.getCoreTypes | train | public static Map<String, String> getCoreTypes() {
if (CORE_TYPES.isEmpty()) {
try {
for (Class<? extends ParaObject> clazz : getCoreClassesMap().values()) {
ParaObject p = clazz.getConstructor().newInstance();
CORE_TYPES.put(p.getPlural(), p.getType());
}
} catch (Exception ex) {
logger.error(null, ex);
}
}
return Collections.unmodifiableMap(CORE_TYPES);
} | java | {
"resource": ""
} |
q164751 | ParaObjectUtils.getAllTypes | train | public static Map<String, String> getAllTypes(App app) {
Map<String, String> map = new LinkedHashMap<>(getCoreTypes());
if (app != null) {
map.putAll(app.getDatatypes());
}
return map;
} | java | {
"resource": ""
} |
q164752 | ParaObjectUtils.getAppidFromAuthHeader | train | public static String getAppidFromAuthHeader(String authorization) {
if (StringUtils.isBlank(authorization)) {
return "";
}
String appid = "";
// JWT token
if (StringUtils.startsWith(authorization, "Bearer")) {
try {
String[] parts = StringUtils.split(authorization, '.');
if (parts.length > 1) {
Map<String, Object> jwt = getJsonReader(Map.class).readValue(Utils.base64dec(parts[1]));
if (jwt != null && jwt.containsKey(Config._APPID)) {
appid = (String) jwt.get(Config._APPID);
}
}
} catch (Exception e) { }
} else if (StringUtils.startsWith(authorization, "Anonymous")) {
// Anonymous request - no signature or JWT
appid = StringUtils.substringAfter(authorization, "Anonymous").trim();
} else {
// Amazon Signature v4
appid = StringUtils.substringBetween(authorization, "=", "/");
}
if (StringUtils.isBlank(appid)) {
return "";
}
return App.id(appid).substring(4);
} | java | {
"resource": ""
} |
q164753 | ParaObjectUtils.typesMatch | train | public static boolean typesMatch(ParaObject so) {
return (so == null) ? false : so.getClass().equals(toClass(so.getType()));
} | java | {
"resource": ""
} |
q164754 | ParaObjectUtils.toObject | train | public static <P extends ParaObject> P toObject(String type) {
try {
return (P) toClass(type).getConstructor().newInstance();
} catch (Exception ex) {
logger.error(null, ex);
return null;
}
} | java | {
"resource": ""
} |
q164755 | ParaObjectUtils.toJSON | train | public static <P extends ParaObject> String toJSON(P obj) {
if (obj == null) {
return "{}";
}
try {
return getJsonWriter().writeValueAsString(obj);
} catch (Exception e) {
logger.error(null, e);
}
return "{}";
} | java | {
"resource": ""
} |
q164756 | GZipServletResponseWrapper.flushBuffer | train | @Override
public void flushBuffer() throws IOException {
//PrintWriter.flush() does not throw exception
if (this.printWriter != null) {
this.printWriter.flush();
}
if (this.gzipOutputStream != null) {
this.gzipOutputStream.flush();
}
// doing this might leads to response already committed exception
// when the PageInfo has not yet built but the buffer already flushed
// Happens in Weblogic when a servlet forward to a JSP page and the forward
// method trigger a flush before it forwarded to the JSP
// disableFlushBuffer for that purpose is 'true' by default
if (!disableFlushBuffer) {
super.flushBuffer();
}
} | java | {
"resource": ""
} |
q164757 | GZipServletResponseWrapper.flush | train | public void flush() throws IOException {
if (printWriter != null) {
printWriter.flush();
}
if (gzipOutputStream != null) {
gzipOutputStream.flush();
}
} | java | {
"resource": ""
} |
q164758 | App.id | train | public static final String id(String id) {
if (StringUtils.startsWith(id, PREFIX)) {
return PREFIX.concat(Utils.noSpaces(Utils.stripAndTrim(id.replaceAll(PREFIX, ""), " "), "-"));
} else if (id != null) {
return PREFIX.concat(Utils.noSpaces(Utils.stripAndTrim(id, " "), "-"));
} else {
return null;
}
} | java | {
"resource": ""
} |
q164759 | App.addSetting | train | public App addSetting(String name, Object value) {
if (!StringUtils.isBlank(name) && value != null) {
getSettings().put(name, value);
for (AppSettingAddedListener listener : ADD_SETTING_LISTENERS) {
listener.onSettingAdded(this, name, value);
logger.debug("Executed {}.onSettingAdded().", listener.getClass().getName());
}
}
return this;
} | java | {
"resource": ""
} |
q164760 | App.getSetting | train | public Object getSetting(String name) {
if (!StringUtils.isBlank(name)) {
return getSettings().get(name);
}
return null;
} | java | {
"resource": ""
} |
q164761 | App.removeSetting | train | public App removeSetting(String name) {
if (!StringUtils.isBlank(name)) {
Object result = getSettings().remove(name);
if (result != null) {
for (AppSettingRemovedListener listener : REMOVE_SETTING_LISTENERS) {
listener.onSettingRemoved(this, name);
logger.debug("Executed {}.onSettingRemoved().", listener.getClass().getName());
}
}
}
return this;
} | java | {
"resource": ""
} |
q164762 | App.getValidationConstraints | train | public Map<String, Map<String, Map<String, Map<String, ?>>>> getValidationConstraints() {
if (validationConstraints == null) {
validationConstraints = new LinkedHashMap<>();
}
return validationConstraints;
} | java | {
"resource": ""
} |
q164763 | App.setValidationConstraints | train | public void setValidationConstraints(Map<String, Map<String, Map<String, Map<String, ?>>>> validationConstraints) {
this.validationConstraints = validationConstraints;
} | java | {
"resource": ""
} |
q164764 | App.getResourcePermissions | train | public Map<String, Map<String, List<String>>> getResourcePermissions() {
if (resourcePermissions == null) {
resourcePermissions = new LinkedHashMap<>();
}
return resourcePermissions;
} | java | {
"resource": ""
} |
q164765 | App.setResourcePermissions | train | public void setResourcePermissions(Map<String, Map<String, List<String>>> resourcePermissions) {
this.resourcePermissions = resourcePermissions;
} | java | {
"resource": ""
} |
q164766 | App.getDatatypes | train | @SuppressWarnings("unchecked")
public Map<String, String> getDatatypes() {
if (datatypes == null) {
datatypes = new DualHashBidiMap();
}
return datatypes;
} | java | {
"resource": ""
} |
q164767 | App.getAllValidationConstraints | train | public Map<String, Map<String, Map<String, Map<String, ?>>>> getAllValidationConstraints(String... types) {
Map<String, Map<String, Map<String, Map<String, ?>>>> allConstr = new LinkedHashMap<>();
if (types == null || types.length == 0) {
types = ParaObjectUtils.getAllTypes(this).values().toArray(new String[0]);
}
try {
for (String aType : types) {
Map<String, Map<String, Map<String, ?>>> vc = new LinkedHashMap<>();
// add all core constraints first
if (ValidationUtils.getCoreValidationConstraints().containsKey(aType)) {
vc.putAll(ValidationUtils.getCoreValidationConstraints().get(aType));
}
// also add the ones that are defined locally for this app
Map<String, Map<String, Map<String, ?>>> appConstraints = getValidationConstraints().get(aType);
if (appConstraints != null && !appConstraints.isEmpty()) {
vc.putAll(appConstraints);
}
if (!vc.isEmpty()) {
allConstr.put(aType, vc);
}
}
} catch (Exception ex) {
logger.error(null, ex);
}
return allConstr;
} | java | {
"resource": ""
} |
q164768 | App.addValidationConstraint | train | public boolean addValidationConstraint(String type, String field, Constraint c) {
if (!StringUtils.isBlank(type) && !StringUtils.isBlank(field) &&
c != null && !c.getPayload().isEmpty() &&
Constraint.isValidConstraintName(c.getName())) {
Map<String, Map<String, Map<String, ?>>> fieldMap = getValidationConstraints().get(type);
Map<String, Map<String, ?>> consMap;
if (fieldMap != null) {
consMap = fieldMap.get(field);
if (consMap == null) {
consMap = new LinkedHashMap<>();
}
} else {
fieldMap = new LinkedHashMap<>();
consMap = new LinkedHashMap<>();
}
consMap.put(c.getName(), c.getPayload());
fieldMap.put(field, consMap);
getValidationConstraints().put(type, fieldMap);
return true;
}
return false;
} | java | {
"resource": ""
} |
q164769 | App.removeValidationConstraint | train | public boolean removeValidationConstraint(String type, String field, String constraintName) {
if (!StringUtils.isBlank(type) && !StringUtils.isBlank(field) && constraintName != null) {
Map<String, Map<String, Map<String, ?>>> fieldsMap = getValidationConstraints().get(type);
if (fieldsMap != null && fieldsMap.containsKey(field)) {
if (fieldsMap.get(field).containsKey(constraintName)) {
fieldsMap.get(field).remove(constraintName);
}
if (fieldsMap.get(field).isEmpty()) {
getValidationConstraints().get(type).remove(field);
}
if (getValidationConstraints().get(type).isEmpty()) {
getValidationConstraints().remove(type);
}
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q164770 | App.getAllResourcePermissions | train | public Map<String, Map<String, List<String>>> getAllResourcePermissions(String... subjectids) {
Map<String, Map<String, List<String>>> allPermits = new LinkedHashMap<>();
if (subjectids == null || subjectids.length == 0) {
return getResourcePermissions();
}
try {
for (String subjectid : subjectids) {
if (subjectid != null) {
if (getResourcePermissions().containsKey(subjectid)) {
allPermits.put(subjectid, getResourcePermissions().get(subjectid));
} else {
allPermits.put(subjectid, new LinkedHashMap<>(0));
}
if (getResourcePermissions().containsKey(ALLOW_ALL)) {
allPermits.put(ALLOW_ALL, getResourcePermissions().get(ALLOW_ALL));
}
}
}
} catch (Exception ex) {
logger.error(null, ex);
}
return allPermits;
} | java | {
"resource": ""
} |
q164771 | App.revokeResourcePermission | train | public boolean revokeResourcePermission(String subjectid, String resourcePath) {
if (!StringUtils.isBlank(subjectid) && getResourcePermissions().containsKey(subjectid) &&
!StringUtils.isBlank(resourcePath)) {
// urlDecode resource path
resourcePath = Utils.urlDecode(resourcePath);
getResourcePermissions().get(subjectid).remove(resourcePath);
if (getResourcePermissions().get(subjectid).isEmpty()) {
getResourcePermissions().remove(subjectid);
}
return true;
}
return false;
} | java | {
"resource": ""
} |
q164772 | App.revokeAllResourcePermissions | train | public boolean revokeAllResourcePermissions(String subjectid) {
if (!StringUtils.isBlank(subjectid) && getResourcePermissions().containsKey(subjectid)) {
getResourcePermissions().remove(subjectid);
return true;
}
return false;
} | java | {
"resource": ""
} |
q164773 | App.isDeniedExplicitly | train | final boolean isDeniedExplicitly(String subjectid, String resourcePath, String httpMethod) {
if (StringUtils.isBlank(subjectid) || StringUtils.isBlank(resourcePath) ||
StringUtils.isBlank(httpMethod) || getResourcePermissions().isEmpty()) {
return false;
}
// urlDecode resource path
resourcePath = Utils.urlDecode(resourcePath);
if (getResourcePermissions().containsKey(subjectid)) {
if (getResourcePermissions().get(subjectid).containsKey(resourcePath)) {
return !isAllowed(subjectid, resourcePath, httpMethod);
} else if (getResourcePermissions().get(subjectid).containsKey(ALLOW_ALL)) {
return !isAllowed(subjectid, ALLOW_ALL, httpMethod);
}
}
return false;
} | java | {
"resource": ""
} |
q164774 | App.permissionsContainOwnKeyword | train | public boolean permissionsContainOwnKeyword(User user, ParaObject object) {
if (user == null || object == null) {
return false;
}
String resourcePath1 = object.getType();
String resourcePath2 = object.getObjectURI().substring(1); // remove first '/'
String resourcePath3 = object.getPlural();
return hasOwnKeyword(App.ALLOW_ALL, resourcePath1)
|| hasOwnKeyword(App.ALLOW_ALL, resourcePath2)
|| hasOwnKeyword(App.ALLOW_ALL, resourcePath3)
|| hasOwnKeyword(user.getId(), resourcePath1)
|| hasOwnKeyword(user.getId(), resourcePath2)
|| hasOwnKeyword(user.getId(), resourcePath3);
} | java | {
"resource": ""
} |
q164775 | App.addDatatype | train | public void addDatatype(String pluralDatatype, String datatype) {
pluralDatatype = Utils.noSpaces(Utils.stripAndTrim(pluralDatatype, " "), "-");
datatype = Utils.noSpaces(Utils.stripAndTrim(datatype, " "), "-");
if (StringUtils.isBlank(pluralDatatype) || StringUtils.isBlank(datatype)) {
return;
}
if (getDatatypes().size() >= Config.MAX_DATATYPES_PER_APP) {
LoggerFactory.getLogger(App.class).warn("Maximum number of types per app reached - {}.",
Config.MAX_DATATYPES_PER_APP);
return;
}
if (!getDatatypes().containsKey(pluralDatatype) && !getDatatypes().containsValue(datatype) &&
!ParaObjectUtils.getCoreTypes().containsKey(pluralDatatype)) {
getDatatypes().put(pluralDatatype, datatype);
}
} | java | {
"resource": ""
} |
q164776 | App.getCredentials | train | @JsonIgnore
public Map<String, String> getCredentials() {
if (getId() == null) {
return Collections.emptyMap();
} else {
Map<String, String> keys = new LinkedHashMap<String, String>(2);
keys.put("accessKey", getId());
keys.put("secretKey", getSecret());
return keys;
}
} | java | {
"resource": ""
} |
q164777 | Config.init | train | public static void init(com.typesafe.config.Config conf) {
try {
config = ConfigFactory.load().getConfig(PARA);
if (conf != null) {
config = conf.withFallback(config);
}
configMap = new HashMap<>();
for (Map.Entry<String, ConfigValue> con : config.entrySet()) {
if (con.getValue().valueType() != ConfigValueType.LIST) {
configMap.put(con.getKey(), config.getString(con.getKey()));
}
}
} catch (Exception ex) {
logger.warn("Para configuration file 'application.(conf|json|properties)' is missing from classpath.");
config = com.typesafe.config.ConfigFactory.empty();
}
} | java | {
"resource": ""
} |
q164778 | Config.getConfigBoolean | train | public static boolean getConfigBoolean(String key, boolean defaultValue) {
return Boolean.parseBoolean(getConfigParam(key, Boolean.toString(defaultValue)));
} | java | {
"resource": ""
} |
q164779 | Config.getConfigInt | train | public static int getConfigInt(String key, int defaultValue) {
return NumberUtils.toInt(getConfigParam(key, Integer.toString(defaultValue)));
} | java | {
"resource": ""
} |
q164780 | Config.getConfigDouble | train | public static double getConfigDouble(String key, double defaultValue) {
return NumberUtils.toDouble(getConfigParam(key, Double.toString(defaultValue)));
} | java | {
"resource": ""
} |
q164781 | Config.getConfig | train | public static com.typesafe.config.Config getConfig() {
if (config == null) {
init(null);
}
return config;
} | java | {
"resource": ""
} |
q164782 | SimpleRequestCache.saveRequest | train | @Override
public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
if (anyRequestMatcher.matches(request) && !ajaxRequestMatcher.matches(request)) {
DefaultSavedRequest savedRequest = new DefaultSavedRequest(request, portResolver);
HttpUtils.setStateParam(Config.RETURNTO_COOKIE,
Utils.base64enc(savedRequest.getRedirectUrl().getBytes()), request, response);
}
} | java | {
"resource": ""
} |
q164783 | SimpleRequestCache.removeRequest | train | @Override
public void removeRequest(HttpServletRequest request, HttpServletResponse response) {
HttpUtils.removeStateParam(Config.RETURNTO_COOKIE, request, response);
} | java | {
"resource": ""
} |
q164784 | SearchQueryAspect.invoke | train | public Object invoke(MethodInvocation mi) throws Throwable {
if (!Modifier.isPublic(mi.getMethod().getModifiers())) {
return mi.proceed();
}
Method searchMethod = mi.getMethod();
Object[] args = mi.getArguments();
String appid = AOPUtils.getFirstArgOfString(args);
Method superMethod = null;
Measured measuredAnno = null;
try {
superMethod = Search.class.getMethod(searchMethod.getName(), searchMethod.getParameterTypes());
measuredAnno = superMethod.getAnnotation(Measured.class);
} catch (Exception e) {
logger.error("Error in search AOP layer!", e);
}
Set<IOListener> ioListeners = Para.getSearchQueryListeners();
for (IOListener ioListener : ioListeners) {
ioListener.onPreInvoke(superMethod, args);
logger.debug("Executed {}.onPreInvoke().", ioListener.getClass().getName());
}
Object result = null;
if (measuredAnno != null) {
result = invokeTimedSearch(appid, searchMethod, mi);
} else {
result = mi.proceed();
}
for (IOListener ioListener : ioListeners) {
ioListener.onPostInvoke(superMethod, result);
logger.debug("Executed {}.onPostInvoke().", ioListener.getClass().getName());
}
return result;
} | java | {
"resource": ""
} |
q164785 | HttpUtils.removeStateParam | train | public static void removeStateParam(String name, HttpServletRequest req,
HttpServletResponse res) {
setRawCookie(name, "", req, res, false, 0);
} | java | {
"resource": ""
} |
q164786 | HttpUtils.getCookieValue | train | public static String getCookieValue(HttpServletRequest req, String name) {
if (StringUtils.isBlank(name) || req == null) {
return null;
}
Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
//Otherwise, we have to do a linear scan for the cookie.
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie.getValue();
}
}
return null;
} | java | {
"resource": ""
} |
q164787 | SimpleAxFetchListFactory.createAttributeList | train | public List<OpenIDAttribute> createAttributeList(String identifier) {
List<OpenIDAttribute> list = new LinkedList<>();
if (identifier != null && identifier.matches("https://www.google.com/.*")) {
OpenIDAttribute email = new OpenIDAttribute("email", "http://axschema.org/contact/email");
OpenIDAttribute first = new OpenIDAttribute("firstname", "http://axschema.org/namePerson/first");
OpenIDAttribute last = new OpenIDAttribute("lastname", "http://axschema.org/namePerson/last");
email.setCount(1);
email.setRequired(true);
first.setRequired(true);
last.setRequired(true);
list.add(email);
list.add(first);
list.add(last);
}
return list;
} | java | {
"resource": ""
} |
q164788 | Thing.getDeviceMetadata | train | @JsonIgnore
public Map<String, Object> getDeviceMetadata() {
if (deviceMetadata == null) {
deviceMetadata = new LinkedHashMap<>(20);
}
return deviceMetadata;
} | java | {
"resource": ""
} |
q164789 | Vote.isExpired | train | public boolean isExpired() {
if (getTimestamp() == null || getExpiresAfter() == 0) {
return false;
}
long expires = (getExpiresAfter() * 1000);
long now = Utils.timestamp();
return (getTimestamp() + expires) <= now;
} | java | {
"resource": ""
} |
q164790 | Vote.isAmendable | train | public boolean isAmendable() {
if (getTimestamp() == null) {
return false;
}
long now = Utils.timestamp();
// check timestamp for recent correction,
return (getTimestamp() + (Config.VOTE_LOCKED_AFTER_SEC * 1000)) > now;
} | java | {
"resource": ""
} |
q164791 | GZipResponseUtil.addGzipHeader | train | public static void addGzipHeader(final HttpServletResponse response) throws ServletException {
response.setHeader("Content-Encoding", "gzip");
boolean containsEncoding = response.containsHeader("Content-Encoding");
if (!containsEncoding) {
throw new ServletException("Failure when attempting to set Content-Encoding: gzip");
}
} | java | {
"resource": ""
} |
q164792 | OAuth1HmacSigner.sign | train | public static String sign(String httpMethod, String url, Map<String, String[]> params,
String apiKey, String apiSecret, String oauthToken, String tokenSecret) {
try {
if (httpMethod != null && url != null && !url.trim().isEmpty() && params != null && apiSecret != null) {
Map<String, String[]> paramMap = new TreeMap<>(params);
String keyString = percentEncode(apiSecret) + "&" + percentEncode(tokenSecret);
byte[] keyBytes = keyString.getBytes(Config.DEFAULT_ENCODING);
SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
addRequiredParameters(paramMap, apiKey, oauthToken);
String sbs = httpMethod.toUpperCase() + "&" + percentEncode(normalizeRequestUrl(url))
+ "&" + percentEncode(normalizeRequestParameters(paramMap));
logger.debug("Oatuh1 base string: {}", sbs);
byte[] text = sbs.getBytes(Config.DEFAULT_ENCODING);
String sig = Utils.base64enc(mac.doFinal(text)).trim();
logger.debug("Oauth1 Signature: {}", sig);
StringBuilder sb = new StringBuilder();
sb.append("OAuth ");
// add the realm parameter, if any
if (paramMap.containsKey("realm")) {
String val = paramMap.get("realm")[0];
sb.append("realm=\"".concat(val).concat("\""));
sb.append(", ");
}
Map<String, SortedSet<String>> oauthParams = getOAuthParameters(paramMap);
TreeSet<String> set = new TreeSet<>();
set.add(percentEncode(sig));
oauthParams.put("oauth_signature", set);
Iterator<String> iter = oauthParams.keySet().iterator();
while (iter.hasNext()) {
String param = iter.next();
SortedSet<String> valSet = oauthParams.get(param);
String value = (valSet == null || valSet.isEmpty()) ? null : valSet.first();
String headerElem = (value == null) ? null : param + "=\"" + value + "\"";
sb.append(headerElem);
if (iter.hasNext()) {
sb.append(", ");
}
}
String header = sb.toString();
logger.debug("OAuth1 signed header: {}", header);
return header;
}
} catch (Exception e) {
logger.error(null, e);
}
return null;
} | java | {
"resource": ""
} |
q164793 | Utils.md5 | train | public static String md5(String s) {
if (s == null) {
return "";
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(s.getBytes());
byte[] byteData = md.digest();
//convert the byte to hex format method 1
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
return "";
}
} | java | {
"resource": ""
} |
q164794 | Utils.bcrypt | train | public static String bcrypt(String s) {
return (s == null) ? s : BCrypt.hashpw(s, BCrypt.gensalt(12));
} | java | {
"resource": ""
} |
q164795 | Utils.bcryptMatches | train | public static boolean bcryptMatches(String plain, String storedHash) {
if (StringUtils.isBlank(plain) || StringUtils.isBlank(storedHash)) {
return false;
}
try {
return BCrypt.checkpw(plain, storedHash);
} catch (Exception e) {
return false;
}
} | java | {
"resource": ""
} |
q164796 | Utils.generateSecurityToken | train | public static String generateSecurityToken(int length, boolean urlSafe) {
final byte[] bytes = new byte[length];
SecureRandom rand;
try {
rand = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException ex) {
logger.error(null, ex);
rand = new SecureRandom();
}
rand.nextBytes(bytes);
return urlSafe ? base64encURL(bytes) : base64enc(bytes);
} | java | {
"resource": ""
} |
q164797 | Utils.stripHtml | train | public static String stripHtml(String html) {
return (html == null) ? "" : Jsoup.parse(html).text();
} | java | {
"resource": ""
} |
q164798 | Utils.abbreviate | train | public static String abbreviate(String str, int max) {
return StringUtils.isBlank(str) ? "" : StringUtils.abbreviate(str, max);
} | java | {
"resource": ""
} |
q164799 | Utils.arrayJoin | train | public static String arrayJoin(List<String> arr, String separator) {
return (arr == null || separator == null) ? "" : StringUtils.join(arr, separator);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.