Java Code Examples for org.elasticsearch.common.Strings#isNullOrEmpty()
The following examples show how to use
org.elasticsearch.common.Strings#isNullOrEmpty() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebConfig.java From openvsx with Eclipse Public License 2.0 | 6 votes |
@Override public void addCorsMappings(CorsRegistry registry) { if (!Strings.isNullOrEmpty(webuiUrl) && UrlUtil.isAbsolute(webuiUrl)) { // The Web UI is given with an absolute URL, so we need to enable CORS with credentials. var authorizedEndpoints = new String[] { "/user/**", "/logout", "/api/*/*/review/**" }; for (var endpoint : authorizedEndpoints) { registry.addMapping(endpoint) .allowedOrigins(webuiUrl) .allowCredentials(true); } } }
Example 2
Source File: RecommendedActionServiceImpl.java From pacbot with Apache License 2.0 | 6 votes |
@Override public List<Map<String, Object>> getRecommendedActions(String dataSource, String targetType, String ruleId) throws ServiceException { Map<String, Object> mustFilter = new HashMap<>(); if (!Strings.isNullOrEmpty(dataSource)) { mustFilter.put("dataSource.keyword", dataSource); } if (Strings.isNullOrEmpty(targetType)) { throw new ServiceException("target type cannot be empty"); } if (Strings.isNullOrEmpty(ruleId)) { throw new ServiceException("ruleId cannot be empty"); } mustFilter.put("actsOn.keyword", targetType); mustFilter.put("ruleId.keyword", ruleId); try{ return elasticSearchRepository.getSortedDataFromES(INDEX_RECOMMENDED_ACTIONS, TYPE_RECOMMENDED_ACTIONS, mustFilter, null, null, null, null,null); }catch(Exception e){ throw new ServiceException(e); } }
Example 3
Source File: LDAPAuthorizationBackend2.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
private String getRoleFromEntry(final Connection ldapConnection, final LdapName ldapName, final String role) { if (ldapName == null || Strings.isNullOrEmpty(role)) { return null; } if("dn".equalsIgnoreCase(role)) { return ldapName.toString(); } try { final LdapEntry roleEntry = LdapHelper.lookup(ldapConnection, ldapName.toString()); if(roleEntry != null) { final LdapAttribute roleAttribute = roleEntry.getAttribute(role); if(roleAttribute != null) { return Utils.getSingleStringValue(roleAttribute); } } } catch (LdapException e) { log.error("Unable to handle role {} because of ",ldapName, e.toString(), e); } return null; }
Example 4
Source File: Netty4CorsHandler.java From crate with Apache License 2.0 | 6 votes |
private boolean setOrigin(final HttpResponse response) { final String origin = request.headers().get(HttpHeaderNames.ORIGIN); if (!Strings.isNullOrEmpty(origin)) { if ("null".equals(origin) && config.isNullOriginAllowed()) { setAnyOrigin(response); return true; } if (config.isAnyOriginSupported()) { if (config.isCredentialsAllowed()) { echoRequestOrigin(response); setVaryHeader(response); } else { setAnyOrigin(response); } return true; } if (config.isOriginAllowed(origin)) { setOrigin(response, origin); setVaryHeader(response); return true; } } return false; }
Example 5
Source File: DataSourceTransformer.java From frostmourne with MIT License | 6 votes |
public static DataSourceContract model2Contract(DataSource dataSource) { DataSourceContract dataSourceContract = new DataSourceContract(); dataSourceContract.setDatasource_name(dataSource.getDatasource_name()); dataSourceContract.setDatasource_type(dataSource.getDatasource_type()); dataSourceContract.setId(dataSource.getId()); dataSourceContract.setService_address(dataSource.getService_address()); if(!Strings.isNullOrEmpty(dataSource.getProperties())) { dataSourceContract.setSettings(JacksonUtil.deSerialize(dataSource.getProperties(), new TypeReference<Map<String, String>>() { })); } else { dataSourceContract.setSettings(new HashMap<>()); } dataSourceContract.setCreate_at(dataSource.getCreate_at()); dataSourceContract.setCreator(dataSource.getCreator()); dataSourceContract.setModifier(dataSource.getModifier()); dataSourceContract.setModify_at(dataSource.getModify_at()); return dataSourceContract; }
Example 6
Source File: PrometheusFetcherProvider.java From skywalking with Apache License 2.0 | 6 votes |
private void generateTraffic(MeterEntity entity) { ServiceTraffic s = new ServiceTraffic(); s.setName(requireNonNull(entity.getServiceName())); s.setNodeType(NodeType.Normal); s.setTimeBucket(TimeBucket.getMinuteTimeBucket(System.currentTimeMillis())); MetricsStreamProcessor.getInstance().in(s); if (!Strings.isNullOrEmpty(entity.getInstanceName())) { InstanceTraffic instanceTraffic = new InstanceTraffic(); instanceTraffic.setName(entity.getInstanceName()); instanceTraffic.setServiceId(entity.serviceId()); instanceTraffic.setTimeBucket(TimeBucket.getMinuteTimeBucket(System.currentTimeMillis())); instanceTraffic.setLastPingTimestamp(System.currentTimeMillis()); MetricsStreamProcessor.getInstance().in(instanceTraffic); } if (!Strings.isNullOrEmpty(entity.getEndpointName())) { EndpointTraffic endpointTraffic = new EndpointTraffic(); endpointTraffic.setName(entity.getEndpointName()); endpointTraffic.setServiceId(entity.serviceId()); endpointTraffic.setTimeBucket(TimeBucket.getMinuteTimeBucket(System.currentTimeMillis())); MetricsStreamProcessor.getInstance().in(endpointTraffic); } }
Example 7
Source File: DataQueryController.java From frostmourne with MIT License | 6 votes |
@ResponseBody @RequestMapping(value = "/elasticsearchData", method = RequestMethod.GET) public Protocol<ElasticsearchDataResult> elasticsearchData(@RequestParam(value = "_appId", required = true) String _appId, @RequestParam(value = "dataName", required = true) String dataName, @RequestParam(value = "startTime", required = true) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ") Date startTime, @RequestParam(value = "endTime", required = true) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ") Date endTime, @RequestParam(value = "esQuery", required = false) String esQuery, @RequestParam(value = "scrollId", required = false) String scrollId, @RequestParam(value = "sortOrder", required = true) String sortOrder, @RequestParam(value = "intervalInSeconds", required = false) Integer intervalInSeconds) { if (Strings.isNullOrEmpty(esQuery)) { esQuery = "*"; } ElasticsearchDataResult elasticsearchDataResult = queryService.elasticsearchQuery(dataName, startTime, endTime, esQuery, scrollId, sortOrder, intervalInSeconds); return new Protocol<>(elasticsearchDataResult); }
Example 8
Source File: Netty4CorsHandler.java From crate with Apache License 2.0 | 6 votes |
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) { if (!config.isCorsSupportEnabled()) { return; } String originHeader = request.headers().get(HttpHeaderNames.ORIGIN); if (!Strings.isNullOrEmpty(originHeader)) { final String originHeaderVal; if (config.isAnyOriginSupported()) { originHeaderVal = ANY_ORIGIN; } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) { originHeaderVal = originHeader; } else { originHeaderVal = null; } if (originHeaderVal != null) { resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal); } } if (config.isCredentialsAllowed()) { resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } }
Example 9
Source File: URLTokenFilter.java From elasticsearch-analysis-url with Apache License 2.0 | 5 votes |
/** * Attempt to parse a malformed url string * @param urlString the malformed url string * @return the url part if it can be parsed, null otherwise * @deprecated parsing of malformed URLs is now delegated to {@link URLTokenizer} */ private String parseMalformed(String urlString) { if (parts != null && !parts.isEmpty()) { String ret; for (URLPart part : parts) { switch (part) { case PROTOCOL: ret = applyPattern(REGEX_PROTOCOL, urlString); break; case PORT: ret = applyPattern(REGEX_PORT, urlString); break; case QUERY: ret = applyPattern(REGEX_QUERY, urlString); break; case WHOLE: ret = urlString; break; default: ret = urlString; } if (!Strings.isNullOrEmpty(ret)) { return ret; } } } return urlString; }
Example 10
Source File: Netty4HttpServerTransport.java From crate with Apache License 2.0 | 5 votes |
static Netty4CorsConfig buildCorsConfig(Settings settings) { if (SETTING_CORS_ENABLED.get(settings) == false) { return Netty4CorsConfigBuilder.forOrigins().disable().build(); } String origin = SETTING_CORS_ALLOW_ORIGIN.get(settings); final Netty4CorsConfigBuilder builder; if (Strings.isNullOrEmpty(origin)) { builder = Netty4CorsConfigBuilder.forOrigins(); } else if (origin.equals(ANY_ORIGIN)) { builder = Netty4CorsConfigBuilder.forAnyOrigin(); } else { try { Pattern p = RestUtils.checkCorsSettingForRegex(origin); if (p == null) { builder = Netty4CorsConfigBuilder.forOrigins(RestUtils.corsSettingAsArray(origin)); } else { builder = Netty4CorsConfigBuilder.forPattern(p); } } catch (PatternSyntaxException e) { throw new SettingsException("Bad regex in [" + SETTING_CORS_ALLOW_ORIGIN.getKey() + "]: [" + origin + "]", e); } } if (SETTING_CORS_ALLOW_CREDENTIALS.get(settings)) { builder.allowCredentials(); } String[] strMethods = Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_METHODS.get(settings), ","); HttpMethod[] methods = Arrays.stream(strMethods) .map(HttpMethod::valueOf) .toArray(HttpMethod[]::new); return builder.allowedRequestMethods(methods) .maxAge(SETTING_CORS_MAX_AGE.get(settings)) .allowedRequestHeaders(Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_HEADERS.get(settings), ",")) .shortCircuit() .build(); }
Example 11
Source File: ConnectorManager.java From metacat with Apache License 2.0 | 5 votes |
private Map<String, CatalogHolder> getCatalogHoldersByDatabaseName(final String catalogName) { Map<String, CatalogHolder> result = catalogs.row(catalogName); if (result.isEmpty()) { final String proxyCatalogName = getConnectorNameFromCatalogName(catalogName); if (!Strings.isNullOrEmpty(proxyCatalogName)) { result = catalogs.row(proxyCatalogName); } } return result; }
Example 12
Source File: CorsHandler.java From Elasticsearch with Apache License 2.0 | 5 votes |
private static boolean isSameOrigin(final String origin, final String host) { if (Strings.isNullOrEmpty(host) == false) { // strip protocol from origin final String originDomain = SCHEME_PATTERN.matcher(origin).replaceFirst(""); if (host.equals(originDomain)) { return true; } } return false; }
Example 13
Source File: AlarmExecutor.java From frostmourne with MIT License | 5 votes |
private String completeAlertMessage() { String alertMessage = this.rule.alertMessage(alarmContract.getRuleContract(), this.alarmProcessLogger.getContext()); String timeString = DateTime.now().toString("yyyy-MM-dd hh:mm:ss"); String shortLink = generateShortLinkService.generate(alarmProcessLogger); String completeMessage = null; if(Strings.isNullOrEmpty(shortLink)) { completeMessage = String.format("[%s]\n%s", timeString, alertMessage); } else { completeMessage = String.format("[%s]\n%s\n\n详细请看: %s", timeString, alertMessage, shortLink); } return completeMessage; }
Example 14
Source File: PermissionInterceptor.java From frostmourne with MIT License | 5 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (!(handler instanceof HandlerMethod)) { return super.preHandle(request, response, handler); } boolean needLogin = true; HandlerMethod method = (HandlerMethod)handler; PermissionLimit permission = method.getMethodAnnotation(PermissionLimit.class); if (permission!=null) { needLogin = permission.limit(); } if (needLogin) { String token = request.getHeader("Frostmourne-Token"); if(Strings.isNullOrEmpty(token)) { notLoginResponse(response); return false; } Claims claims = null; try { claims = jwtToken.parseToken(token); } catch (Exception ex) { wrongTokenResponse(response); return false; } String json =(String) claims.get("userinfo"); UserInfo userInfo = JacksonUtil.deSerialize(json, UserInfo.class); request.setAttribute(AuthTool.USER_ATTR, userInfo); } return super.preHandle(request, response, handler); }
Example 15
Source File: PatchableResourceApiAction.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
private void handlePatch(RestChannel channel, final RestRequest request, final Client client) throws IOException { if (request.getXContentType() != XContentType.JSON) { badRequestResponse(channel, "PATCH accepts only application/json"); return; } String name = request.param("name"); SecurityDynamicConfiguration<?> existingConfiguration = load(getConfigName(), false); JsonNode jsonPatch; try { jsonPatch = DefaultObjectMapper.readTree(request.content().utf8ToString()); } catch (IOException e) { log.debug("Error while parsing JSON patch", e); badRequestResponse(channel, "Error in JSON patch: " + e.getMessage()); return; } JsonNode existingAsJsonNode = Utils.convertJsonToJackson(existingConfiguration, true); if (!(existingAsJsonNode instanceof ObjectNode)) { internalErrorResponse(channel, "Config " + getConfigName() + " is malformed"); return; } ObjectNode existingAsObjectNode = (ObjectNode) existingAsJsonNode; if (Strings.isNullOrEmpty(name)) { handleBulkPatch(channel, request, client, existingConfiguration, existingAsObjectNode, jsonPatch); } else { handleSinglePatch(channel, request, client, name, existingConfiguration, existingAsObjectNode, jsonPatch); } }
Example 16
Source File: LDAPAuthorizationBackend.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
private boolean isValidDn(final String dn) { if (Strings.isNullOrEmpty(dn)) { return false; } try { new LdapName(dn); } catch (final Exception e) { return false; } return true; }
Example 17
Source File: SearchConfig.java From openvsx with Eclipse Public License 2.0 | 5 votes |
@Override public RestHighLevelClient elasticsearchClient() { ClientConfiguration config; if (Strings.isNullOrEmpty(searchHost)) { config = ClientConfiguration.localhost(); } else { config = ClientConfiguration.create(searchHost); } return RestClients.create(config).rest(); }
Example 18
Source File: ProfileThreadSnapshotQuery.java From skywalking with Apache License 2.0 | 4 votes |
@Override public SegmentRecord getProfiledSegment(String segmentId) throws IOException { WhereQueryImpl query = select().column(SegmentRecord.SEGMENT_ID) .column(SegmentRecord.TRACE_ID) .column(SegmentRecord.SERVICE_ID) .column(SegmentRecord.ENDPOINT_NAME) .column(SegmentRecord.START_TIME) .column(SegmentRecord.END_TIME) .column(SegmentRecord.LATENCY) .column(SegmentRecord.IS_ERROR) .column(SegmentRecord.DATA_BINARY) .column(SegmentRecord.VERSION) .from(client.getDatabase(), SegmentRecord.INDEX_NAME) .where() .and(eq(SegmentRecord.SEGMENT_ID, segmentId)); List<QueryResult.Series> series = client.queryForSeries(query); if (log.isDebugEnabled()) { log.debug("SQL: {} result set: {}", query.getCommand(), series); } if (Objects.isNull(series) || series.isEmpty()) { return null; } List<Object> values = series.get(0).getValues().get(0); SegmentRecord segmentRecord = new SegmentRecord(); segmentRecord.setSegmentId((String) values.get(1)); segmentRecord.setTraceId((String) values.get(2)); segmentRecord.setServiceId((String) values.get(3)); segmentRecord.setEndpointName((String) values.get(4)); segmentRecord.setStartTime((long) values.get(5)); segmentRecord.setEndTime((long) values.get(6)); segmentRecord.setLatency((int) values.get(7)); segmentRecord.setIsError((int) values.get(8)); segmentRecord.setVersion((int) values.get(10)); String base64 = (String) values.get(9); if (!Strings.isNullOrEmpty(base64)) { segmentRecord.setDataBinary(Base64.getDecoder().decode(base64)); } return segmentRecord; }
Example 19
Source File: AlarmQuery.java From skywalking with Apache License 2.0 | 4 votes |
@Override public Alarms getAlarm(Integer scopeId, String keyword, int limit, int from, long startTB, long endTB) throws IOException { WhereQueryImpl<SelectQueryImpl> recallQuery = select() .function("top", AlarmRecord.START_TIME, limit + from).as(AlarmRecord.START_TIME) .column(AlarmRecord.ID0) .column(AlarmRecord.ALARM_MESSAGE) .column(AlarmRecord.SCOPE) .from(client.getDatabase(), AlarmRecord.INDEX_NAME) .where(); if (startTB > 0 && endTB > 0) { recallQuery.and(gte(InfluxClient.TIME, InfluxClient.timeInterval(startTB))) .and(lte(InfluxClient.TIME, InfluxClient.timeInterval(endTB))); } if (!Strings.isNullOrEmpty(keyword)) { recallQuery.and(contains(AlarmRecord.ALARM_MESSAGE, keyword.replaceAll("/", "\\\\/"))); } if (Objects.nonNull(scopeId)) { recallQuery.and(eq(AlarmRecord.SCOPE, scopeId)); } WhereQueryImpl<SelectQueryImpl> countQuery = select().count(AlarmRecord.ID0) .from(client.getDatabase(), AlarmRecord.INDEX_NAME) .where(); recallQuery.getClauses().forEach(clause -> { countQuery.where(clause); }); Query query = new Query(countQuery.getCommand() + recallQuery.getCommand()); List<QueryResult.Result> results = client.query(query); if (log.isDebugEnabled()) { log.debug("SQL: {} result set: {}", query.getCommand(), results); } if (results.size() != 2) { throw new IOException("Expecting to get 2 Results, but it is " + results.size()); } List<QueryResult.Series> series = results.get(1).getSeries(); if (series == null || series.isEmpty()) { return new Alarms(); } List<QueryResult.Series> counter = results.get(0).getSeries(); Alarms alarms = new Alarms(); alarms.setTotal(((Number) counter.get(0).getValues().get(0).get(1)).intValue()); series.get(0).getValues() .stream() // re-sort by self, because of the result order by time. .sorted((a, b) -> Long.compare((long) b.get(1), (long) a.get(1))) .skip(from) .forEach(values -> { final int sid = ((Number) values.get(4)).intValue(); Scope scope = Scope.Finder.valueOf(sid); AlarmMessage message = new AlarmMessage(); message.setStartTime((long) values.get(1)); message.setId((String) values.get(2)); message.setMessage((String) values.get(3)); message.setScope(scope); message.setScopeId(sid); alarms.getMsgs().add(message); }); return alarms; }
Example 20
Source File: HttpDownloadHelper.java From Elasticsearch with Apache License 2.0 | 4 votes |
private URLConnection openConnection(URL aSource) throws IOException { // set up the URL connection URLConnection connection = aSource.openConnection(); // modify the headers // NB: things like user authentication could go in here too. if (hasTimestamp) { connection.setIfModifiedSince(timestamp); } // in case the plugin manager is its own project, this can become an authenticator boolean isSecureProcotol = "https".equalsIgnoreCase(aSource.getProtocol()); boolean isAuthInfoSet = !Strings.isNullOrEmpty(aSource.getUserInfo()); if (isAuthInfoSet) { if (!isSecureProcotol) { throw new IOException("Basic auth is only supported for HTTPS!"); } String basicAuth = Base64.encodeBytes(aSource.getUserInfo().getBytes(StandardCharsets.UTF_8)); connection.setRequestProperty("Authorization", "Basic " + basicAuth); } if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setInstanceFollowRedirects(false); connection.setUseCaches(true); connection.setConnectTimeout(5000); } connection.setRequestProperty("ES-Version", Version.CURRENT.toString()); connection.setRequestProperty("ES-Build-Hash", Build.CURRENT.hashShort()); connection.setRequestProperty("User-Agent", "elasticsearch-plugin-manager"); // connect to the remote site (may take some time) connection.connect(); // First check on a 301 / 302 (moved) response (HTTP only) if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String newLocation = httpConnection.getHeaderField("Location"); URL newURL = new URL(newLocation); if (!redirectionAllowed(aSource, newURL)) { return null; } return openConnection(newURL); } // next test for a 304 result (HTTP only) long lastModified = httpConnection.getLastModified(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED || (lastModified != 0 && hasTimestamp && timestamp >= lastModified)) { // not modified so no file download. just return // instead and trace out something so the user // doesn't think that the download happened when it // didn't return null; } // test for 401 result (HTTP only) if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { String message = "HTTP Authorization failure"; throw new IOException(message); } } //REVISIT: at this point even non HTTP connections may //support the if-modified-since behaviour -we just check //the date of the content and skip the write if it is not //newer. Some protocols (FTP) don't include dates, of //course. return connection; }