http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/SessionMgr.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/SessionMgr.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/SessionMgr.java new file mode 100644 index 0000000..dbc14e1 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/SessionMgr.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.manager; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.ambari.logsearch.common.UserSessionInfo; +import org.apache.ambari.logsearch.security.context.LogsearchContextHolder; +import org.apache.ambari.logsearch.security.context.LogsearchSecurityContext; +import org.apache.ambari.logsearch.web.model.User; +import org.apache.log4j.Logger; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Component; + +@Component +public class SessionMgr { + + static final Logger logger = Logger.getLogger(SessionMgr.class); + + public SessionMgr() { + logger.debug("SessionManager created"); + } + + public UserSessionInfo processSuccessLogin(int authType, String userAgent) { + return processSuccessLogin(authType, userAgent, null); + } + + public UserSessionInfo processSuccessLogin(int authType, String userAgent, HttpServletRequest httpRequest) { + boolean newSessionCreation = true; + UserSessionInfo userSession = null; + LogsearchSecurityContext context = LogsearchContextHolder.getSecurityContext(); + if (context != null) { + userSession = context.getUserSession(); + } + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails(); + String currentLoginId = authentication.getName(); + if (userSession != null) { + if (validateUserSession(userSession, currentLoginId)) { + newSessionCreation = false; + } + } + // + if (newSessionCreation) { + // // Need to build the UserSession + userSession = new UserSessionInfo(); + User user = new User(); + user.setUsername(currentLoginId); + userSession.setUser(user); + if (details != null) { + logger.info("Login Success: loginId=" + currentLoginId + ", sessionId=" + details.getSessionId() + + ", requestId=" + details.getRemoteAddress()); + } else { + logger.info("Login Success: loginId=" + currentLoginId + ", msaSessionId=" + ", details is null"); + } + + } + + return userSession; + } + + protected boolean validateUserSession(UserSessionInfo userSession, String currentUsername) { + if (currentUsername.equalsIgnoreCase(userSession.getUser().getUsername())) { + return true; + } else { + logger.info("loginId doesn't match loginId from HTTPSession. Will create new session. loginId=" + + currentUsername + ", userSession=" + userSession, new Exception()); + return false; + } + } + +}
http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/UserConfigMgr.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/UserConfigMgr.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/UserConfigMgr.java new file mode 100644 index 0000000..d76a3e7 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/manager/UserConfigMgr.java @@ -0,0 +1,382 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.ambari.logsearch.manager; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.apache.ambari.logsearch.common.LogSearchConstants; +import org.apache.ambari.logsearch.common.MessageEnums; +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.dao.UserConfigSolrDao; +import org.apache.ambari.logsearch.query.QueryGeneration; +import org.apache.ambari.logsearch.util.ConfigUtil; +import org.apache.ambari.logsearch.util.RESTErrorUtil; +import org.apache.ambari.logsearch.util.SolrUtil; +import org.apache.ambari.logsearch.util.StringUtil; +import org.apache.ambari.logsearch.view.VLogfeederFilterWrapper; +import org.apache.ambari.logsearch.view.VUserConfig; +import org.apache.ambari.logsearch.view.VUserConfigList; +import org.apache.log4j.Logger; +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.client.solrj.SolrServerException; +import org.apache.solr.client.solrj.response.FacetField.Count; +import org.apache.solr.client.solrj.response.QueryResponse; +import org.apache.solr.common.SolrDocument; +import org.apache.solr.common.SolrDocumentList; +import org.apache.solr.common.SolrException; +import org.apache.solr.common.SolrInputDocument; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.google.gson.JsonParseException; + +@Component +public class UserConfigMgr extends MgrBase { + static Logger logger = Logger.getLogger(UserConfigMgr.class); + + @Autowired + UserConfigSolrDao userConfigSolrDao; + + @Autowired + SolrUtil solrUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + QueryGeneration queryGenerator; + + @Autowired + StringUtil stringUtil; + + public String saveUserConfig(VUserConfig vHistory) { + + SolrInputDocument solrInputDoc = new SolrInputDocument(); + if (!isValid(vHistory)) { + throw restErrorUtil.createRESTException("No FilterName Specified", + MessageEnums.INVALID_INPUT_DATA); + } + + if (isNotUnique(vHistory) && !vHistory.isOverwrite()) { + throw restErrorUtil.createRESTException( + "Name '" + vHistory.getFilterName() + "' already exists", + MessageEnums.INVALID_INPUT_DATA); + } + + solrInputDoc.addField(LogSearchConstants.ID, vHistory.getId()); + solrInputDoc.addField(LogSearchConstants.USER_NAME, + vHistory.getUserName()); + solrInputDoc.addField(LogSearchConstants.VALUES, vHistory.getValues()); + solrInputDoc.addField(LogSearchConstants.FILTER_NAME, + vHistory.getFilterName()); + solrInputDoc.addField(LogSearchConstants.ROW_TYPE, + vHistory.getRowType()); + List<String> shareNameList = vHistory.getShareNameList(); + if (shareNameList != null && !shareNameList.isEmpty()) + solrInputDoc.addField(LogSearchConstants.SHARE_NAME_LIST, shareNameList); + + try { + userConfigSolrDao.addDocs(solrInputDoc); + return convertObjToString(solrInputDoc); + } catch (SolrException | SolrServerException | IOException e) { + logger.error(e); + throw restErrorUtil.createRESTException(e.getMessage(), + MessageEnums.ERROR_SYSTEM); + } + } + + private boolean isNotUnique(VUserConfig vHistory) { + String filterName = vHistory.getFilterName(); + String rowType = vHistory.getRowType(); + + if (filterName != null && rowType != null) { + SolrQuery solrQuery = new SolrQuery(); + filterName = solrUtil.makeSearcableString(filterName); + solrQuery.setQuery(LogSearchConstants.COMPOSITE_KEY + ":" + + filterName + "-" + rowType); + queryGenerator.setRowCount(solrQuery, 0); + try { + Long numFound = userConfigSolrDao.process(solrQuery) + .getResults().getNumFound(); + if (numFound > 0) + return true; + } catch (SolrException | SolrServerException | IOException e) { + logger.error(e); + } + } + return false; + } + + private boolean isValid(VUserConfig vHistory) { + + return !stringUtil.isEmpty(vHistory.getFilterName()) + && !stringUtil.isEmpty(vHistory.getRowType()) + && !stringUtil.isEmpty(vHistory.getUserName()) + && !stringUtil.isEmpty(vHistory.getValues()); + } + + public void deleteUserConfig(String id) { + try { + userConfigSolrDao.removeDoc("id:" + id); + } catch (SolrException | SolrServerException | IOException e) { + logger.error(e); + throw restErrorUtil.createRESTException(e.getMessage(), + MessageEnums.ERROR_SYSTEM); + } + } + + @SuppressWarnings("unchecked") + public String getUserConfig(SearchCriteria searchCriteria) { + + SolrDocumentList solrList = new SolrDocumentList(); + VUserConfigList userConfigList = new VUserConfigList(); + + String rowType = (String) searchCriteria + .getParamValue(LogSearchConstants.ROW_TYPE); + if (stringUtil.isEmpty(rowType)) { + throw restErrorUtil.createRESTException( + "row type was not specified", + MessageEnums.INVALID_INPUT_DATA); + } + + String userName = (String) searchCriteria + .getParamValue(LogSearchConstants.USER_NAME); + if (stringUtil.isEmpty(userName)) { + throw restErrorUtil.createRESTException( + "user name was not specified", + MessageEnums.INVALID_INPUT_DATA); + } + String filterName = (String) searchCriteria + .getParamValue(LogSearchConstants.FILTER_NAME); + filterName = stringUtil.isEmpty(filterName) ? "*" : "*" + filterName + + "*"; + + try { + + SolrQuery userConfigQuery = new SolrQuery(); + queryGenerator.setMainQuery(userConfigQuery, null); + queryGenerator.setPagination(userConfigQuery, searchCriteria); + queryGenerator.setSingleIncludeFilter(userConfigQuery, + LogSearchConstants.ROW_TYPE, rowType); + queryGenerator.setSingleORFilter(userConfigQuery, + LogSearchConstants.USER_NAME, userName, + LogSearchConstants.SHARE_NAME_LIST, userName); + queryGenerator.setSingleIncludeFilter(userConfigQuery, + LogSearchConstants.FILTER_NAME, filterName); + + if (stringUtil.isEmpty(searchCriteria.getSortBy()) + || searchCriteria.getSortBy().equals("historyName")) + searchCriteria + .setSortBy(LogSearchConstants.FILTER_NAME); + if (stringUtil.isEmpty(searchCriteria.getSortType())) + searchCriteria.setSortType("" + SolrQuery.ORDER.asc); + + queryGenerator.setSingleSortOrder(userConfigQuery, searchCriteria); + solrList = userConfigSolrDao.process(userConfigQuery).getResults(); + + Collection<VUserConfig> configList = new ArrayList<VUserConfig>(); + + for (SolrDocument solrDoc : solrList) { + VUserConfig userConfig = new VUserConfig(); + userConfig.setFilterName("" + + solrDoc.get(LogSearchConstants.FILTER_NAME)); + userConfig.setId("" + solrDoc.get(LogSearchConstants.ID)); + userConfig.setValues("" + solrDoc.get(LogSearchConstants.VALUES)); + userConfig.setRowType("" + + solrDoc.get(LogSearchConstants.ROW_TYPE)); + try { + List<String> shareNameList = (List<String>) solrDoc + .get(LogSearchConstants.SHARE_NAME_LIST); + userConfig.setShareNameList(shareNameList); + } catch (Exception e) { + // do nothing + } + + userConfig.setUserName("" + + solrDoc.get(LogSearchConstants.USER_NAME)); + + configList.add(userConfig); + } + + userConfigList.setName("historyList"); + userConfigList.setUserConfigList(configList); + + userConfigList.setStartIndex(searchCriteria.getStartIndex()); + userConfigList.setPageSize((int) searchCriteria.getMaxRows()); + + userConfigList.setTotalCount((long) solrList.getNumFound()); + userConfigList + .setResultSize((int) (configList.size() - searchCriteria + .getStartIndex())); + } catch (SolrException | SolrServerException | IOException e) { + // do nothing + } + try { + return convertObjToString(userConfigList); + } catch (IOException e) { + return ""; + } + } + + public String updateUserConfig(VUserConfig vuserConfig) { + String id = "" + vuserConfig.getId(); + deleteUserConfig(id); + return saveUserConfig(vuserConfig); + } + + // ////////////////////////////LEVEL + // FILTER///////////////////////////////////// + + /** + * @return + */ + @SuppressWarnings("unchecked") + public String getUserFilter() { + String filterName = LogSearchConstants.LOGFEEDER_FILTER_NAME; + SolrQuery solrQuery = new SolrQuery(); + solrQuery.setQuery("*:*"); + String fq = LogSearchConstants.ROW_TYPE + ":" + filterName; + solrQuery.setFilterQueries(fq); + try { + QueryResponse response = userConfigSolrDao.process(solrQuery); + SolrDocumentList documentList = response.getResults(); + VLogfeederFilterWrapper logfeederFilterWrapper = null; + if (documentList != null && documentList.size() > 0) { + SolrDocument configDoc = documentList.get(0); + String configJson = jsonUtil.objToJson(configDoc); + HashMap<String, Object> configMap = (HashMap<String, Object>) jsonUtil.jsonToMapObject(configJson); + String json = (String) configMap.get(LogSearchConstants.VALUES); + logfeederFilterWrapper = (VLogfeederFilterWrapper) jsonUtil.jsonToObj(json, VLogfeederFilterWrapper.class); + logfeederFilterWrapper.setId("" + configDoc.get(LogSearchConstants.ID)); + + } else { + String hadoopServiceString = getHadoopServiceConfigJSON(); + try { + + JSONObject componentList = new JSONObject(); + JSONObject jsonValue = new JSONObject(); + + JSONObject hadoopServiceJsonObject = new JSONObject(hadoopServiceString) + .getJSONObject("service"); + Iterator<String> hadoopSerivceKeys = hadoopServiceJsonObject + .keys(); + while (hadoopSerivceKeys.hasNext()) { + String key = hadoopSerivceKeys.next(); + JSONArray componentArray = hadoopServiceJsonObject + .getJSONObject(key).getJSONArray("components"); + for (int i = 0; i < componentArray.length(); i++) { + JSONObject compJsonObject = (JSONObject) componentArray + .get(i); + String componentName = compJsonObject + .getString("name"); + JSONObject innerContent = new JSONObject(); + innerContent.put("label", componentName); + innerContent.put("hosts", new JSONArray()); + innerContent.put("defaultLevels", new JSONArray()); + componentList.put(componentName, innerContent); + } + } + jsonValue.put("filter", componentList); + return saveUserFiter(jsonValue.toString()); + + } catch (JsonParseException | JSONException je) { + logger.error(je); + logfeederFilterWrapper = new VLogfeederFilterWrapper(); + } + } + return convertObjToString(logfeederFilterWrapper); + } catch (SolrException | SolrServerException | IOException e) { + logger.error(e); + throw restErrorUtil.createRESTException(e.getMessage(), MessageEnums.ERROR_SYSTEM); + } + } + + /** + * Creating filter for logfeeder + * + * @param String + * @return + */ + public String saveUserFiter(String json) { + VLogfeederFilterWrapper logfeederFilterWrapper = (VLogfeederFilterWrapper) jsonUtil.jsonToObj(json, + VLogfeederFilterWrapper.class); + if (logfeederFilterWrapper == null) { + logger.error("filter json is not a valid :" + json); + throw restErrorUtil.createRESTException("Invalid filter json", MessageEnums.ERROR_SYSTEM); + } + String id = logfeederFilterWrapper.getId(); + if (!stringUtil.isEmpty(id)) { + deleteUserConfig(id); + } + String filterName = LogSearchConstants.LOGFEEDER_FILTER_NAME; + json = jsonUtil.objToJson(logfeederFilterWrapper); + SolrInputDocument conifgDocument = new SolrInputDocument(); + conifgDocument.addField(LogSearchConstants.ID, new Date().getTime()); + conifgDocument.addField(LogSearchConstants.ROW_TYPE, filterName); + conifgDocument.addField(LogSearchConstants.VALUES, json); + conifgDocument.addField(LogSearchConstants.USER_NAME, filterName); + conifgDocument.addField(LogSearchConstants.FILTER_NAME, filterName); + try { + userConfigSolrDao.addDocs(conifgDocument); + } catch (SolrException | SolrServerException | IOException e) { + logger.error(e); + throw restErrorUtil.createRESTException(e.getMessage(), MessageEnums.ERROR_SYSTEM); + } + return getUserFilter(); + } + + public String getAllUserName() { + List<String> userList = new ArrayList<String>(); + try { + SolrQuery userListQuery = new SolrQuery(); + queryGenerator.setMainQuery(userListQuery, null); + queryGenerator.setFacetField(userListQuery, + LogSearchConstants.USER_NAME); + QueryResponse queryResponse = userConfigSolrDao + .process(userListQuery); + if (queryResponse == null) + return convertObjToString(userList); + List<Count> counList = queryResponse.getFacetField( + LogSearchConstants.USER_NAME).getValues(); + for (Count cnt : counList) { + String userName = cnt.getName(); + userList.add(userName); + } + } catch (SolrException | SolrServerException | IOException e) { + // do nothing + } + + try { + return convertObjToString(userList); + } catch (IOException e) { + return ""; + } + } + +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGeneration.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGeneration.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGeneration.java new file mode 100644 index 0000000..38a31fb --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGeneration.java @@ -0,0 +1,442 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.ambari.logsearch.query; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.regex.Pattern; + +import org.apache.ambari.logsearch.common.LogSearchConstants; +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.util.BizUtil; +import org.apache.ambari.logsearch.util.ConfigUtil; +import org.apache.ambari.logsearch.util.DateUtil; +import org.apache.ambari.logsearch.util.JSONUtil; +import org.apache.ambari.logsearch.util.PropertiesUtil; +import org.apache.ambari.logsearch.util.RESTErrorUtil; +import org.apache.ambari.logsearch.util.SolrUtil; +import org.apache.ambari.logsearch.util.StringUtil; +import org.apache.log4j.Logger; +import org.apache.solr.client.solrj.SolrQuery; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class QueryGeneration extends QueryGenerationBase { + + static Logger logger = Logger.getLogger(QueryGeneration.class); + + @Autowired + SolrUtil solrUtil; + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + BizUtil bizUtil; + + @Autowired + DateUtil dateUtil; + + @Autowired + StringUtil stringUtil; + + @Autowired + JSONUtil jsonUtil; + + public SolrQuery commonFilterQuery(SearchCriteria searchCriteria) { + + SolrQuery solrQuery = new SolrQuery(); + + String jsonHCNames = (String) searchCriteria + .getParamValue("treeParams"); + String givenQuery = (String) searchCriteria.getParamValue("q"); + String level = (String) searchCriteria.getParamValue("level"); + + String startTime = (String) searchCriteria.getParamValue("from"); + String endTime = (String) searchCriteria.getParamValue("to"); + String iMessage = (String) searchCriteria.getParamValue("iMessage"); + String eMessage = (String) searchCriteria.getParamValue("eMessage"); + String gEmessage = (String) searchCriteria.getParamValue("gEMessage"); + String selectedComp = (String) searchCriteria + .getParamValue("selectComp"); + String bundleId = (String) searchCriteria + .getParamValue(LogSearchConstants.BUNDLE_ID); + String globalExcludeComp = (String) searchCriteria + .getParamValue("gMustNot"); + String unselectedComp = (String) searchCriteria + .getParamValue("unselectComp"); + String urlHostName = (String) searchCriteria.getParamValue("host_name"); + String urlComponents = (String) searchCriteria.getParamValue("components_name"); + + String advQuery = (String) searchCriteria.getParamValue("advanceSearch"); + if (!stringUtil.isEmpty(advQuery)) { + String advQueryParameters[] = advQuery.split(Pattern.quote("}{")); + SolrQuery advSolrQuery = new SolrQuery(); + + for (String queryParam : advQueryParameters) { + String params[] = queryParam.split(Pattern.quote("=")); + advSolrQuery.setParam(params[0], params[1]); + } + + // Building and adding levels to filters + setFilterClauseWithFieldName(advSolrQuery, level, + LogSearchConstants.SOLR_LEVEL, "", "OR"); + + // Adding Logtime to filters + setSingleRangeFilter(advSolrQuery, LogSearchConstants.LOGTIME, + startTime, endTime); + + // Building and adding exlcude components to filters + setFilterClauseWithFieldName(advSolrQuery, unselectedComp, + LogSearchConstants.SOLR_COMPONENT, + LogSearchConstants.MINUS_OPERATOR, "AND"); + + // Building and adding exlcude components to filters + setFilterClauseWithFieldName(advSolrQuery, selectedComp, + LogSearchConstants.SOLR_COMPONENT, + LogSearchConstants.NO_OPERATOR, "OR"); + + // Set Pagination + setPagination(advSolrQuery, searchCriteria); + + return advSolrQuery; + } + + setMainQuery(solrQuery, givenQuery); + + // Adding Logtime to filters + setSingleRangeFilter(solrQuery, LogSearchConstants.LOGTIME, startTime, + endTime); + + String mainFilterQuery = buildQueryFromJSONCompHost(jsonHCNames, selectedComp); + + if (mainFilterQuery != null && !mainFilterQuery.equals("")) + solrQuery.addFilterQuery(mainFilterQuery); + + // Building and adding levels to filters + setFilterClauseWithFieldName(solrQuery, level, LogSearchConstants.SOLR_LEVEL, "", "OR"); + + // Building and adding include string to filters + setFilterClauseForSolrSearchableString(solrQuery, iMessage, "OR", "", + LogSearchConstants.SOLR_LOG_MESSAGE); + + // Building and adding global exclude string to filters + setFilterClauseForSolrSearchableString(solrQuery, gEmessage, "AND", + LogSearchConstants.MINUS_OPERATOR, + LogSearchConstants.SOLR_LOG_MESSAGE); + + // Building and adding exclude string to filter + setFilterClauseForSolrSearchableString(solrQuery, eMessage, "AND", + LogSearchConstants.MINUS_OPERATOR, + LogSearchConstants.SOLR_LOG_MESSAGE); + + // Building and adding logfile to filters + applyLogFileFilter(solrQuery, searchCriteria); + + // Building and adding exclude components to filters + setFilterClauseWithFieldName(solrQuery, globalExcludeComp, + LogSearchConstants.SOLR_COMPONENT, + LogSearchConstants.MINUS_OPERATOR, "AND"); + + // Building and adding exlcude components to filters + setFilterClauseWithFieldName(solrQuery, unselectedComp, + LogSearchConstants.SOLR_COMPONENT, + LogSearchConstants.MINUS_OPERATOR, "AND"); + + //Building and addding host names given url + setFilterClauseWithFieldName(solrQuery, urlHostName, + LogSearchConstants.SOLR_HOST, + "", "OR"); + + //Building and addding component names given url + setFilterClauseWithFieldName(solrQuery, urlComponents, + LogSearchConstants.SOLR_COMPONENT, + "", "OR"); + + // Set Pagination + setPagination(solrQuery, searchCriteria); + + // SetSort type (by default Descending) + setSortOrderDefaultServiceLog(solrQuery, searchCriteria); + + // Set Bundle Id + setSingleIncludeFilter(solrQuery, LogSearchConstants.BUNDLE_ID, bundleId); + + this.setUserSpecificFilter(searchCriteria, solrQuery, + LogSearchConstants.INCLUDE_QUERY, + LogSearchConstants.INCLUDE_QUERY); + + this.setUserSpecificFilter(searchCriteria, solrQuery, + LogSearchConstants.EXCLUDE_QUERY, + LogSearchConstants.EXCLUDE_QUERY); + return solrQuery; + } + + public void applyLogFileFilter(SolrQuery solrQuery, + SearchCriteria searchCriteria) { + String hostLogFile = (String) searchCriteria + .getParamValue("hostLogFile"); + String compLogFile = (String) searchCriteria + .getParamValue("compLogFile"); + String givenQuery = (String) searchCriteria.getParamValue("q"); + String logfileQuery = ""; + if (hostLogFile != null && !hostLogFile.equals("") + && compLogFile != null && !compLogFile.equals("")) { + logfileQuery = "host:" + hostLogFile + " AND type:" + compLogFile; + if (givenQuery != null && !givenQuery.equals("")) + logfileQuery = "(" + givenQuery + ") AND (" + logfileQuery + + ")"; + solrQuery.addFilterQuery(logfileQuery); + } + } + + public void setUserSpecificFilter(SearchCriteria searchCriteria, + SolrQuery solrQuery, String paramName, String operation) { + + String queryString = (String) searchCriteria.getParamValue(paramName); + String columnQuery = (String) searchCriteria + .getParamValue(LogSearchConstants.COLUMN_QUERY); + if (!stringUtil.isEmpty(queryString) && "[]".equals(queryString)) + queryString = null; + if (!stringUtil.isEmpty(columnQuery) && stringUtil.isEmpty(queryString) + && !paramName.equals(LogSearchConstants.EXCLUDE_QUERY)) + queryString = columnQuery; + List<String> conditionQuries = new ArrayList<String>(); + List<String> referalConditionQuries = new ArrayList<String>(); + List<String> elments = new ArrayList<String>(); + if (!stringUtil.isEmpty(queryString)) { + List<HashMap<String, Object>> queryList = jsonUtil + .jsonToMapObjectList(queryString); + if (!stringUtil.isEmpty(columnQuery) + && !columnQuery.equals(queryString) && !paramName.equals(LogSearchConstants.EXCLUDE_QUERY)) { + List<HashMap<String, Object>> columnQueryList = jsonUtil + .jsonToMapObjectList(columnQuery); + queryList.addAll(columnQueryList); + } + + for (HashMap<String, Object> columnListMap : queryList) { + String orQuery = ""; + String field = ""; + for (String key : columnListMap.keySet()) { + String originalKey = getOriginalKey(key); + String value = getOriginalValue(originalKey, "" + + columnListMap.get(key)); + orQuery = originalKey + ":" + + putWildCardByType(value, originalKey); + + boolean isSame = false; + for (String temp : elments) { + if (key.equals(temp)) + isSame = true; + } + if (isSame + && !operation + .equals(LogSearchConstants.EXCLUDE_QUERY)) { + for (String tempCondition : conditionQuries) { + if (tempCondition.contains(originalKey)) { + String newCondtion = tempCondition + " OR " + + orQuery; + referalConditionQuries.remove(tempCondition); + referalConditionQuries.add(newCondtion); + } + } + conditionQuries.removeAll(conditionQuries); + conditionQuries.addAll(referalConditionQuries); + } else { + conditionQuries.add(orQuery); + referalConditionQuries.add(orQuery); + } + + field = key; + elments.add(field); + } + + } + } + if (!referalConditionQuries.isEmpty()) { + if (operation.equals(LogSearchConstants.INCLUDE_QUERY) + || operation.equals(LogSearchConstants.COLUMN_QUERY)) { + for (String filter : referalConditionQuries) + solrQuery.addFilterQuery(filter); + } else if (operation.equals(LogSearchConstants.EXCLUDE_QUERY)) { + + for (String filter : referalConditionQuries) { + filter = "-" + filter; + solrQuery.addFilterQuery(filter); + } + } + } + } + + public SolrQuery commonAuditFilterQuery(SearchCriteria searchCriteria) { + + SolrQuery solrQuery = new SolrQuery(); + solrQuery.setQuery("*:*"); + + String startTime = (String) searchCriteria.getParamValue("startTime"); + String endTime = (String) searchCriteria.getParamValue("endTime"); + String selectedComp = (String) searchCriteria + .getParamValue("includeString"); + + this.setFilterClauseWithFieldName(solrQuery, selectedComp, + LogSearchConstants.AUDIT_COMPONENT, + LogSearchConstants.NO_OPERATOR, "OR"); + + String globalExcludeComp = (String) searchCriteria + .getParamValue("gMustNot"); + + this.setUserSpecificFilter(searchCriteria, solrQuery, + LogSearchConstants.INCLUDE_QUERY, + LogSearchConstants.INCLUDE_QUERY); + + this.setUserSpecificFilter(searchCriteria, solrQuery, + LogSearchConstants.EXCLUDE_QUERY, + LogSearchConstants.EXCLUDE_QUERY); + + String unselectedComp = (String) searchCriteria + .getParamValue("unselectComp"); + + this.setFilterClauseWithFieldName(solrQuery, globalExcludeComp, + LogSearchConstants.AUDIT_COMPONENT, + LogSearchConstants.MINUS_OPERATOR, "AND"); + + // Building and adding exlcude components to filters + this.setFilterClauseWithFieldName(solrQuery, unselectedComp, + LogSearchConstants.AUDIT_COMPONENT, + LogSearchConstants.MINUS_OPERATOR, "AND"); + + // Adding Logtime to filters + this.setSingleRangeFilter(solrQuery, LogSearchConstants.AUDIT_EVTTIME, + startTime, endTime); + + this.setPagination(solrQuery, searchCriteria); + try { + if (searchCriteria.getSortBy().isEmpty()) { + searchCriteria.setSortBy(LogSearchConstants.AUDIT_EVTTIME); + searchCriteria.setSortType(SolrQuery.ORDER.desc.toString()); + } + } catch (Exception e) { + searchCriteria.setSortBy(LogSearchConstants.AUDIT_EVTTIME); + searchCriteria.setSortType(SolrQuery.ORDER.desc.toString()); + } + + this.setSortOrderDefaultServiceLog(solrQuery, searchCriteria); + return solrQuery; + } + + private String putWildCardByType(String str, String key) { + + String auditSuffix = PropertiesUtil + .getProperty("auditlog.solr.core.logs"); + String serviceLogs = PropertiesUtil.getProperty("solr.core.logs"); + + String type = ConfigUtil.schemaFieldsName.get(key + auditSuffix); + if (type == null) + type = ConfigUtil.schemaFieldsName.get(key + serviceLogs); + if (type == null) + return "*" + str + "*"; + if ("text_std_token_lower_case".equalsIgnoreCase(type)) + return giveSplittedStringQuery(str); + if ("key_lower_case".equalsIgnoreCase(type) + || "string".equalsIgnoreCase(type)) + //return solrUtil.makeSolrSearchString(str); + return solrUtil.makeSolrSearchStringWithoutAsterisk(str); + if ("ip_address".equalsIgnoreCase(type)) + return str; + return putEscapeCharacterForNumber(str); + } + + private String giveSplittedStringQuery(String str) { + try { + String splittedString[] = str + .split("/|-|@|&|^|%|$|#|!|~|:|;|\\*|\\+"); + String newStr = "("; + int cnt = 0; + for (String normalString : splittedString) { + cnt++; + if (!normalString.isEmpty()) { + newStr += "*" + normalString + "*"; + } + if (!normalString.isEmpty() && cnt < splittedString.length) + newStr += " AND "; + } + newStr += ")"; + return newStr; + } catch (Exception e) { + return "*" + str + "*"; + } + } + + private String putEscapeCharacterForNumber(String str) { + String escapeCharSting = "" + returnDefaultIfValueNotNumber(str); + escapeCharSting = str.replace("-", "\\-"); + return escapeCharSting; + } + + private String returnDefaultIfValueNotNumber(String str) { + try { + return "" + Integer.parseInt(str); + } catch (Exception e) { + return "0"; + } + } + + private String getOriginalValue(String name, String value) { + String solrValue = PropertiesUtil.getProperty(name); + + try { + String propertyFieldMappings[] = solrValue.split(","); + HashMap<String, String> propertyFieldValue = new HashMap<String, String>(); + for (String temp : propertyFieldMappings) { + String arrayValue[] = temp.split(":"); + propertyFieldValue.put(arrayValue[0].toLowerCase(Locale.ENGLISH), + arrayValue[1].toLowerCase(Locale.ENGLISH)); + } + String originalValue = propertyFieldValue.get(value.toLowerCase(Locale.ENGLISH)); + if (originalValue != null && !originalValue.isEmpty()) + return originalValue; + + } catch (Exception e) { + // do nothing + } + return value; + + } + + private String getOriginalKey(String key) { + String originalServiceKey = ConfigUtil.serviceLogsColumnMapping.get(key + + LogSearchConstants.UI_SUFFIX); + String originalAuditKey = ConfigUtil.auditLogsColumnMapping.get(key + + LogSearchConstants.UI_SUFFIX); + if (originalAuditKey != null && originalServiceKey == null) { + return originalAuditKey; + } + if (originalServiceKey != null && originalAuditKey == null) { + return originalServiceKey; + } + if (originalAuditKey != null && originalServiceKey != null) { + return originalServiceKey; + } + return key; + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGenerationBase.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGenerationBase.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGenerationBase.java new file mode 100644 index 0000000..e357d02 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/query/QueryGenerationBase.java @@ -0,0 +1,389 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.ambari.logsearch.query; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.ambari.logsearch.common.LogSearchConstants; +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.util.JSONUtil; +import org.apache.ambari.logsearch.util.QueryBase; +import org.apache.ambari.logsearch.util.SolrUtil; +import org.apache.ambari.logsearch.util.StringUtil; +import org.apache.log4j.Logger; +import org.apache.solr.client.solrj.SolrQuery; +import org.apache.solr.client.solrj.SolrQuery.ORDER; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class QueryGenerationBase extends QueryBase { + + static Logger logger = Logger.getLogger(QueryGenerationBase.class); + + @Autowired + SolrUtil solrUtil; + + @Autowired + StringUtil stringUtil; + + @Autowired + JSONUtil jsonUtil; + + // SetMethods to apply to the query + public void setFilterClauseForSolrSearchableString(SolrQuery solrQuery, + String commaSepratedString, String booleanOperator, String opr, + String messageField) { + String operator = opr; + String filterQuery = ""; + if (commaSepratedString != null && !commaSepratedString.isEmpty()) { + + String queryMsg = ""; + operator = operator == null ? "" : operator; + String[] msgList = commaSepratedString + .split(LogSearchConstants.I_E_SEPRATOR); + int count = 0; + for (String temp : msgList) { + count += 1; + + queryMsg = queryMsg + " " + operator + messageField + ":" + + solrUtil.makeSolrSearchString(temp); + if (msgList.length > count) + queryMsg = queryMsg + " " + booleanOperator + " "; + } + filterQuery = queryMsg; + solrQuery.addFilterQuery(filterQuery); + logger.debug("Filter added :- " + filterQuery); + } + } + + public void setFilterClauseWithFieldName(SolrQuery solrQuery, + String commaSepratedString, String field, String operator, + String condition) { + if (commaSepratedString != null && !commaSepratedString.isEmpty()) { + String[] arrayOfSepratedString = commaSepratedString.split(","); + String filterQuery; + if ("OR".equals(condition)) + filterQuery = solrUtil.orList(operator + field, + arrayOfSepratedString, ""); + else + filterQuery = solrUtil.andList(operator + field, + arrayOfSepratedString, ""); + solrQuery.addFilterQuery(filterQuery); + logger.debug("Filter added :- " + filterQuery); + } + } + + public void setSortOrderDefaultServiceLog(SolrQuery solrQuery, + SearchCriteria searchCriteria) { + List<SolrQuery.SortClause> defaultSort = new ArrayList<SolrQuery.SortClause>(); + if (searchCriteria.getSortBy() != null + && (!searchCriteria.getSortBy().isEmpty())) { + ORDER order = SolrQuery.ORDER.asc; + if (searchCriteria.getSortType() != null + && (!searchCriteria.getSortType().isEmpty()) + && !searchCriteria.getSortType().equalsIgnoreCase( + order.toString())) { + order = SolrQuery.ORDER.desc; + } + SolrQuery.SortClause logtimeSortClause = SolrQuery.SortClause + .create(searchCriteria.getSortBy(), order); + defaultSort.add(logtimeSortClause); + } else { + // by default sorting by logtime and sequence number in + // Descending order + SolrQuery.SortClause logtimeSortClause = SolrQuery.SortClause + .create(LogSearchConstants.LOGTIME, SolrQuery.ORDER.desc); + + defaultSort.add(logtimeSortClause); + + } + SolrQuery.SortClause sequenceNumberSortClause = SolrQuery.SortClause + .create(LogSearchConstants.SEQUNCE_ID, SolrQuery.ORDER.desc); + defaultSort.add(sequenceNumberSortClause); + solrQuery.setSorts(defaultSort); + logger.debug("Sort Order :-" + defaultSort); + } + + public void setFilterFacetSort(SolrQuery solrQuery, + SearchCriteria searchCriteria) { + if (searchCriteria.getSortBy() != null + && (!searchCriteria.getSortBy().isEmpty())) { + solrQuery.setFacetSort(searchCriteria.getSortBy()); + logger.info("Sorted By :- " + searchCriteria.getSortBy()); + } + } + + public void setSingleSortOrder(SolrQuery solrQuery, + SearchCriteria searchCriteria) { + List<SolrQuery.SortClause> sort = new ArrayList<SolrQuery.SortClause>(); + if (searchCriteria.getSortBy() != null + && (!searchCriteria.getSortBy().isEmpty())) { + ORDER order = SolrQuery.ORDER.asc; + if (searchCriteria.getSortType() != null + && (!searchCriteria.getSortType().isEmpty()) + && !searchCriteria.getSortType().equalsIgnoreCase( + order.toString())) { + order = SolrQuery.ORDER.desc; + } + SolrQuery.SortClause sortOrder = SolrQuery.SortClause.create( + searchCriteria.getSortBy(), order); + sort.add(sortOrder); + solrQuery.setSorts(sort); + logger.debug("Sort Order :-" + sort); + } + } + + // Search Criteria has parameter "sort" from it can get list of Sort Order + // Example of list can be [logtime desc,seq_num desc] + @SuppressWarnings("unchecked") + public void setMultipleSortOrder(SolrQuery solrQuery, + SearchCriteria searchCriteria) { + List<SolrQuery.SortClause> sort = new ArrayList<SolrQuery.SortClause>(); + List<String> sortList = (List<String>) searchCriteria + .getParamValue("sort"); + for (String sortOrder : sortList) { + String sortByAndOrder[] = sortOrder.split(" "); + ORDER order = sortByAndOrder[1].contains("asc") ? SolrQuery.ORDER.asc + : SolrQuery.ORDER.desc; + SolrQuery.SortClause sortOrder2 = SolrQuery.SortClause.create( + sortByAndOrder[0], order); + sort.add(sortOrder2); + logger.debug("Sort Order :-" + sort); + } + solrQuery.setSorts(sort); + } + + public void setSingleIncludeFilter(SolrQuery solrQuery, String filterType, + String filterValue) { + if (filterType != null && !filterType.isEmpty() && filterValue != null + && !filterValue.isEmpty()) { + String filterQuery = buildFilterQuery(filterType, filterValue); + solrQuery.addFilterQuery(filterQuery); + logger.debug("Filter added :- " + filterQuery); + } + } + + public void setSingleExcludeFilter(SolrQuery solrQuery, String filterType, + String filterValue) { + if (filterType != null && !filterType.isEmpty() && filterValue != null + && !filterValue.isEmpty()) { + String filterQuery = "-" + + buildFilterQuery(filterType, filterValue); + solrQuery.addFilterQuery(filterQuery); + logger.debug("Filter added :- " + filterQuery); + } + } + + public void setSingleRangeFilter(SolrQuery solrQuery, String filterType, + String filterFromValue, String filterToValue) { + if (filterType != null && !filterType.isEmpty() + && filterFromValue != null && !filterFromValue.isEmpty() + && filterToValue != null && !filterToValue.isEmpty()) { + String filterQuery = buildInclusiveRangeFilterQuery(filterType, + filterFromValue, filterToValue); + solrQuery.addFilterQuery(filterQuery); + logger.debug("Filter added :- " + filterQuery); + } + } + + public void setPagination(SolrQuery solrQuery, SearchCriteria searchCriteria) { + Integer startIndex = null; + Integer maxRows = null; + try { + startIndex = (Integer) searchCriteria.getStartIndex(); + setStart(solrQuery, startIndex); + } catch (ClassCastException e) { + setStart(solrQuery, 0); + } + try { + maxRows = (Integer) searchCriteria.getMaxRows(); + setRowCount(solrQuery, maxRows); + } catch (ClassCastException e) { + setRowCount(solrQuery, 10); + } + + if (startIndex != null && maxRows != null) + logger.info("Pagination was set from " + startIndex.intValue() + + " to " + maxRows.intValue()); + } + + public void setSingleORFilter(SolrQuery solrQuery, String filterName1, String value1, String filterName2, String value2) { + String filterQuery = filterName1 + ":" + value1 + " OR " + filterName2 + ":" + value2; + solrQuery.setFilterQueries(filterQuery); + } + + // BuildMethods to prepare a particular format as required for solr + public String buildInclusiveRangeFilterQuery(String filterType, + String filterFromValue, String filterToValue) { + String filterQuery = filterType + ":[" + filterFromValue + " TO " + + filterToValue + "]"; + logger.info("Build Filter was :- " + filterQuery); + return filterQuery; + } + + public String buildExclusiveRangeFilterQuery(String filterType, + String filterFromValue, String filterToValue) { + String filterQuery = filterType + ":{" + filterFromValue + " TO " + + filterToValue + "}"; + logger.info("Build Filter was :- " + filterQuery); + return filterQuery; + } + + public String buildFilterQuery(String filterType, String filterValue) { + String filterQuery = filterType + ":" + filterValue; + logger.info("Build Filter Query was :- " + filterQuery); + return filterQuery; + } + + public String buildQueryFromJSONCompHost(String jsonHCNames, + String selectedComponent) { + String queryHostComponent = ""; + // Building and adding exclude string to filters + String selectedCompQuery = ""; + + if (selectedComponent != null && !selectedComponent.equals("")) { + String[] selectedComponents = selectedComponent.split(","); + selectedCompQuery = solrUtil.orList(LogSearchConstants.SOLR_COMPONENT, selectedComponents); + + } + + // Building Query of Host and Components from given json + if (jsonHCNames != null && !jsonHCNames.equals("") + && !jsonHCNames.equals("[]")) { + + try { + JSONArray jarray = new JSONArray(jsonHCNames); + int flagHost = 0; + int flagComp; + int count; + for (int i = 0; i < jarray.length(); i++) { + if (flagHost == 1) + queryHostComponent = queryHostComponent + " OR "; + JSONObject jsonObject = jarray.getJSONObject(i); + String host = jsonObject.getString("h"); + queryHostComponent = queryHostComponent + "( host:" + host; + List<String> components = JSONUtil.JSONToList(jsonObject + .getJSONArray("c")); + if (components.isEmpty()) + queryHostComponent = queryHostComponent + " AND "; + + flagComp = 0; + count = 0; + for (String comp : components) { + if (flagComp == 0) + queryHostComponent = queryHostComponent + " ( "; + count += 1; + queryHostComponent = queryHostComponent + " " + + " type:" + comp; + if (components.size() <= count) + queryHostComponent = queryHostComponent + " ) "; + else + queryHostComponent = queryHostComponent + " OR "; + flagComp = 1; + } + queryHostComponent = queryHostComponent + " ) "; + flagHost = 1; + } + } catch (JSONException e) { + logger.error(e); + } + } + if (selectedCompQuery != null && !selectedCompQuery.equals("")) { + if (queryHostComponent == null || queryHostComponent.equals("")) + queryHostComponent = selectedCompQuery; + else + queryHostComponent = queryHostComponent + " OR " + + selectedCompQuery; + } + return queryHostComponent; + } + + // JSON BuildMethods + + /** + * @param function , xAxisField + * @return jsonString + */ + public String buildJSONFacetAggregatedFuncitonQuery(String function, + String xAxisField) { + return "{x:'" + function + "(" + xAxisField + ")'}"; + } + + /** + * @param fieldName , fieldTime, from, to, unit + * @return jsonString + * @hierarchy Term, Time Range + */ + public String buildJSONFacetTermTimeRangeQuery(String fieldName, + String fieldTime, String from, String to, String unit) { + String query = "{"; + query += "x" + ":{type:terms,field:" + fieldName + + ",facet:{y:{type:range,field:" + fieldTime + ",start:\"" + + from + "\",end:\"" + to + "\",gap:\"" + unit + "\"}}}"; + query += "}"; + logger.info("Build JSONQuery is :- " + query); + return query; + } + + /** + * @param stackField , xAxisField + * @return jsonString + * @hierarchy Term, Range + */ + public String buildJsonFacetTermsRangeQuery(String stackField, + String xAxisField) { + String jsonQuery = "{ " + stackField + ": { type: terms,field:" + + stackField + "," + "facet: { x: { type: terms, field:" + + xAxisField + ",mincount:0,sort:{index:asc}}}}}"; + logger.info("Build JSONQuery is :- " + jsonQuery); + return jsonQuery; + } + + /** + * @param stackField , xAxisField, function + * @return + * @hierarchy Term, Range + */ + public String buidlJSONFacetRangeQueryForNumber(String stackField, + String xAxisField, String function) { + String jsonQuery = "{ " + stackField + ": { type: terms,field:" + + stackField + "," + "facet: { x:'" + function + "(" + + xAxisField + ")'}}}}"; + logger.info("Build JSONQuery is :- " + jsonQuery); + return jsonQuery; + } + + /** + * @param stackField , xAxisField, function + * @return + * @hierarchy Query, T + */ + public String buidlJSONFacetRangeQueryForSuggestion( + String originalFieldName, String valueToSuggest) { + String jsonQuery = "{y:{type:query,query:\"" + originalFieldName + ":" + + valueToSuggest + "\",facet:{x:{type:terms,field:" + + originalFieldName + "}}}}"; + logger.info("Build JSONQuery is :- " + jsonQuery); + return jsonQuery; + } +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/AuditREST.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/AuditREST.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/AuditREST.java new file mode 100644 index 0000000..6e47d34 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/AuditREST.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.ambari.logsearch.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; + +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.manager.AuditMgr; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.log4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Path("audit") +@Component +@Scope("request") +public class AuditREST { + + @Autowired + AuditMgr auditMgr; + + @GET + @Path("/getAuditSchemaFieldsName") + @Produces({"application/json"}) + public String getSolrFieldList(@Context HttpServletRequest request) { + return auditMgr.getAuditLogsSchemaFieldsName(); + } + + @GET + @Path("/getAuditLogs") + @Produces({"application/json"}) + public String getAuditLogs(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + return auditMgr.getLogs(searchCriteria); + } + + @GET + @Path("/getAuditComponents") + @Produces({"application/json"}) + public String getAuditComponents(@Context HttpServletRequest request) { + + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam("q", request.getParameter("q")); + return auditMgr.getAuditComponents(searchCriteria); + } + + @GET + @Path("/getAuditLineGraphData") + @Produces({"application/json"}) + public String getAuditLineGraphData(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + searchCriteria.addParam("unit", request.getParameter("unit")); + return auditMgr.getAuditLineGraphData(searchCriteria); + } + + @GET + @Path("/getTopAuditUsers") + @Produces({"application/json"}) + public String getTopAuditUsers(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + searchCriteria.addParam("field", request.getParameter("field")); + return auditMgr.topTenUsers(searchCriteria); + } + + @GET + @Path("/getTopAuditResources") + @Produces({"application/json"}) + public String getTopAuditResources(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + searchCriteria.addParam("field", request.getParameter("field")); + //return auditMgr.getTopAuditFieldCount(searchCriteria); + return auditMgr.topTenResources(searchCriteria); + + + } + + @GET + @Path("/getTopAuditComponents") + @Produces({"application/json"}) + public String getTopAuditComponents(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + searchCriteria.addParam("field", request.getParameter("field")); + searchCriteria.addParam("unit", request.getParameter("unit")); + return auditMgr.getTopAuditFieldCount(searchCriteria); + } + + @GET + @Path("/getLiveLogsCount") + @Produces({"application/json"}) + public String getLiveLogsCount() { + return auditMgr.getLiveLogCounts(); + } + + @GET + @Path("/getRequestUserLineGraph") + @Produces({"application/json"}) + public String getRequestUserLineGraph(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + searchCriteria.addParam("field", request.getParameter("field")); + searchCriteria.addParam("unit", request.getParameter("unit")); + return auditMgr.getRequestUserLineGraph(searchCriteria); + } + + @GET + @Path("/getAnyGraphData") + @Produces({"application/json"}) + public String getAnyGraphData(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam("xAxis", request.getParameter("xAxis")); + searchCriteria.addParam("yAxis", request.getParameter("yAxis")); + searchCriteria.addParam("stackBy", request.getParameter("stackBy")); + searchCriteria.addParam("from", request.getParameter("from")); + searchCriteria.addParam("to", request.getParameter("to")); + searchCriteria.addParam("unit", request.getParameter("unit")); + return auditMgr.getAnyGraphData(searchCriteria); + } + + @GET + @Path("/exportUserTableToTextFile") + @Produces({"application/json"}) + public Response exportUserTableToTextFile(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + searchCriteria.addParam("field", request.getParameter("field")); + searchCriteria.addParam("format", request.getParameter("format")); + return auditMgr.exportUserTableToTextFile(searchCriteria); + } + + @GET + @Path("/getServiceLoad") + @Produces({"application/json"}) + public String getServiceLoad(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredAuditLogsParams(request); + return auditMgr.getServiceLoad(searchCriteria); + } + +} + \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/DashboardREST.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/DashboardREST.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/DashboardREST.java new file mode 100644 index 0000000..5f56ccb --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/DashboardREST.java @@ -0,0 +1,309 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; + +import org.apache.ambari.logsearch.common.LogSearchConstants; +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.manager.LogsMgr; +import org.apache.ambari.logsearch.util.RESTErrorUtil; +import org.apache.ambari.logsearch.view.VCountList; +import org.apache.ambari.logsearch.view.VNameValueList; +import org.apache.ambari.logsearch.view.VNodeList; +import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Path("dashboard") +@Component +@Scope("request") +public class DashboardREST { + + @Autowired + LogsMgr logMgr; + + @Autowired + RESTErrorUtil restErrorUtil; + + @GET + @Path("/solr/logs_search") + @Produces({"application/json"}) + public String searchSolrData(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + searchCriteria.addParam("keyword", StringEscapeUtils.unescapeXml(request.getParameter("find"))); + searchCriteria.addParam("sourceLogId", request.getParameter("sourceLogId")); + searchCriteria.addParam("keywordType", + request.getParameter("keywordType")); + searchCriteria.addParam("token", + request.getParameter("token")); + return logMgr.searchLogs(searchCriteria); + } + + @GET + @Path("/hosts") + @Produces({"application/json"}) + public String getHosts(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam("q", request.getParameter("q")); + return logMgr.getHosts(searchCriteria); + } + + @GET + @Path("/components") + @Produces({"application/json"}) + public String getComponents(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam("q", request.getParameter("q")); + return logMgr.getComponents(searchCriteria); + } + + @GET + @Path("/aggregatedData") + @Produces({"application/json"}) + public String getAggregatedInfo(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.addRequiredServiceLogsParams(request); + return logMgr.getAggregatedInfo(searchCriteria); + } + + @GET + @Path("/levels_count") + @Produces({"application/json"}) + public VCountList getLogLevelsCount(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.addParam("q", request.getParameter("q")); + searchCriteria + .addParam("startDate", request.getParameter("start_time")); + searchCriteria.addParam("endDate", request.getParameter("end_time")); + return logMgr.getLogLevelCount(searchCriteria); + } + + @GET + @Path("/components_count") + @Produces({"application/json"}) + public VCountList getComponentsCount(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.addParam("q", request.getParameter("q")); + searchCriteria + .addParam("startDate", request.getParameter("start_time")); + searchCriteria.addParam("endDate", request.getParameter("end_time")); + return logMgr.getComponenetsCount(searchCriteria); + } + + @GET + @Path("/hosts_count") + @Produces({"application/json"}) + public VCountList getHostsCount(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.addParam("q", request.getParameter("q")); + searchCriteria + .addParam("startDate", request.getParameter("start_time")); + searchCriteria.addParam("endDate", request.getParameter("end_time")); + searchCriteria.addParam("excludeQuery", StringEscapeUtils + .unescapeXml(request.getParameter("excludeQuery"))); + searchCriteria.addParam("includeQuery", StringEscapeUtils + .unescapeXml(request.getParameter("includeQuery"))); + return logMgr.getHostsCount(searchCriteria); + } + + @GET + @Path("/getTreeExtension") + @Produces({"application/json"}) + public VNodeList getTreeExtension(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + searchCriteria.addParam("hostName", request.getParameter("hostName")); + return logMgr.getTreeExtension(searchCriteria); + } + + @GET + @Path("/getLogLevelCounts") + @Produces({"application/json"}) + public VNameValueList getLogsLevelCount(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + return logMgr.getLogsLevelCount(searchCriteria); + } + + @GET + @Path("/getHistogramData") + @Produces({"application/json"}) + public String getHistogramData(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + searchCriteria.addParam("unit", request.getParameter("unit")); + return logMgr.getHistogramData(searchCriteria); + } + + @GET + @Path("/cancelFindRequest") + @Produces({"application/json"}) + public String cancelFindRequest(@Context HttpServletRequest request) { + return logMgr.cancelFindRequestByDate(request); + } + + @GET + @Path("/exportToTextFile") + @Produces({"application/json"}) + public Response exportToTextFile(@Context HttpServletRequest request) { + + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + searchCriteria.addParam("unit", request.getParameter("unit")); + searchCriteria.addParam("format", request.getParameter("format")); + searchCriteria.addParam("utcOffset", request.getParameter("utcOffset")); + return logMgr.exportToTextFile(searchCriteria); + + } + + @GET + @Path("/getHostListByComponent") + @Produces({"application/json"}) + public String getHostListByComponent(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + searchCriteria.addParam("componentName", + request.getParameter("componentName")); + return logMgr.getHostListByComponent(searchCriteria); + } + + @GET + @Path("/getComponentListWithLevelCounts") + @Produces({"application/json"}) + public String getComponentListWithLevelCounts( + @Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + return logMgr.getComponentListWithLevelCounts(searchCriteria); + } + + @GET + @Path("/solr/getBundleIdBoundaryDates") + @Produces({"application/json"}) + public String getExtremeDatesForBundelId(@Context HttpServletRequest request) { + + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam(LogSearchConstants.BUNDLE_ID, + request.getParameter("bundle_id")); + + return logMgr.getExtremeDatesForBundelId(searchCriteria); + + } + + @GET + @Path("/getServiceLogsFieldsName") + @Produces({"application/json"}) + public String getServiceLogsFieldsName() { + return logMgr.getServiceLogsFieldsName(); + } + + @GET + @Path("/getServiceLogsSchemaFieldsName") + @Produces({"application/json"}) + public String getServiceLogsSchemaFieldsName() { + return logMgr.getServiceLogsSchemaFieldsName(); + } + + @GET + @Path("/getCurrentPageOfKeywordSearch") + @Produces({"application/json"}) + public String getCurrentPageOfKeywordSearch(@Context HttpServletRequest request) { + String requestDate = (String) request.getParameter("requestDate"); + return logMgr.getCurrentPageOfKeywordSearch(requestDate); + } + + @GET + @Path("/getAnyGraphData") + @Produces({"application/json"}) + public String getAnyGraphData(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("xAxis", request.getParameter("xAxis")); + searchCriteria.addParam("yAxis", request.getParameter("yAxis")); + searchCriteria.addParam("stackBy", request.getParameter("stackBy")); + searchCriteria.addParam("from", request.getParameter("from")); + searchCriteria.addParam("to", request.getParameter("to")); + searchCriteria.addParam("unit", request.getParameter("unit")); + return logMgr.getAnyGraphData(searchCriteria); + } + + @GET + @Path("/getAfterBeforeLogs") + @Produces({"application/json"}) + public String getAfterBeforeLogs(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addRequiredServiceLogsParams(request); + searchCriteria.addParam("hostLogFile", request.getParameter("host")); + searchCriteria.addParam("compLogFile", + request.getParameter("component")); + searchCriteria.addParam("id", request.getParameter("id")); + searchCriteria.addParam("scrollType", + request.getParameter("scrollType")); + searchCriteria.addParam("numberRows", + request.getParameter("numberRows")); + return logMgr.getAfterBeforeLogs(searchCriteria); + } + + @GET + @Path("/getSuggestoins") + @Produces({"application/json"}) + public String getSuggestions(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.addParam("fieldName", request.getParameter("fieldName")); + searchCriteria.addParam("valueToSuggest", + request.getParameter("valueToSuggest")); + return logMgr.getSuggestions(searchCriteria); + } + + @GET + @Path("/getHadoopServiceConfigJSON") + @Produces({"application/json"}) + public String getHadoopServiceConfigJSON() { + return logMgr.getHadoopServiceConfigJSON(); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/LogFileREST.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/LogFileREST.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/LogFileREST.java new file mode 100644 index 0000000..ef1bb8f --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/LogFileREST.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; + +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.manager.LogFileMgr; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Path("logfile") +@Component +@Scope("request") +public class LogFileREST { + + @Autowired + LogFileMgr logFileMgr; + + @GET + @Produces({"application/json"}) + public String searchLogFiles(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam("component", request.getParameter("component")); + searchCriteria.addParam("host", request.getParameter("host")); + searchCriteria.addParam("logType", request.getParameter("logType")); + return logFileMgr.searchLogFiles(searchCriteria); + } + + @GET + @Path("/getLogFileTail") + @Produces({"application/json"}) + public String getLogFileTail(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.addParam("host", request.getParameter("host")); + searchCriteria.addParam("component", request.getParameter("component")); + searchCriteria.addParam("name", request.getParameter("name")); + searchCriteria.addParam("tailSize", request.getParameter("tailSize")); + return logFileMgr.getLogFileTail(searchCriteria); + } + +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/PublicREST.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/PublicREST.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/PublicREST.java new file mode 100644 index 0000000..7977703 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/PublicREST.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.rest; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +import org.apache.ambari.logsearch.manager.PublicMgr; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Path("public") +@Component +@Scope("request") +public class PublicREST { + + @Autowired + PublicMgr generalMgr; + + @GET + @Path("/getGeneralConfig") + public String getGeneralConfig() { + return generalMgr.getGeneralConfig(); + } +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/UserConfigREST.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/UserConfigREST.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/UserConfigREST.java new file mode 100644 index 0000000..c459ab7 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/rest/UserConfigREST.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.ambari.logsearch.rest; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; + +import org.apache.ambari.logsearch.common.LogSearchConstants; +import org.apache.ambari.logsearch.common.SearchCriteria; +import org.apache.ambari.logsearch.manager.UserConfigMgr; +import org.apache.ambari.logsearch.util.RESTErrorUtil; +import org.apache.ambari.logsearch.view.VLogfeederFilter; +import org.apache.ambari.logsearch.view.VLogfeederFilterWrapper; +import org.apache.ambari.logsearch.view.VUserConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Path("userconfig") +@Component +@Scope("request") +public class UserConfigREST { + + @Autowired + RESTErrorUtil restErrorUtil; + + @Autowired + UserConfigMgr userConfigMgr; + + @POST + @Path("/saveUserConfig") + @Produces({"application/json"}) + public String saveUserConfig(VUserConfig vhist) { + return userConfigMgr.saveUserConfig(vhist); + } + + @PUT + @Path("/updateUserConfig") + @Produces({"application/json"}) + public String updateUserConfig(VUserConfig vhist) { + return userConfigMgr.updateUserConfig(vhist); + } + + @DELETE + @Path("/deleteUserConfig/{id}") + public void deleteUserConfig(@PathParam("id") String id) { + userConfigMgr.deleteUserConfig(id); + } + + @GET + @Path("/getUserConfig") + @Produces({"application/json"}) + public String getUserConfig(@Context HttpServletRequest request) { + SearchCriteria searchCriteria = new SearchCriteria(request); + searchCriteria.addParam(LogSearchConstants.USER_NAME, + request.getParameter("userId")); + searchCriteria.addParam(LogSearchConstants.FILTER_NAME, + request.getParameter("filterName")); + searchCriteria.addParam(LogSearchConstants.ROW_TYPE, + request.getParameter("rowType")); + return userConfigMgr.getUserConfig(searchCriteria); + } + + @GET + @Path("/user_filter") + @Produces({"application/json"}) + public String getUserFilter(@Context HttpServletRequest request) { + return userConfigMgr.getUserFilter(); + } + + @POST + @Path("/user_filter") + @Produces({"application/json"}) + public String createUserFilter(String json) { + return userConfigMgr.saveUserFiter(json); + } + + @PUT + @Path("/user_filter/{id}") + @Produces({"application/json"}) + public String updateUserFilter(String json) { + return userConfigMgr.saveUserFiter(json); + } + + @GET + @Path("/getAllUserName") + @Produces({"application/json"}) + public String getAllUserName() { + return userConfigMgr.getAllUserName(); + } + +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchContextHolder.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchContextHolder.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchContextHolder.java new file mode 100644 index 0000000..fb23cde --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchContextHolder.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.security.context; + +public class LogsearchContextHolder { + + private static final ThreadLocal<LogsearchSecurityContext> securityContextThreadLocal = new ThreadLocal<LogsearchSecurityContext>(); + + private LogsearchContextHolder() { + + } + + public static LogsearchSecurityContext getSecurityContext() { + return securityContextThreadLocal.get(); + } + + public static void setSecurityContext(LogsearchSecurityContext context) { + securityContextThreadLocal.set(context); + } + + public static void resetSecurityContext() { + securityContextThreadLocal.remove(); + } + +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchSecurityContext.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchSecurityContext.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchSecurityContext.java new file mode 100644 index 0000000..4a79525 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/security/context/LogsearchSecurityContext.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.security.context; + +import java.io.Serializable; + +import org.apache.ambari.logsearch.common.RequestContext; +import org.apache.ambari.logsearch.common.UserSessionInfo; + + +public class LogsearchSecurityContext implements Serializable{ + private static final long serialVersionUID = 1L; + private UserSessionInfo userSession; + private RequestContext requestContext; + + public UserSessionInfo getUserSession() { + return userSession; + } + + public void setUserSession(UserSessionInfo userSession) { + this.userSession = userSession; + } + + /** + * @return the requestContext + */ + public RequestContext getRequestContext() { + return requestContext; + } + + /** + * @param requestContext the requestContext to set + */ + public void setRequestContext(RequestContext requestContext) { + this.requestContext = requestContext; + } + + +} http://git-wip-us.apache.org/repos/asf/ambari/blob/39c85bb8/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/service/UserService.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/service/UserService.java b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/service/UserService.java new file mode 100644 index 0000000..4b2b918 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-portal/src/main/java/org/apache/ambari/logsearch/service/UserService.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.ambari.logsearch.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.apache.ambari.logsearch.dao.UserDao; +import org.apache.ambari.logsearch.web.model.User; +import org.apache.log4j.Logger; + + +@Service +public class UserService implements UserDetailsService { + private static final Logger logger = Logger.getLogger(UserService.class); + + @Autowired + private UserDao userDao; + + @Override + public User loadUserByUsername(final String username) throws UsernameNotFoundException { + logger.debug(userDao + " loadUserByUsername " + username); + return userDao.loadUserByUsername(username); + } + +}
