public static User getCurrentUser(String username) { User user = new User(); try { if (StringUtils.isNotBlank(username)) { user = (User)getJdbcTemplate().queryForObject( GET_CURRENT_USER_INFO, new UserRowMapper(), username); } } catch(EmptyResultDataAccessException e) { Logger.error("UserDAO getCurrentUser failed, username = " + username); Logger.error("Exception = " + e.getMessage()); } return user; }
/** * @desc 分页查询所有链路列表 * * @author liuliang * * @param pageIndex 当前页 * @param pageSize 每页条数 * @return List<LinkBO> 链路BO集合 * @throws Exception */ @Override public List<LinkBO> getLinkList(String linkName,int pageIndex, int pageSize) throws Exception{ //1、查询 List<Link> linkList = null; if(StringUtils.isBlank(linkName)){ linkList = linkDao.queryLinkByPage(pageIndex, pageSize); }else{ linkList = linkDao.queryLinkByPage(linkName,pageIndex, pageSize); } //2、转换 List<LinkBO> linkBOList = new ArrayList<LinkBO>(); if((null != linkList) && (0 < linkList.size())){ LinkBO linkBO = null; for(Link link:linkList){ linkBO = new LinkBO(); BeanUtils.copyProperties(link, linkBO); linkBOList.add(linkBO); } } //3、返回 return linkBOList; }
/** * 微信下单map to xml * * @param params * 参数 * @return String */ public static String toXml(Map<String, String> params) { StringBuilder xml = new StringBuilder(); xml.append("<xml>"); for (Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // 略过空值 if (StringUtils.isBlank(value)) continue; xml.append("<").append(key).append(">"); xml.append(entry.getValue()); xml.append("</").append(key).append(">"); } xml.append("</xml>"); return xml.toString(); }
public static void init(Context ctx){ context = ctx; preferences = ctx.getSharedPreferences(CHAT_SDK_SHRED_PREFS, Context.MODE_PRIVATE); VolleyUtils.init(ctx); DaoCore.init(ctx); BFacebookManager.init(context.getString(R.string.facebook_id), ctx); //Bug Sense if (BNetworkManager.BUGSENSE_ENABLED && StringUtils.isNotEmpty( context.getString(R.string.bug_sense_key) )) { BugSenseHandler.initAndStartSession(ctx, context.getString(R.string.bug_sense_key)); BugSenseHandler.addCrashExtraData("Version", BuildConfig.VERSION_NAME); } }
public void searchInBody(String pattern) { httpCallBodyView.removeOldHighlightedSpans(); if (StringUtils.isEmpty(pattern)) { return; } ArrayList<Bound> bounds = new ArrayList<>(); int indexOfKeyword = formattedBodyLowerCase.indexOf(pattern); while (indexOfKeyword > -1) { int rightBound = indexOfKeyword + pattern.length(); bounds.add(new Bound(indexOfKeyword, rightBound)); indexOfKeyword = formattedBodyLowerCase.indexOf(pattern, rightBound); } if (!bounds.isEmpty()) { httpCallBodyView.highlightBounds(bounds); } }
private void notifyNewYear(NewYearNotification baseNotification, Guild guild) { NewYearNotification notification = repository.findOneByGuildId(guild.getId()); if (notification == null) { notification = baseNotification; } if (notification == null || !notification.isEnabled() || StringUtils.isEmpty(notification.getMessage())) { return; } TextChannel channel = getChannel(notification, guild); if (channel == null) { return; } String message = notification.getMessage(); MapPlaceholderResolver resolver = new MapPlaceholderResolver(); resolver.put("name", guild.getName()); message = placeholderHelper.replacePlaceholders(message, resolver); EmbedBuilder builder = messageService.getBaseEmbed(); if (StringUtils.isNotEmpty(notification.getImageUrl())) { builder.setImage(notification.getImageUrl()); } builder.setDescription(message); messageService.sendMessageSilent(channel::sendMessage, builder.build()); }
/** * 根据key和类的类别获取缓存对象 * * @param key * 键 * @param value * 值 * @param <T> * 泛型对象 * @return json字符串 */ @Override public <T> T get(final String bizkey, final String nameSpace, Class<T> value, final GetDataCallBack<T> gbs) { final String key = CacheUtils.getKeyByNamespace(bizkey, nameSpace); String res = get(bizkey, nameSpace, null); T rtn = null; if (StringUtils.isNotEmpty(res)) { rtn = CacheUtils.parseObject(key, res, value); } else { if (gbs != null) { rtn = gbs.invoke(); // 取出的数据要set回去 if (null != rtn) { set(bizkey, nameSpace, rtn, gbs.getExpiredTime()); } } } return rtn; }
@Security.Authenticated(Secured.class) public static Result flowLineage(String application, String project, String flow) { String username = session("user"); if (username == null) { username = ""; } String type = "azkaban"; if (StringUtils.isNotBlank(application) && (application.toLowerCase().indexOf("appworx") != -1)) { type = "appworx"; } return ok(lineage.render(username, type, 0, application.replace(" ", "."), project, flow)); }
@Override public void run() { if (GenerationUtils.validate(containerName)) { Shell shell = Display.getDefault().getActiveShell(); boolean confirm = MessageDialog.openQuestion(shell, "Confirm Create", "Existing Files will be cleared. Do you wish to continue?"); if (confirm) { wsRoot = ResourcesPlugin.getWorkspace().getRoot(); names = StringUtils.split(containerName, "/"); wsRootRes = wsRoot.findMember(new Path("/" + names[0])); prj = wsRootRes.getProject(); steps = prj.getFolder("target/Steps"); File root = new File(steps.getLocation().toOSString()); if (root.exists()) { GenerationUtils.clearCreatedFolders(root); } for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { try { project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { } } } } }
@SystemControllerLog(description="权限管理-角色列表") @RequestMapping(value = "/data") @ResponseBody public String data(String params) { try { ObjectMapper om = new ObjectMapper(); Map<String, Object> map = new HashMap<String, Object>(); if (!StringUtils.isEmpty(params)) { // 参数处理 map = om.readValue(params, new TypeReference<Map<String, Object>>() {}); } PagerModel<Role> pg = roleService.findPaginated(map); // 序列化查询结果为JSON Map<String, Object> result = new HashMap<String, Object>(); result.put("total", pg.getTotal()); result.put("rows", pg.getData()); return om.writeValueAsString(result); } catch (Exception e) { e.printStackTrace(); return "{ \"total\" : 0, \"rows\" : [] }"; } }
@Override protected void addProxyHeaders(final HttpServletRequest clientRequest, final Request proxyRequest) { super.addProxyHeaders(clientRequest, proxyRequest); // Forward security identifier if defined proxyRequest.header("SM_UNIVERSALID", clientRequest.getUserPrincipal() == null ? StringUtils.trimToNull(clientRequest.getParameter(apiUserParameter)) : clientRequest.getUserPrincipal().getName()); // Forward original SESSIONID proxyRequest.header("SM_SESSIONID", clientRequest.getSession(false) == null ? null : clientRequest.getSession(false).getId()); // Forward API key, if defined. proxyRequest.header(apiKeyHeader, StringUtils.trimToNull(clientRequest.getParameter(apiKeyParameter))); // Forward all cookies but JSESSIONID. final String cookies = clientRequest.getHeader(HEADER_COOKIE); if (cookies != null) { proxyRequest.header(HEADER_COOKIE, StringUtils.trimToNull( Arrays.stream(cookies.split("; ")).filter(cookie -> !cookie.split("=")[0].equals(COOKIE_JEE)).collect(Collectors.joining("; ")))); } }
public static Promise<Result> updateDatasetSecurity(int datasetId) { String username = session("user"); if (StringUtils.isNotBlank(username)) { final String queryUrl = BACKEND_URL + DATASET_SECURITY_PATH; final JsonNode queryNode = Json.newObject() .put("datasetId", datasetId) .set("securitySpecification", request().body().asJson()); return WS.url(queryUrl) .setRequestTimeout(1000) .post(queryNode) .map(response -> ok(response.asJson()) ); } else { final JsonNode result = Json.newObject() .put("status", "failed") .put("error", "true") .put("msg", "Unauthorized User."); return Promise.promise(() -> ok(result)); } }
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (EasyExpandMeta) smi; data = (EasyExpandData) sdi; if(StringUtils.isNotBlank(meta.getClassName())){ try { //实例化配置的类 if(first){ kui = (EasyExpandRunBase) Class.forName( environmentSubstitute(meta.getClassName())).newInstance(); kui.setKu(this); kui.setMeta(meta,this); } kui.setData(data); return kui.run(); } catch (Exception e) { setErrors(getErrors()+1); logError("运行失败,"+meta.getClassName()+"," +environmentSubstitute(meta.getConfigInfo()), e); return defaultRun(); } }else{ return defaultRun(); } }
public static <T> Matcher<SolrInputField> solrInputField(String fieldName, Matcher<T> valueMatcher) { return new TypeSafeMatcher<SolrInputField>() { @Override protected boolean matchesSafely(SolrInputField item) { return StringUtils.equals(fieldName, item.getName()) && valueMatcher.matches(item.getValue()); } @Override public void describeTo(Description description) { description.appendText("SolrInputField(") .appendValue(fieldName) .appendText(" value matching ") .appendDescriptionOf(valueMatcher) .appendText(")"); } }; }
/** * Checks if a Displayname is valid according to the configuration * <br /><br /><b>Note: </b> Field is also valid if it is null or blank * <br />Also set {@link RequiredValidator} for to validate mandantory fields */ @Override public boolean isValid(final String displayName) { if (StringUtils.isBlank(displayName)) { return true; } if (displayName.length() < c.getIntProperty("validation.displayname.minLength") || displayName.length() > c.getIntProperty("validation.displayname.maxLength")) { return false; } if (!c.getBooleanProperty("validation.displayname.allowSpecial")) { if (displayName.matches(CONTAINS_SPECIALCHARS_REGEX)) { return false; } } return true; }
@RequestMapping(value = "/save", method = RequestMethod.POST) @ResponseBody public String save(@RequestParam String params) { JSONObject po = JSONObject.parseObject(params); MchInfo mchInfo = new MchInfo(); String mchId = po.getString("mchId"); mchInfo.setName(po.getString("name")); mchInfo.setType(po.getString("type")); mchInfo.setState((byte) ("on".equalsIgnoreCase(po.getString("state")) ? 1 : 0)); mchInfo.setReqKey(po.getString("reqKey")); mchInfo.setResKey(po.getString("resKey")); int result; if(StringUtils.isBlank(mchId)) { // 添加 result = mchInfoService.addMchInfo(mchInfo); }else { // 修改 mchInfo.setMchId(mchId); result = mchInfoService.updateMchInfo(mchInfo); } _log.info("保存商户记录,返回:{}", result); return result+""; }
@Override protected String handleHttpResponseResult(CloseableHttpResponse httpResponse) throws Throwable { if (StringUtils.isNotBlank(charset)) { return IOUtils.toString(httpResponse.getEntity().getContent(), charset); } Charset contentTypeCharset = getCharsetFromContentType(httpResponse.getEntity()); if (contentTypeCharset != null) { return IOUtils.toString(httpResponse.getEntity().getContent(), contentTypeCharset.name()); } byte[] bytes = IOUtils.toByteArray(httpResponse.getEntity().getContent()); String content = new String(bytes, Config.DEFAULT_CHARSET); Charset contentCharset = getCharsetFromContent(content); if (contentCharset == null || contentCharset.name().equalsIgnoreCase(Config.DEFAULT_CHARSET)) { return content; } return new String(bytes, contentCharset); }
@Override public boolean deleteTicket(final String ticketIdToDelete) { final String ticketId = encodeTicketId(ticketIdToDelete); if (StringUtils.isBlank(ticketId)) { return false; } final Ticket ticket = getTicket(ticketId); if (ticket == null) { return false; } if (ticket instanceof TicketGrantingTicket) { logger.debug("Removing ticket [{}] and its children from the registry.", ticket); return deleteTicketAndChildren((TicketGrantingTicket) ticket); } logger.debug("Removing ticket [{}] from the registry.", ticket); return this.serviceTicketsCache.remove(ticketId); }
/** * Rename existing file on server if there is a conflict. */ @Override public void apply(final Path file, final Local local, final TransferStatus status, final ProgressListener listener) throws BackgroundException { // Rename existing file before putting new file in place if(status.isExists()) { Path rename; do { final String proposal = MessageFormat.format(PreferencesFactory.get().getProperty("queue.upload.file.rename.format"), FilenameUtils.getBaseName(file.getName()), UserDateFormatterFactory.get().getMediumFormat(System.currentTimeMillis(), false).replace(Path.DELIMITER, '-').replace(':', '-'), StringUtils.isNotBlank(file.getExtension()) ? String.format(".%s", file.getExtension()) : StringUtils.EMPTY); rename = new Path(file.getParent(), proposal, file.getType()); } while(find.find(rename)); if(log.isInfoEnabled()) { log.info(String.format("Rename existing file %s to %s", file, rename)); } move.move(file, rename, new TransferStatus().exists(false), new Delete.DisabledCallback(), new DisabledConnectionCallback()); if(log.isDebugEnabled()) { log.debug(String.format("Clear exist flag for file %s", file)); } status.setExists(false); } super.apply(file, local, status, listener); }
@Override public void process(Object annotation, OperationGenerator operationGenerator) { PutMapping mappingAnnotation = (PutMapping) annotation; Operation operation = operationGenerator.getOperation(); // path/value是等同的 this.processPath(mappingAnnotation.path(), operationGenerator); this.processPath(mappingAnnotation.value(), operationGenerator); this.processMethod(RequestMethod.PUT, operationGenerator); this.processConsumes(mappingAnnotation.consumes(), operation); this.processProduces(mappingAnnotation.produces(), operation); if (StringUtils.isEmpty(operationGenerator.getHttpMethod()) && StringUtils.isEmpty(operationGenerator.getSwaggerGenerator().getHttpMethod())) { throw new Error("HttpMethod must not both be empty in class and method"); } }
public static String convertToURN(LineagePathInfo pathInfo) { if (pathInfo == null) return null; String filePath = ""; if (StringUtils.isNotBlank(pathInfo.filePath)) { if(pathInfo.filePath.charAt(0) == '/') { filePath = pathInfo.filePath.substring(1); } else { filePath = pathInfo.filePath; } } return pathInfo.storageType.toLowerCase() + ":///" + filePath; }
public List<Workspace> listWorkspaces(final String masterURL, final String namespace, final String openShiftToken, final String repository, final String requestUrl, final String keycloakToken) throws RouteNotFoundException { String cheServerURL = openShiftClientWrapper.getCheServerUrl(masterURL, namespace, openShiftToken, keycloakToken); List<Workspace> workspaces; try { if (!StringUtils.isBlank(repository)) { LOG.info("Fetching workspaces for repositoriy: {}", repository); workspaces = workspaceClient.listWorkspacesPerRepository(cheServerURL, repository, keycloakToken); } else { workspaces = workspaceClient.listWorkspaces(cheServerURL, keycloakToken); } workspaceHelper.addWorkspaceStartLink(workspaces, requestUrl); } catch (RestClientException e) { throw new RestClientException( "Error while getting the list of workspaces against che server route: " + cheServerURL, e); } return workspaces; }
/** * 使用UUID获取唯一的文件名 * * @param filename 文件名 * @return 返回经过UUID处理后的filename */ public static String getUUIDName(String filename) { // 判断文件名是否为空 if (StringUtils.isBlank(filename)) { return null; } String name = filename; String ext = getExtension(filename); if (ext != null) {// 有后缀 name = getBaseName(filename); } else { ext = ""; } StringBuilder sb = new StringBuilder(name); sb.append('_').append(UUID.randomUUID().toString().replaceAll("-", "")).append(ext); return sb.toString(); }
@Override public void dumpHisAfnemerindicatieTabel(final File outputFile) { LOGGER.info("Genereer hisafnemerindicatie rijen naar {}", outputFile.getAbsolutePath()); try (FileOutputStream fos = new FileOutputStream(outputFile)) { final SqlRowSet sqlRowSet = new JdbcTemplate(masterDataSource).queryForRowSet("select hpa.* from autaut.his_persafnemerindicatie hpa\n" + "inner join (select pa.id as afnemerindid \n" + "from autaut.persafnemerindicatie pa, autaut.levsautorisatie la where pa.levsautorisatie = la.id and la.dateinde is null) \n" + "as x on hpa.persafnemerindicatie = x.afnemerindid"); while (sqlRowSet.next()) { IOUtils.write(String.format("%s,%s,%s,%s,%s,%s,%s,%s%n", sqlRowSet.getString(INDEX_HIS_ID), sqlRowSet.getString(INDEX_HIS_PERSAFNEMERINDICATIE), sqlRowSet.getString(INDEX_HIS_TSREG), StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_TSVERVAL), AfnemerindicatieConversie.NULL_VALUE), StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DIENSTINHOUD), AfnemerindicatieConversie.NULL_VALUE), StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DIENSTVERVAL), AfnemerindicatieConversie.NULL_VALUE), StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DATAANVANGMATERIELEPERIODE), AfnemerindicatieConversie.NULL_VALUE), StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DATEINDEVOLGEN), AfnemerindicatieConversie.NULL_VALUE) ), fos, StandardCharsets.UTF_8); } } catch (IOException e) { throw new IllegalStateException(e); } }
public void saveMonitor(Monitor monitor) throws NiPingException { String monitorId = monitor.getMonitorId(); Date currentDate = new Date(); String nipingT = monitor.getNipingT(); monitor.setModifiedTime(currentDate); try { if (monitorDao.countMonitor(monitorId) == 0) { monitor.setCreationTime(currentDate); monitor.setStatus(Monitor.Status.active.getStatus()); monitorDao.insertMonitor(monitor); log.debug("monitor {} saved", monitor); } else if (StringUtils.isNoneBlank(nipingT)) { monitorDao.updateMonitorNiping(monitor); log.debug("monitor {} modified", monitor); } } catch (DBIException e) { log.error("monitors: save monitor {} error: {}", monitor, ExceptionUtils.getMessage(e)); throw new NiPingException(DBError); } }
/** * Returns list of long values by splititng input string. * @param input Input string. * @return List of long values. */ public static List<Long> splitToLongList(String input) { if (StringUtils.isEmpty(input)) { return Collections.emptyList(); } return Arrays.stream(StringUtils.split(input, ',')) .map(value -> { try { return Long.parseLong(value); } catch (NumberFormatException e) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); }
private boolean shouldIssueTicketGrantingTicket(final Authentication authentication, final String ticketGrantingTicket) { boolean issueTicketGrantingTicket = true; if (StringUtils.isNotBlank(ticketGrantingTicket)) { LOGGER.debug("Located ticket-granting ticket in the context. Retrieving associated authentication"); final Authentication authenticationFromTgt = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket); if (authenticationFromTgt == null) { LOGGER.debug("Authentication session associated with [{}] is no longer valid", ticketGrantingTicket); this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicket); } else if (authentication.getPrincipal().equals(authenticationFromTgt.getPrincipal())) { LOGGER.debug("Resulting authentication matches the authentication from context"); issueTicketGrantingTicket = false; } else { LOGGER.debug("Resulting authentication is different from the context"); } } return issueTicketGrantingTicket; }
/** * Gets the live env's persisted logicaldb record. Requires exactly 1. */ private LogicalDatabase findLiveLogicalDatabaseFromEnvironment() { List<LogicalDatabase> logicalDatabases = liveEnv.getLogicalDatabases(); if (CollectionUtils.isEmpty(logicalDatabases)) { throw new IllegalStateException(liveContext() + "No logical databases"); } else if (logicalDatabases.size() > 1) { throw new UnsupportedOperationException(liveContext() + "Currently only support case of 1 logicalDatabase, but live env has " + logicalDatabases.size() + ": " + environmentHelper.listOfNames(logicalDatabases)); } else if (StringUtils.isBlank(logicalDatabases.get(0).getLogicalName())) { throw new IllegalStateException(liveContext() + "Live logical database has blank name"); } return logicalDatabases.get(0); }
/** * This method will do basic validation for user request object. * * @param userRequest */ public static void doUserBasicValidation(Request userRequest) { if (StringUtils.isBlank((String)userRequest.getRequest().get(JsonKey.USERNAME))) { throw new ProjectCommonException(ResponseCode.userNameRequired.getErrorCode(), ResponseCode.userNameRequired.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.FIRST_NAME))) { throw new ProjectCommonException(ResponseCode.firstNameRequired.getErrorCode(), ResponseCode.firstNameRequired.getErrorMessage(), ERROR_CODE); } if (userRequest.getRequest().containsKey(JsonKey.ROLES) && null != userRequest.getRequest().get(JsonKey.ROLES) && !(userRequest.getRequest().get(JsonKey.ROLES) instanceof List)) { throw new ProjectCommonException(ResponseCode.dataTypeError.getErrorCode(), ProjectUtil .formatMessage(ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), ERROR_CODE); } if (userRequest.getRequest().containsKey(JsonKey.LANGUAGE) && null != userRequest.getRequest().get(JsonKey.LANGUAGE) && !(userRequest.getRequest().get(JsonKey.LANGUAGE) instanceof List)) { throw new ProjectCommonException(ResponseCode.dataTypeError.getErrorCode(), ProjectUtil.formatMessage(ResponseCode.dataTypeError.getErrorMessage(), JsonKey.LANGUAGE, JsonKey.LIST), ERROR_CODE); } }
/** * Construct httpclient with SSL protocol * * @param clientConfiguration the client configuration * @return {@code CloseableHttpClient} * @throws Exception */ public static CloseableHttpClient getHttpClient(ClientConfiguration clientConfiguration) throws Exception { if (clientConfiguration == null) { clientConfiguration = new ClientConfiguration(); } SSLConnectionSocketFactory sslSocketFactory = createSslConnectionSocketFactory(clientConfiguration); HttpClientBuilder builder = HttpClients.custom(); // set proxy String proxyHost = clientConfiguration.getProxyHost(); int proxyPort = clientConfiguration.getProxyPort(); if (!StringUtils.isEmpty(proxyHost) && proxyPort > 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); builder.setProxy(proxy); String username = clientConfiguration.getProxyUserName(); String password = clientConfiguration.getProxyPassword(); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); AuthScope authscope = new AuthScope(proxy); Credentials credentials = new UsernamePasswordCredentials(username, password); credentialsProvider.setCredentials(authscope, credentials); builder.setDefaultCredentialsProvider(credentialsProvider); } } builder.setUserAgent(VersionUtil.getDefaultUserAgent()); CloseableHttpClient httpclient = builder.setSSLSocketFactory(sslSocketFactory).build(); return httpclient; }
@Before public void setUp() throws Exception { config = UroboroSQL.builder(DriverManager.getConnection("jdbc:h2:mem:SecretColumnSqlFilterTest")).build(); sqlFilterManager = config.getSqlFilterManager(); filter = new SecretColumnSqlFilter(); sqlFilterManager.addSqlFilter(filter); filter.setCryptColumnNames(Arrays.asList("PRODUCT_NAME")); // 下記コマンドでkeystoreファイル生成 // keytool -genseckey -keystore C:\keystore.jceks -storetype JCEKS // -alias testexample // -storepass password -keypass password -keyalg AES -keysize 128 filter.setKeyStoreFilePath("src/test/resources/data/expected/SecretColumnSqlFilter/keystore.jceks"); filter.setStorePassword("cGFzc3dvcmQ="); // 文字列「password」をBase64で暗号化 filter.setAlias("testexample"); filter.setCharset("UTF-8"); filter.setTransformationType("AES/ECB/PKCS5Padding"); sqlFilterManager.initialize(); try (SqlAgent agent = config.agent()) { String[] sqls = new String(Files.readAllBytes(Paths.get("src/test/resources/sql/ddl/create_tables.sql")), StandardCharsets.UTF_8).split(";"); for (String sql : sqls) { if (StringUtils.isNotBlank(sql)) { agent.updateWith(sql.trim()).count(); } } agent.commit(); } catch (UroborosqlSQLException ex) { ex.printStackTrace(); fail(ex.getMessage()); } }
private static boolean deleteCookie(Header header) { String[] kvs = header.getValue().split(";"); for (String s : kvs) { String[] kv = s.trim().split("="); if (StringUtils.equals(kv[0], "Max-Age") && kv.length == 2 && StringUtils.equals(kv[1], "0")) { return true; } } return false; }
/** * @desc 设置Scene的ContainLinkid字段 * * @param scene 场景实体 * @return Scene * @throws Exception */ private Scene updateSceneContainLinkid(Scene scene) throws Exception { if(null != scene){ String containLinkid = scene.getContainLinkid(); if(StringUtils.isNotBlank(containLinkid)){ scene.setContainLinkid(containLinkid.substring(1,containLinkid.length()-1)); return scene; } } return scene; }
@BeforeClass public static void setUpBeforeClass() throws Exception { datas = new HashMap<String, Object>(); datas.put("k1", "v1"); datas.put(nullKey, null); datas.put("k3", new Date()); longKey = StringUtils.repeat("keys", 1024); datas.put(longKey, StringUtils.repeat("valuevalue", 10240)); }
@Override public <P extends ParaObject> List<P> findNearby(String appid, String type, String query, int radius, double lat, double lng, Pager... pager) { if (StringUtils.isBlank(type) || StringUtils.isBlank(appid)) { return Collections.emptyList(); } if (StringUtils.isBlank(query)) { query = "*"; } // find nearby Address objects Pager page = getPager(pager); QueryBuilder qb1 = geoDistanceQuery("latlng").point(lat, lng).distance(radius, DistanceUnit.KILOMETERS); SearchHits hits1 = searchQueryRaw(appid, Utils.type(Address.class), qb1, page); page.setLastKey(null); // will cause problems if not cleared if (hits1 == null) { return Collections.emptyList(); } if (type.equals(Utils.type(Address.class))) { return searchQuery(appid, hits1); } // then find their parent objects String[] parentids = new String[hits1.getHits().length]; for (int i = 0; i < hits1.getHits().length; i++) { Object pid = hits1.getAt(i).getSourceAsMap().get(Config._PARENTID); if (pid != null) { parentids[i] = (String) pid; } } QueryBuilder qb2 = boolQuery().must(queryStringQuery(qs(query))).filter(idsQuery().addIds(parentids)); SearchHits hits2 = searchQueryRaw(appid, type, qb2, page); return searchQuery(appid, hits2); }
/** * Update the persisted access token and the authorization header if necessary * * @return The id of the currently linked user */ @SuppressWarnings("Duplicates") private synchronized String executeTokenPreflight() throws Exception { AuthToken token = authTokenDao.get(TokenGroup.INTEGRATIONS, "spotify"); if (StringUtils.isEmpty(token.getToken())) { throw new UnavailableException("The Spotify Api is not connected to an account"); } DateTime expiryTime = token.getExpiryTime(); DateTime now = DateTime.now(); if (expiryTime != null && now.isAfter(expiryTime)) { SpotifyOAuthFlowDirector director = new SpotifyOAuthFlowDirector(configService.getConsumerKey(), configService.getConsumerSecret(), webClient); boolean refreshSuccess = director.awaitRefreshedAccessToken(token.getRefreshToken()); if (refreshSuccess) { token.setToken(director.getAccessToken()); token.setIssuedAt(now); token.setTimeToLive(director.getTimeToLive()); authTokenDao.save(token); } else { throw new UnavailableException("The Spotify Api failed to refresh the access token"); } } else { headers.put(HttpHeader.AUTHORIZATION, OAUTH_HEADER_PREFIX + token.getToken()); } return token.getUserId(); }
/** * Find all pageable permitted entities. * @param pageable the page info * @param entityClass the entity class to get * @param privilegeKey the privilege key for permission lookup * @param <T> the type of entity * @return page of permitted entities */ public <T> Page<T> findAll(Pageable pageable, Class<T> entityClass, String privilegeKey) { String selectSql = String.format(SELECT_ALL_SQL, entityClass.getSimpleName()); String countSql = String.format(COUNT_ALL_SQL, entityClass.getSimpleName()); String permittedCondition = createPermissionCondition(privilegeKey); if (StringUtils.isNotBlank(permittedCondition)) { selectSql += WHERE_SQL + permittedCondition; countSql += WHERE_SQL + permittedCondition; } log.debug("Executing SQL '{}'", selectSql); return execute(createCountQuery(countSql), pageable, createSelectQuery(selectSql, pageable, entityClass)); }
/** * Put warn cookie if request parameter present. * * @param warnCookieGenerator the warn cookie generator * @param context the context */ public static void putWarnCookieIfRequestParameterPresent(final CookieGenerator warnCookieGenerator, final RequestContext context) { if (warnCookieGenerator != null) { LOGGER.debug("Evaluating request to determine if warning cookie should be generated"); final HttpServletResponse response = WebUtils.getHttpServletResponse(context); if (StringUtils.isNotBlank(context.getExternalContext().getRequestParameterMap().get("warn"))) { warnCookieGenerator.addCookie(response, "true"); } } else { LOGGER.debug("No warning cookie generator is defined"); } }
public static HttpEntity<Resource> buildAvatarHttpEntity(HttpServletRequest request, String fileName) throws IOException { // result headers HttpHeaders headers = new HttpHeaders(); // 'Content-Type' header String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE); if (StringUtils.isNotBlank(contentType)) { headers.setContentType(MediaType.valueOf(contentType)); } // 'Content-Length' header String headerContentLength = request.getHeader(HttpHeaders.CONTENT_LENGTH); long contentLength = -1L; if (StringUtils.isBlank(headerContentLength)) { try { contentLength = Long.parseLong(headerContentLength); } catch (NumberFormatException e) { contentLength = -1L; } } if (contentLength < 0) { contentLength = request.getContentLengthLong(); } if (contentLength >= 0) { headers.setContentLength(contentLength); } // File name header headers.set(XM_HEADER_CONTENT_NAME, fileName); Resource resource = new InputStreamResource(request.getInputStream()); return new HttpEntity<>(resource, headers); }
@OnMessage public void processMessage(String message) { JsonElement jelement = new JsonParser().parse(message); JsonObject jobject = jelement.getAsJsonObject(); if (jobject.has("id")) { if (StringUtils.equals(jobject.get("id").getAsString(), String.valueOf(MarketID.MARKET_SUBSCRIBE.ordinal())) && StringUtils.equals(jobject.get("status").getAsString(), "ok")) { LOGGER.info("subscribe huibi market scueess"); } } else if (jobject.has("ch")) { if (StringUtils.equals(jobject.get("ch").getAsString(), channel)) { JsonElement bids = jobject.getAsJsonArray("data").get(0); JsonElement asks = jobject.getAsJsonArray("data").get(1); } } }