List of usage examples for java.lang StringBuilder lastIndexOf
@Override public int lastIndexOf(String str)
From source file:edu.harvard.i2b2.workplace.dao.FolderDao.java
/** * This method is to set protected access on a file/folder in workplace * It first checks if user has correct privileges to the file, that is * either he she is manager or the file is shared or the file belongs * to him/her. The it searches for all the folders under the given * index. if folders are found then it runs the update query atleast * 3 times to update the root folder in workplace_access table, all the * child folders in workplace table and all the child content in workplace * table. /*from w w w .j a v a 2 s . com*/ * * @param requestType * @param projectInfo * @param dbInfo * @param userId * @return * @throws I2B2DAOException * @throws I2B2Exception * * @author Neha Patel */ public int setProtectedAccess(final ProtectedType requestType, final ProjectType projectInfo, final DBInfoType dbInfo, String userId) throws I2B2DAOException, I2B2Exception { boolean settingRoot = false; int numRowsSet = -1; int numParentUpdated = -1; int numWorkAccUpdated = -1; String sharedStr = ""; String contentUserId = ""; String tableName = ""; boolean managerRole = false; boolean isFolder = true; String metadataSchema = dbInfo.getDb_fullSchema(); setDataSource(dbInfo.getDb_dataSource()); if (projectInfo.getRole().size() == 0) { log.error("no role found for this user in project: " + projectInfo.getName()); I2B2Exception e = new I2B2Exception("No role found for user"); throw e; } // Check if user is a manager for (String param : projectInfo.getRole()) { if (param.equalsIgnoreCase("manager")) { managerRole = true; break; } } ParameterizedRowMapper<String> map = new ParameterizedRowMapper<String>() { public String mapRow(ResultSet rs, int rowNum) throws SQLException { String resultRow = "\\tablename=" + rs.getString("c_table_name") + "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id"); return resultRow; } }; //extract table code and index String tableCd = StringUtil.getTableCd(requestType.getIndex()); String index = StringUtil.getIndex(requestType.getIndex()); List resultString = null; StringBuilder sqlToRetrieveTableName = new StringBuilder( "select distinct c_table_name, c_share_id, c_user_id from " + metadataSchema + "workplace_access where LOWER(c_group_id) = ?"); // Check if the user is setting access for root directory // by looking for index in the current table try { sqlToRetrieveTableName.append(" and c_index = ? "); resultString = jt.query(sqlToRetrieveTableName.toString(), map, projectInfo.getId().toLowerCase(), index); } catch (DataAccessException e) { log.error(e.getMessage()); throw new I2B2DAOException("Database Error"); } String resultToSplit = ""; // if the above query returned any result // that means user was setting access for root directory if (resultString != null && !resultString.isEmpty()) { settingRoot = true; isFolder = true; // getting tablename, share_id, user_id from the result string resultToSplit = (String) resultString.get(0); int indexofShared = resultToSplit.indexOf("\\share_id="); int indexofUser = resultToSplit.indexOf("\\user_id="); tableName = resultToSplit.substring(11, indexofShared); // if its not manager check if the file/folder is shared // if not shared either, then verify that user is setting // privilege for his/her file/folder if (managerRole == false) { sharedStr = resultToSplit.substring(indexofShared + 10, indexofUser); contentUserId = resultToSplit.substring(indexofUser + 9); if (!sharedStr.equalsIgnoreCase("Y")) { if (!contentUserId.equalsIgnoreCase(userId)) { log.debug("User does not have privileges to set protected access for this content"); return -11111; } } // if (sharedStr==null || !sharedStr.equalsIgnoreCase("Y")) } // if managerRole == false } //if(resultString!=null && !resultString.isEmpty()) // query result is null that means item doesn't exist in workplace_access table // or user is not setting access for root directory // Get tablename using the tablecd given as part of indexString in the request else if (resultString == null || resultString.isEmpty()) { // replace the last condition of 'and c_index=?' with 'and c_table_cd' sqlToRetrieveTableName.replace(sqlToRetrieveTableName.lastIndexOf("and"), sqlToRetrieveTableName.length() - 1, " and LOWER(c_table_cd) = ? "); try { resultString = jt.query(sqlToRetrieveTableName.toString(), map, projectInfo.getId().toLowerCase(), tableCd.toLowerCase()); } catch (DataAccessException e) { log.error(e.getMessage()); throw new I2B2DAOException("Database Error"); } resultToSplit = (String) resultString.get(0); // getting tablename from the query result tableName = resultToSplit.substring(11, resultToSplit.indexOf("\\share_id=")); List result; ParameterizedRowMapper<String> mapTocheckAccess = new ParameterizedRowMapper<String>() { public String mapRow(ResultSet rs, int rowNum) throws SQLException { String resultRow = "\\share_id=" + rs.getString("c_share_id") + "\\user_id=" + rs.getString("c_user_id") + "\\type=" + rs.getString("c_work_xml_i2b2_type"); return resultRow; } }; // Run query in table workplace to find out if the content is shared or does it belong to user // Also find the type of the file String sql = "select c_share_id, c_user_id, c_work_xml_i2b2_type from " + metadataSchema + tableName + " where c_index = ? and LOWER(c_group_id) = ?"; try { result = jt.query(sql, mapTocheckAccess, index, projectInfo.getId().toLowerCase()); } catch (DataAccessException e) { log.error(e.getMessage()); throw new I2B2DAOException("Database Error"); } // get the user id and share_id from result string resultToSplit = (String) result.get(0); String type = resultToSplit.substring(resultToSplit.lastIndexOf("\\") + 6); if (!type.equalsIgnoreCase("FOLDER")) { isFolder = false; } else isFolder = true; // if user is not a manager // then check if file/folder is shared // if not shared then verify file/folder belongs to user if (managerRole == false) { sharedStr = resultToSplit.substring(10, resultToSplit.indexOf("\\user_id=")); contentUserId = resultToSplit.substring(resultToSplit.indexOf("\\user_id=") + 9, resultToSplit.lastIndexOf("\\")); if (sharedStr != null && !sharedStr.equalsIgnoreCase("Y")) { if (!contentUserId.equalsIgnoreCase(userId)) { log.debug("User does not have privileges to set protected access for this content"); return -11111; } } // if (sharedStr==null || !sharedStr.equalsIgnoreCase("Y")) } // if managerRole == false } StringBuilder indexStr = new StringBuilder(); String protectedAccVal = ""; if (requestType.getProtectedAccess().trim().equalsIgnoreCase("true")) protectedAccVal = "Y"; else protectedAccVal = "N"; ArrayList<String> parentIdxList = new ArrayList<String>(); parentIdxList.add(index); indexStr.append("'" + index + "'"); // if initial request was for a folder only // then run this part if (isFolder) { List resultingIndx; ParameterizedRowMapper<String> mapForIndexes = new ParameterizedRowMapper<String>() { public String mapRow(ResultSet rs, int rowNum) throws SQLException { String name = (rs.getString("c_index")); return name; } }; // Get all the parent indexes (folder indexes under the top level directory) // and store it in an arraylist String parentIdx = ""; for (int i = 0; i < parentIdxList.size(); i++) { try { parentIdx = parentIdxList.get(i); if (i > 0) { indexStr.append(", '" + parentIdx + "'"); } String sqlToCollectIndex = "select c_index from " + metadataSchema + tableName + " where c_parent_index = ? and LOWER(c_group_id) = ? and c_work_xml_i2b2_type = 'FOLDER'"; resultingIndx = jt.query(sqlToCollectIndex, mapForIndexes, parentIdx, projectInfo.getId().toLowerCase()); } catch (DataAccessException e) { log.error(e.getMessage()); throw new I2B2DAOException("Database Error"); } if (resultingIndx != null) parentIdxList.addAll(resultingIndx); } // set the protected access for all the content found under the // parent indexes stored in the arraylist numParentUpdated = updateProtectedAccess(metadataSchema, tableName, "c_parent_index", indexStr.toString(), protectedAccVal); } if (settingRoot) { // set the protected access for root directory which is in workplace_access table numWorkAccUpdated = updateProtectedAccess(metadataSchema, "workplace_access", "c_index", indexStr.toString(), protectedAccVal); } // If setting root folder, then set all the folders to protected access // if setting one item then still use the same query to set that item to protected_access numRowsSet = updateProtectedAccess(metadataSchema, tableName, "c_index", indexStr.toString(), protectedAccVal); // Return the correct number of updated rows if (isFolder) numRowsSet += numParentUpdated; if (settingRoot) numRowsSet += numWorkAccUpdated; return numRowsSet; }
From source file:com.stratelia.webactiv.yellowpages.control.YellowpagesSessionController.java
private List<StringBuilder> exportAllDataAsCSV() { Collection<ContactFatherDetail> contacts = getAllContactDetails(currentTopic.getNodePK()); StringBuilder csvRow = new StringBuilder(); List<StringBuilder> csvRows = new ArrayList<StringBuilder>(); // Can't export all columns because data are heterogenous csvRow = getCSVCols();/*from w ww . jav a2s . co m*/ // csvRows.add(csvRow); for (ContactFatherDetail contactFatherDetail : contacts) { ContactDetail contact = contactFatherDetail.getContactDetail(); if (contact != null) { csvRow = new StringBuilder(); addCSVValue(csvRow, contact.getLastName()); addCSVValue(csvRow, contact.getFirstName()); addCSVValue(csvRow, contact.getEmail()); addCSVValue(csvRow, contact.getPhone()); addCSVValue(csvRow, contact.getFax()); // adding userFull data UserFull userFull = contact.getUserFull(); if (userFull != null) { String[] properties = userFull.getPropertiesNames(); for (String property : properties) { if (!property.startsWith("password")) { addCSVValue(csvRow, userFull.getValue(property)); } } } // adding xml data String modelId = "unknown"; try { modelId = getNodeBm().getDetail(new NodePK(contactFatherDetail.getNodeId(), getComponentId())) .getModelId(); if (StringUtil.isDefined(modelId) && modelId.endsWith(".xml")) { String xmlFormName = modelId; String xmlFormShortName = xmlFormName.substring(0, xmlFormName.indexOf(".")); PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager() .getPublicationTemplate(getComponentId() + ":" + xmlFormShortName, xmlFormName); // get template and data AbstractForm formView = (AbstractForm) pubTemplate.getViewForm(); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord(contact.getPK().getId()); List<FieldTemplate> fields = formView.getFieldTemplates(); for (FieldTemplate fieldTemplate : fields) { String fieldType = fieldTemplate.getTypeName(); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw, true); Field field = data.getField(fieldTemplate.getFieldName()); if (field != null) { if (!fieldType.equals(Field.TYPE_FILE)) { FieldDisplayer fieldDisplayer = TypeManager.getInstance() .getDisplayer(fieldType, "simpletext"); if (fieldDisplayer != null) { fieldDisplayer.display(out, field, fieldTemplate, new PagesContext()); } String fieldValue = sw.getBuffer().toString(); // removing ending carriage return appended by out.println() of displayers if (fieldValue.endsWith("\r\n")) { fieldValue = fieldValue.substring(0, fieldValue.length() - 2); } addCSVValue(csvRow, fieldValue); } } } } } catch (Exception e) { SilverTrace.warn("yellowpages", "YellowpagesSessionController.exportAllDataAsCSV", "yellowpages.EX_GET_USER_DETAIL_FAILED", "modelId = " + modelId + ", contactId = " + contact.getPK().getId()); } // Remove final "," csvRow.deleteCharAt(csvRow.lastIndexOf(",")); csvRows.add(csvRow); } } return csvRows; }
From source file:com.impetus.client.cassandra.query.CassQuery.java
/** * On condition.//from w w w .j ava2 s .c o m * * @param m * the m * @param metaModel * the meta model * @param keyObj * the compound key * @param idColumn * the id column * @param builder * the builder * @param isPresent * the is present * @param translator * the translator * @param use * the use * @return true, if successful */ private boolean onCondition(EntityMetadata m, MetamodelImpl metaModel, EmbeddableType keyObj, String idColumn, StringBuilder builder, boolean isPresent, CQLTranslator translator, boolean use) { String partitionKey = null; boolean allowFiltering = false; for (Object o : getKunderaQuery().getFilterClauseQueue()) { if (o instanceof FilterClause) { FilterClause clause = ((FilterClause) o); String fieldName = clause.getProperty(); String condition = clause.getCondition(); List<Object> value = clause.getValue(); boolean useInClause = condition.trim().equalsIgnoreCase("IN"); // if compound key field is given in where clause. isPresent = true; if (keyObj != null && idColumn.equals(fieldName)) { Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields(); Map<Attribute, List<Object>> columnValues = new HashMap<Attribute, List<Object>>(); for (Field field : fields) { if (!ReflectUtils.isTransientOrStatic(field)) { extractCompositeKey(metaModel, keyObj, builder, translator, value, useInClause, columnValues, field); } } // Composite key always contains clusterKey. allowFiltering = true; if (useInClause) { for (Attribute columnAttribute : columnValues.keySet()) { isPresent = appendInClause(builder, translator, columnValues.get(columnAttribute), ((AbstractAttribute) columnAttribute).getBindableJavaType(), ((AbstractAttribute) columnAttribute).getJPAColumnName(), isPresent); } } } else if (keyObj != null && metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()) && StringUtils.contains(fieldName, '.')) { // Means it is a case of composite column. isPresent = getCompoundKeyColumn(metaModel, keyObj, builder, isPresent, translator, fieldName, condition, value, useInClause); allowFiltering = true; } else if (idColumn.equals(fieldName)) { // dont use token for equals query on id column (#856) boolean useToken = use; if (condition.equals("=")) { useToken = false; } isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause, ((AbstractAttribute) m.getIdAttribute()), CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties, ((CassandraClientBase) persistenceDelegeator.getClient(m)).isCql3Enabled(m)), useToken); } else { EntityType entity = metaModel.entity(m.getEntityClazz()); // Metamodel metamodel = // KunderaMetadataManager.getMetamodel(kunderaMetadata, // m.getPersistenceUnit()); String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn(); if (fieldName.equals(discriminatorColumn)) { translator.buildWhereClause(builder, String.class, fieldName, value.isEmpty() ? null : value.get(0), condition, false); isPresent = true; } else { Metamodel metamodel = KunderaMetadataManager.getMetamodel(kunderaMetadata, m.getPersistenceUnit()); Attribute attribute = ((MetamodelImpl) metamodel).getEntityAttribute(m.getEntityClazz(), m.getFieldName(fieldName)); isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause, ((AbstractAttribute) attribute), fieldName, false); } allowFiltering = true; } } } // Strip last AND clause. if (isPresent) { builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length()); } // Append order by clause into query builder = appendOrderByClause(metaModel, m, keyObj, builder, translator); if (allowFiltering && use) { onLimit(builder); builder.append(" "); translator.buildFilteringClause(builder); } else if (use) { onLimit(builder); } return isPresent; }
From source file:org.kuali.ole.select.document.OleOrderQueueDocument.java
/** * This method invokes approveDocument of DocumentService to approve selected requisitions * and sets errors appriopriately if approval fails. *///from w w w . j a va 2 s. c o m public void massApprove() { LOG.debug("Inside massApprove of OleOrderQueueDocument"); ActionListService actionListSrv = KEWServiceLocator.getActionListService(); ActionRequestService actionReqSrv = KEWServiceLocator.getActionRequestService(); boolean orderQueue = false; boolean orderQueueNotApproved = false; WorkflowDocumentService workflowDocumentService = KRADServiceLocatorWeb.getWorkflowDocumentService(); Person person = SpringContext.getBean(PersonService.class) .getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId()); WorkflowDocument workflowDocument; String docNum = null; StringBuilder orderQueueRequisitionApproved = new StringBuilder(); StringBuilder orderQueueRequisitionNotApproved = new StringBuilder(); List<OleRequisitionItem> refreshItems = new ArrayList<OleRequisitionItem>(); for (OleRequisitionItem item : requisitionItems) { boolean itemAdded = item.isItemAdded(); if (itemAdded) { try { workflowDocument = workflowDocumentService .loadWorkflowDocument(item.getRequisition().getDocumentNumber(), person); if (workflowDocument.getInitiatorPrincipalId() .equals(GlobalVariables.getUserSession().getPerson().getPrincipalId())) { if (DocumentStatus.ENROUTE.equals(workflowDocument.getStatus())) { List<ActionRequestValue> actionReqValues = actionReqSrv .findAllPendingRequests(item.getRequisition().getDocumentNumber()); for (ActionRequestValue actionRequest : actionReqValues) { if (KewApiConstants.ACTION_REQUEST_APPROVE_REQ .equals(actionRequest.getActionRequested())) { Timestamp currentTime = SpringContext.getBean(DateTimeService.class) .getCurrentTimestamp(); List<ActionItem> actionItems = actionRequest.getActionItems(); for (ActionItem actionItem : actionItems) { if (KewApiConstants.ACTION_REQUEST_APPROVE_REQ_LABEL .equals(actionItem.getActionRequestLabel())) { actionItem.setPrincipalId( GlobalVariables.getUserSession().getPerson().getPrincipalId()); actionItem.setDateAssigned(currentTime); actionListSrv.saveActionItem(actionItem); } } actionRequest.setPrincipalId( GlobalVariables.getUserSession().getPerson().getPrincipalId()); actionRequest.setCreateDate(currentTime); actionReqSrv.saveActionRequest(actionRequest); boolean documentApproved = approveDocument( new Long(item.getRequisition().getPurapDocumentIdentifier()), item.getRequisition().getDocumentNumber(), actionRequest.getAnnotation()); if (!documentApproved) { refreshItems.add(item); } else { if (!item.getRequisition().getDocumentNumber().equalsIgnoreCase(docNum)) { orderQueueRequisitionApproved .append(item.getRequisition().getDocumentNumber()).append(","); orderQueue = true; docNum = item.getRequisition().getDocumentNumber(); } } } else { GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS, OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_NOAPPROVALS_REQD, new String[] { item.getRequisition().getDocumentNumber() }); refreshItems.add(item); } } } else if (workflowDocument.isSaved()) { boolean documentSubmitted = submitDocument( Long.valueOf(item.getRequisition().getPurapDocumentIdentifier()), item.getRequisition().getDocumentNumber(), OLEConstants.OrderQueue.SUBMIT_ANNOTATION); if (!documentSubmitted) { refreshItems.add(item); } else { orderQueueRequisitionApproved.append(item.getRequisition().getDocumentNumber()) .append(","); orderQueue = true; } } else { GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS, OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_APPROVE, new String[] { workflowDocument.getStatus().toString(), item.getRequisition().getDocumentNumber() }); refreshItems.add(item); } } else { orderQueueRequisitionNotApproved.append(item.getRequisition().getDocumentNumber()) .append(","); orderQueueNotApproved = true; } } catch (WorkflowException ex) { GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS, RiceKeyConstants.ERROR_CUSTOM, ex.getMessage()); refreshItems.add(item); } } else { refreshItems.add(item); } } int len = orderQueueRequisitionApproved.lastIndexOf(","); if (orderQueue) { orderQueueRequisitionApproved.replace(len, len + 1, " "); GlobalVariables.getMessageMap().putInfo(OLEConstants.OrderQueue.REQUISITIONS, OLEKeyConstants.MESSAGE_ORDERQUEUE_REQUISITIONS_APPROVED, new String[] { orderQueueRequisitionApproved.toString() }); } int length = orderQueueRequisitionNotApproved.lastIndexOf(","); if (orderQueueNotApproved) { orderQueueRequisitionNotApproved.replace(length, length + 1, " "); GlobalVariables.getMessageMap().putError(OLEConstants.OrderQueue.REQUISITIONS, OLEKeyConstants.ERROR_ORDERQUEUE_REQUISITIONS_APPROVE_NOT_INITIATOR, new String[] { orderQueueRequisitionNotApproved.toString() }); } requisitionItems = refreshItems; LOG.debug("Leaving massApprove of OleOrderQueueDocument"); }
From source file:forge.game.card.Card.java
public String getAbilityText(final CardState state) { final CardTypeView type = state.getType(); final StringBuilder sb = new StringBuilder(); if (!mayPlay.isEmpty()) { sb.append("May be played by: "); sb.append(//from w w w.j av a2 s . co m Lang.joinHomogenous(mayPlay.entrySet(), new Function<Entry<Player, CardPlayOption>, String>() { @Override public String apply(final Entry<Player, CardPlayOption> entry) { return entry.getKey().toString() + entry.getValue().toString(); } })); sb.append("\r\n"); } if (type.isInstant() || type.isSorcery()) { sb.append(abilityTextInstantSorcery(state)); if (haunting != null) { sb.append("Haunting: ").append(haunting); sb.append("\r\n"); } while (sb.toString().endsWith("\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } return sb.toString().replaceAll("CARDNAME", state.getName()); } if (monstrous) { sb.append("Monstrous\r\n"); } if (renowned) { sb.append("Renowned\r\n"); } if (manifested) { sb.append("Manifested\r\n"); } sb.append(keywordsToText(getUnhiddenKeywords(state))); // Give spellText line breaks for easier reading sb.append("\r\n"); sb.append(text.replaceAll("\\\\r\\\\n", "\r\n")); sb.append("\r\n"); // Triggered abilities for (final Trigger trig : state.getTriggers()) { if (!trig.isSecondary()) { sb.append(trig.toString().replaceAll("\\\\r\\\\n", "\r\n")).append("\r\n"); } } // Replacement effects for (final ReplacementEffect replacementEffect : state.getReplacementEffects()) { if (!replacementEffect.isSecondary()) { sb.append(replacementEffect.toString()).append("\r\n"); } } // static abilities for (final StaticAbility stAb : state.getStaticAbilities()) { sb.append(stAb.toString()).append("\r\n"); } final List<String> addedManaStrings = new ArrayList<>(); boolean primaryCost = true; boolean isNonAura = !type.hasSubtype("Aura"); for (final SpellAbility sa : state.getSpellAbilities()) { // only add abilities not Spell portions of cards if (sa == null || !state.getType().isPermanent()) { continue; } boolean isNonAuraPermanent = (sa instanceof SpellPermanent) && isNonAura; if (isNonAuraPermanent && primaryCost) { // For Alt costs, make sure to display the cost! primaryCost = false; continue; } final String sAbility = formatSpellAbility(sa); if (sa.getManaPart() != null) { if (addedManaStrings.contains(sAbility)) { continue; } addedManaStrings.add(sAbility); } if (isNonAuraPermanent) { sb.insert(0, "\r\n"); sb.insert(0, sAbility); } else if (!sAbility.endsWith(state.getName() + "\r\n")) { sb.append(sAbility); sb.append("\r\n"); } } // NOTE: if (sb.toString().contains(" (NOTE: ")) { sb.insert(sb.indexOf("(NOTE: "), "\r\n"); } if (sb.toString().contains("(NOTE: ") && sb.toString().contains(".) ")) { sb.insert(sb.indexOf(".) ") + 3, "\r\n"); } // replace triple line feeds with double line feeds int start; final String s = "\r\n\r\n\r\n"; while (sb.toString().contains(s)) { start = sb.lastIndexOf(s); if ((start < 0) || (start >= sb.length())) { break; } sb.replace(start, start + 4, "\r\n"); } return sb.toString().replaceAll("CARDNAME", state.getName()).trim(); }
From source file:com.ah.ui.actions.hiveap.HiveApUpdateAction.java
@Override public String execute() throws Exception { String forward = globalForward(); if (forward != null) { return forward; }/* w w w. j a va 2 s . com*/ try { // check session token for CSRF attack if (!isCSRFTokenValida() && ("updateCountryCode".equals(operation) || "updateBootstrap".equals(operation) || "uploadWizard".equals(operation) || "uploadImage".equals(operation) || "uploadSignature".equals(operation) || "updateBootstrap".equals(operation) || "updatePoe".equals(operation) || "updateNetdump".equals(operation))) { generateAuditLog(HmAuditLog.STATUS_FAILURE, MgrUtil.getUserMessage("security.csrfattack") + getLastTitle()); throw new HmException(MgrUtil.getUserMessage("error.security.invalidRequest"), HmMessageCodes.SECURITY_REQUEST_INVALID, new String[] { "mitigate" }); } if ("wizard".equals(operation)) { removeSessionAttrs(); prepareConfigtBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_CONFIG); return UPDATE_LIST_TYPE_CONFIG; } else if ("imageInput".equals(operation)) { new Thread(new DAInformationTimer()).start(); removeSessionAttrs(); prepareImageBoList(); checkSupportedUpdateImage(); prepareDistributedDownload(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_IMAGE); return UPDATE_LIST_TYPE_IMAGE; } else if ("signatureInput".equals(operation)) { removeSessionAttrs(); prepareL7SignatureBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_L7_SIGNATURE); return UPDATE_LIST_TYPE_L7_SIGNATURE; } else if ("bootstrapInput".equals(operation)) { removeSessionAttrs(); prepareBootstrapBoList(); prepareBootstrapParams(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_BOOTSTRAP); return UPDATE_LIST_TYPE_BOOTSTRAP; } else if ("countryCodeInput".equals(operation)) { removeSessionAttrs(); prepareCountryCodeBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_COUNTRYCODE); return UPDATE_LIST_TYPE_COUNTRYCODE; } else if ("countryCodeInputJson".equals(operation)) { removeSessionAttrs(); prepareCountryCodeBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_COUNTRYCODE); return "countryCodeInputJson"; } else if (UPDATE_OUTDOOR_SETTINGS.equals(operation)) { removeSessionAttrs(); prepareOutdoorSettingsBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_OUTDOOR_SETTINGS); return UPDATE_OUTDOOR_SETTINGS; } else if ("poeInput".equals(operation)) { removeSessionAttrs(); preparePoeBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_POE); return UPDATE_LIST_TYPE_POE; } else if ("netdumpInput".equals(operation)) { removeSessionAttrs(); prepareNetdumpBoList(); MgrUtil.setSessionAttribute(UPDATE_LIST_TYPE, UPDATE_LIST_TYPE_NETDUMP); return UPDATE_LIST_TYPE_NETDUMP; } else if ("uploadWizard".equals(operation)) { log.info("execute", "operation:" + operation + ", configConfiguration:" + configConfiguration + ", configCwp:" + configCwp + ", configCertificate:" + configCertificate + ", configUserDatabase:" + configUserDatabase); if ("uploadConfigEx".equalsIgnoreCase(this.getExConfigGuideFeature())) { removeSessionAttrs(); removeUploadWaringSession(); } Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_SCRIPT_WIZARD); storeIdListToSession(UPDATE_CONFIG_SELECTED_IDS, selectedConfigIds, getPageIds()); if ("uploadConfigEx".equalsIgnoreCase(this.getExConfigGuideFeature())) { storeExIdListToSession(UPDATE_CONFIG_SELECTED_IDS_EX, selectedConfigIds); } if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); removeUploadWaringSession(); removeNWPolicyChangeSession(); logUpdateOperation(); if ("uploadConfigEx".equalsIgnoreCase(this.getExConfigGuideFeature())) { jsonObject = getUploadConfigExJson(operation); if (getUserContext().isSourceFromIdm()) { jsonObject.put("disDone", true); } return "json"; } else { return UPDATE_RESULT_LIST; } } else { prepareConfigtBoList(); if ("uploadConfigEx".equalsIgnoreCase(this.getExConfigGuideFeature())) { jsonObject = getUploadConfigExJson(operation); if (getUserContext().isSourceFromIdm()) { jsonObject.put("disDone", true); } return "json"; } else { return UPDATE_LIST_TYPE_CONFIG; } } } else if ("doneToIDM".equals(operation)) { jsonObject = new JSONObject(); try { JSONObject js; JSONArray ja = new JSONArray(); String sql = "select distinct s.ssidname,s.accessMode,s.cwpSelectEnabled from config_template_ssid c, ssid_profile s " + "where c.ssid_profile_id=s.id and s.enabledIDM=true and s.owner=" + getDomain().getId(); List<?> lst = QueryUtil.executeNativeQuery(sql); if (!lst.isEmpty()) { for (Object obj : lst) { Object[] items = (Object[]) obj; String ssidName = items[0].toString(); int accessMode = Integer.parseInt(items[1].toString()); boolean cwpEnabled = Boolean.valueOf(items[2].toString()); if (accessMode == SsidProfile.ACCESS_MODE_8021X || accessMode == SsidProfile.ACCESS_MODE_PSK) { js = new JSONObject(); js.put("n", ssidName); js.put("t", accessMode); ja.put(js); } else { if (cwpEnabled) { js = new JSONObject(); js.put("n", ssidName); js.put("t", accessMode); ja.put(js); } } } } jsonObject.put("url", getUserContext().getSourceUrl()); if (getUserContext().getSourceUrl() != null && getUserContext().getSourceUrl().indexOf("?") > 0) { jsonObject.put("params", "&ssids="); jsonObject.put("paramsValue", ja.toString()); } else { jsonObject.put("params", "?ssids="); jsonObject.put("paramsValue", ja.toString()); } //jsonObject.put("url", "hm/reports.action?operation=summary&tid=1001"); //jsonObject.put("params", "&v=" + ja.toString()); jsonObject.put("t", true); } catch (Exception e) { jsonObject.put("t", false); jsonObject.put("m", e.getMessage()); } return "json"; } else if ("checkNetworkPolicy".equals(operation)) { log.info("execute", "operation:" + operation + ", configConfiguration:" + configConfiguration + ", configCwp:" + configCwp + ", configCertificate:" + configCertificate + ", configUserDatabase:" + configUserDatabase); jsonObject = new JSONObject(); jsonObject.put(JSON_RESULT_TYPE_KEY, operation + JSON_RESULT_TYPE_SUFFIX); if (isEasyMode()) { jsonObject.put("t", true); return "json"; } else { clearErrorsAndMessages(); Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_SCRIPT_WIZARD); StringBuilder idLstStr = new StringBuilder(); for (Long idObj : selectedConfigIds) { if (idLstStr.length() != 0) { idLstStr.append(","); } idLstStr.append(idObj.toString()); } String strSql = "select _t1.hostName, _t2.enabledhcp, _t1.TEMPLATE_ID, _t1.id from HIVE_AP _t1 left join hiveap_device_interface _t2 on _t1.id= _t2.hiveap_id and _t2.deviceiftype=" + AhInterface.DEVICE_IF_TYPE_ETH0 + " where _t1.id in (" + idLstStr.toString() + ")"; List<?> apList = QueryUtil.executeNativeQuery(strSql); StringBuffer warningMsg = new StringBuffer(); //when the port type is Phone&Data,the lldp should be enabled StringBuffer lldpWarningMsg = new StringBuffer(); Set<String> setPolicyName = new HashSet<>(); boolean blnWarnMsgDisplay = false; StringBuilder bufferWarningMsg = new StringBuilder(); HashMap<Long, ConfigTemplate> mapConfigTemplate = new HashMap<>(); for (Object oneObj : apList) { Object[] oneAp = (Object[]) oneObj; ConfigTemplate wlanPolicy; if (mapConfigTemplate.get(Long.parseLong(oneAp[2].toString())) != null) { wlanPolicy = mapConfigTemplate.get(Long.parseLong(oneAp[2].toString())); } else { wlanPolicy = findBoById(ConfigTemplate.class, Long.parseLong(oneAp[2].toString()), this); mapConfigTemplate.put(wlanPolicy.getId(), wlanPolicy); } HiveAp oneHiveAP = findBoById(HiveAp.class, Long.parseLong(oneAp[3].toString()), this); if (oneHiveAP.isBranchRouter()) { blnWarnMsgDisplay = true; } if (oneHiveAP.isVpnGateway()) { if (oneHiveAP.getEth0Interface() == null || oneHiveAP.getEth0Interface().getIpAddress() == null || oneHiveAP.getEth0Interface().getIpAddress().equals("")) { jsonObject.put("t", false); jsonObject.put("errorMsg", getText("error.hiveap.cvg.wan.ip.empty", new String[] { oneHiveAP.getHostName() })); return "json"; } } // if (oneAp[1]==null || oneAp[1].toString().equals("") || // Boolean.valueOf(oneAp[1].toString()) // /*|| !wlanPolicy.isBlnWirelessRouter()*/ // || // if (!wlanPolicy.getConfigType().isRouterContained() // || !oneHiveAP.isBranchRouter() // || (oneHiveAP.isBranchRouter() && !checkDhcpWhenUpload(oneHiveAP))){ // connection type is pppoe and eth0 is primary // oneHiveAP.getEth0Interface().getConnectionType().equals("3") && // oneHiveAP.getEth0Interface().getWanOrder() == 1 )){ String ret = ""; if (!wlanPolicy.getConfigType().isBonjourOnly()) { ret = checkNetworkPolicy(wlanPolicy, false, warningMsg, setPolicyName, oneHiveAP, lldpWarningMsg); } if (!"".equals(ret)) { jsonObject.put("t", false); jsonObject.put("errorMsg", ret); return "json"; } // } else { // String ret=""; // if (!wlanPolicy.getConfigType().isBonjourOnly()) { // ret= checkNetworkPolicy(wlanPolicy, true, warningMsg, setPolicyName,oneHiveAP,lldpWarningMsg); // } // if (!"".equals(ret)){ // jsonObject.put("t", false); // jsonObject.put("m", ret); // return "json"; // } // } if (oneHiveAP.getDeviceType() == HiveAp.Device_TYPE_BRANCH_ROUTER) { if (mapConfigTemplate.get(Long.parseLong(oneAp[2].toString())) != null) { if (mapConfigTemplate.get(Long.parseLong(oneAp[2].toString())) .getRoutingProfilePolicy() != null) { if (NmsUtil.compareSoftwareVersion(oneHiveAP.getSoftVer(), "6.0.1.0") < 0) { jsonObject.put("t", false); jsonObject.put("errorMsg", getText("error.hiveAp.upload.RoutigPolicy.notmatach.ApVersion", new String[] { oneHiveAP.getHostName() })); return "json"; } } } } //check stp settings if (oneHiveAP.getDeviceStpSettings() != null && oneHiveAP.getDeviceStpSettings().isOverrideStp() && oneHiveAP.getDeviceStpSettings().isEnableStp()) { String ret1 = checkStpSettings(wlanPolicy, oneHiveAP); if (!"".equals(ret1)) { jsonObject.put("t", false); jsonObject.put("errorMsg", ret1); return "json"; } } if (oneHiveAP.isWifi1Available() && oneHiveAP.getDeviceType() != HiveAp.Device_TYPE_VPN_GATEWAY) { if (oneHiveAP.getWifi0RadioProfile() != null && oneHiveAP.getWifi1RadioProfile() != null) { boolean wifi0Model = false; if (oneHiveAP.getWifi0RadioProfile().isEnableClientLoadBalance() && oneHiveAP .getWifi0RadioProfile() .getLoadBalancingMode() == RadioProfile.LOAD_BALANCE_MODE_STATION_NUMBER) { wifi0Model = true; } boolean wifi1Model = false; if (oneHiveAP.getWifi1RadioProfile().isEnableClientLoadBalance() && oneHiveAP .getWifi1RadioProfile() .getLoadBalancingMode() == RadioProfile.LOAD_BALANCE_MODE_STATION_NUMBER) { wifi1Model = true; } if (wifi0Model ^ wifi1Model) { blnWarnMsgDisplay = true; if (!bufferWarningMsg.toString().equals("")) { bufferWarningMsg.append(", (").append(oneHiveAP.getHostName()).append(")"); } else { bufferWarningMsg.append("(").append(oneHiveAP.getHostName()).append(")"); } } } } } if (!getActionMessages().isEmpty()) { blnWarnMsgDisplay = true; } if (lldpWarningMsg.length() > 0) { blnWarnMsgDisplay = true; } if ((!warningMsg.toString().equals("") || !bufferWarningMsg.toString().equals("") || !lldpWarningMsg.toString().equals("") || !getActionMessages().isEmpty()) && blnWarnMsgDisplay) { StringBuilder wn = new StringBuilder(); if (!warningMsg.toString().equals("")) { wn.append(warningMsg.toString()).append("<br/><br/>"); } if (!lldpWarningMsg.toString().equals("")) { wn.append(lldpWarningMsg.toString()).append(".<br/><br/>"); } if (!bufferWarningMsg.toString().equals("")) { wn.append(getText("warning.hiveap.config.radio.loadbalance", new String[] { bufferWarningMsg.toString() })); wn.append("<br/><br/>"); } if (!getActionMessages().isEmpty()) { for (Object obj : getActionMessages()) { wn.append(obj.toString()); wn.append("<br/><br/>"); } } jsonObject.put("wn", wn.toString()); } clearErrorsAndMessages(); jsonObject.put("t", true); return "json"; } } else if ("checkWiFiClientMode".equals(operation)) { jsonObject = new JSONObject(); StringBuilder wfcmHosts = new StringBuilder(); boolean wfcmMsgDisplay = false; clearErrorsAndMessages(); Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_SCRIPT_WIZARD); for (Long idObj : selectedConfigIds) { HiveAp oneHiveAP = findBoById(HiveAp.class, idObj, this); if ((oneHiveAP.getHiveApModel() == HiveAp.HIVEAP_MODEL_BR200_WP || oneHiveAP.getHiveApModel() == HiveAp.HIVEAP_MODEL_BR200_LTE_VZ) && oneHiveAP.getDeviceType() == HiveAp.Device_TYPE_BRANCH_ROUTER && oneHiveAP.getRadioConfigType() == HiveAp.RADIO_MODE_ACCESS_WAN) { if (configSelectType.equals(HiveApUpdateSettings.ConfigSelectType.deltaRunning.toString()) || configSelectType.equals(HiveApUpdateSettings.ConfigSelectType.auto.toString()) && oneHiveAP.getLastCfgTime() != 0) { wfcmMsgDisplay = true; wfcmHosts.append(oneHiveAP.getHostName()).append(","); } } } if (wfcmMsgDisplay) { int index = wfcmHosts.lastIndexOf(","); if (index > 0) { wfcmHosts.deleteCharAt(index); } jsonObject.put("msg", MgrUtil.getUserMessage("info.wificlientmode.clioverride", wfcmHosts.toString())); } jsonObject.put("t", wfcmMsgDisplay); return "json"; } else if ("uploadImage".equals(operation)) { // if(!checkUploadQueue()){ // prepareImageBoList(); // return UPDATE_LIST_TYPE_IMAGE; // } Set<Long> selectedImageIds = getCurrentSelectedBoIds(AH_DOWNLOAD_IMAGE); storeIdListToSession(UPDATE_IMAGE_SELECTED_IDs, selectedImageIds, getPageIds()); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { prepareImageBoList(); return UPDATE_LIST_TYPE_IMAGE; } } else if ("uploadSignature".equals(operation)) { Set<Long> selectedSignatureIds = getCurrentSelectedBoIds(AH_DOWNLOAD_L7_SIGNATURE); storeIdListToSession(UPDATE_L7_SIGNATURE_SELECTED_IDs, selectedSignatureIds, getPageIds()); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { prepareL7SignatureBoList(); return UPDATE_LIST_TYPE_L7_SIGNATURE; } } else if ("updateBootstrap".equals(operation)) { Set<Long> selectedBootstrapIds = getCurrentSelectedBoIds(AH_DOWNLOAD_BOOTSTRAP); storeIdListToSession(UPDATE_BOOTSTRAP_SELECTED_IDs, selectedBootstrapIds, getPageIds()); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { prepareBootstrapBoList(); return UPDATE_LIST_TYPE_BOOTSTRAP; } } else if ("updateCountryCode".equals(operation)) { Set<Long> selectedDtlsIds = getCurrentSelectedBoIds(AH_DOWNLOAD_COUNTRY_CODE); storeIdListToSession(UPDATE_COUNTRYCODE_SELECTED_IDs, selectedDtlsIds, getPageIds()); if (updateCountryCodeParams() && generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { prepareCountryCodeBoList(); return UPDATE_LIST_TYPE_COUNTRYCODE; } } else if ("updateCountryCodeJson".equals(operation)) { Set<Long> selectedDtlsIds = getCurrentSelectedBoIds(AH_DOWNLOAD_COUNTRY_CODE); storeIdListToSession(UPDATE_COUNTRYCODE_SELECTED_IDs, selectedDtlsIds, getPageIds()); jsonObject = new JSONObject(); if (updateCountryCodeParams() && generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); jsonObject.put("t", true); return "json"; } else { jsonObject.put("t", false); for (Object errorMsg : getActionErrors()) { jsonObject.put("m", errorMsg); break; } return "json"; } } else if ("updateOutdoorSettings".equals(operation)) { Set<Long> selectedDtlsIds = getCurrentSelectedBoIds(AH_DOWNLOAD_OUTDOORSTTINGS); storeIdListToSession(UPDATE_OUTDOORSETTINGS_SELECTED_IDS, selectedDtlsIds, getPageIds()); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { prepareOutdoorSettingsBoList(); return UPDATE_OUTDOOR_SETTINGS; } } else if ("updatePoe".equals(operation)) { Set<Long> selectedPoeIds = getCurrentSelectedBoIds(AH_DOWNLOAD_POE); storeIdListToSession(UPDATE_POE_SELECTED_IDs, selectedPoeIds, getPageIds()); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { preparePoeBoList(); return UPDATE_LIST_TYPE_POE; } } else if ("uploadOsDetection".equals(operation)) { jsonObject = new JSONObject(); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); jsonObject.put("suc", true); } else { jsonObject.put("suc", false); } return "json"; } else if ("updateOsDetection".equals(operation)) { prepareOsDetection(); return "json"; } else if ("updateNetdump".equals(operation)) { Set<Long> selectedNetdumpIds = getCurrentSelectedBoIds(AH_DOWNLOAD_NET_DUMP); storeIdListToSession(UPDATE_NETDUMP_SELECTED_IDs, selectedNetdumpIds, getPageIds()); if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); logUpdateOperation(); return UPDATE_RESULT_LIST; } else { preparePoeBoList(); return UPDATE_LIST_TYPE_NETDUMP; } } else if ("importImage".equals(operation)) { addLstTitle(getText("hiveAp.update.image")); addLstForward("hiveApImageUpdate"); Set<Long> selectedImageIds = getCurrentSelectedBoIds(AH_DOWNLOAD_IMAGE); storeIdListToSession(UPDATE_IMAGE_SELECTED_IDs, selectedImageIds, getPageIds()); return operation; } else if ("continueImage".equals(operation)) { prepareImageBoList(); removeLstTitle(); removeLstForward(); return UPDATE_LIST_TYPE_IMAGE; } else if ("viewScript".equals(operation)) { log.info("execute", "operation:" + operation + ", ap id:" + id); String strSql = "select _t1.hostName, _t2.enabledhcp, _t1.TEMPLATE_ID, _t1.id from HIVE_AP _t1 left join hiveap_device_interface _t2 on _t1.id= _t2.hiveap_id and _t2.deviceiftype=" + AhInterface.DEVICE_IF_TYPE_ETH0 + " where _t1.id=" + id; // String strSql = "select hostName, dhcp, TEMPLATE_ID, id from HIVE_AP where id =" + id; List<?> apList = QueryUtil.executeNativeQuery(strSql); StringBuffer warningMsg = new StringBuffer(); HashMap<Long, ConfigTemplate> mapConfigTemplate = new HashMap<>(); Set<String> setPolicyName = new HashSet<>(); ConfigTemplate wlanPolicy = null; for (Object oneObj : apList) { Object[] oneAp = (Object[]) oneObj; if (mapConfigTemplate.get(Long.parseLong(oneAp[2].toString())) != null) { wlanPolicy = mapConfigTemplate.get(Long.parseLong(oneAp[2].toString())); } else { wlanPolicy = findBoById(ConfigTemplate.class, Long.parseLong(oneAp[2].toString()), this); mapConfigTemplate.put(wlanPolicy.getId(), wlanPolicy); } HiveAp oneHiveAP = findBoById(HiveAp.class, Long.parseLong(oneAp[3].toString()), this); if (oneHiveAP.isVpnGateway()) { if (oneHiveAP.getEth0Interface() == null || oneHiveAP.getEth0Interface().getIpAddress() == null || oneHiveAP.getEth0Interface().getIpAddress().equals("")) { jsonObject = new JSONObject(); jsonObject.put("err", getText("error.hiveap.cvg.wan.ip.empty", new String[] { oneHiveAP.getHostName() })); return "json"; } } // if (oneAp[1]==null || oneAp[1].toString().equals("") || // Boolean.valueOf(oneAp[1].toString()) /*|| !wlanPolicy.isBlnWirelessRouter()*/ // if(!wlanPolicy.getConfigType().isRouterContained() // || !oneHiveAP.isBranchRouter() // || (oneHiveAP.isBranchRouter() && !checkDhcpWhenUpload(oneHiveAP))){ // connection type is pppoe and eth0 is primary // oneHiveAP.getEth0Interface().getConnectionType().equals("3") && // oneHiveAP.getEth0Interface().getWanOrder() == 1 )){ // String ret=""; /*if (!wlanPolicy.isBlnBonjourOnly()) {*/ // if (!wlanPolicy.getConfigType().isBonjourOnly()) { String ret = checkNetworkPolicy(wlanPolicy, false, warningMsg, setPolicyName, oneHiveAP, null); // } if (!"".equals(ret)) { jsonObject = new JSONObject(); jsonObject.put("err", ret); return "json"; } // } else { // String ret=""; // if (!wlanPolicy.getConfigType().isBonjourOnly()) { // ret= checkNetworkPolicy(wlanPolicy, true, warningMsg, setPolicyName,oneHiveAP,null); // } // if (!"".equals(ret)){ // jsonObject = new JSONObject(); // jsonObject.put("err", ret); // return "json"; // } // } //check stp settings if (oneHiveAP.getDeviceStpSettings() != null && oneHiveAP.getDeviceStpSettings().isOverrideStp() && oneHiveAP.getDeviceStpSettings().isEnableStp()) { String ret1 = checkStpSettings(wlanPolicy, oneHiveAP); if (!"".equals(ret1)) { jsonObject = new JSONObject(); jsonObject.put("err", ret1); return "json"; } } } jsonObject = getScriptDetails(id, wlanPolicy); return "json"; } else if ("viewBootstrap".equals(operation)) { log.info("execute", "operation:" + operation + ", ap id:" + id); jsonObject = getBootstrapDetails(id); return "json"; } else if ("viewPsk".equals(operation)) { log.info("execute", "operation:" + operation + ", ap id:" + id); jsonObject = getPskDetails(id); return "json"; } else if ("enableTftp".equals(operation)) { jsonObject = getTftpResult(); return "json"; } else if ("saveSignatureOption".equals(operation)) { log.info("execute", "operation:" + operation); jsonObject = saveSignatureOptions(); return "json"; } else if ("saveImageOption".equals(operation)) { log.info("execute", "operation:" + operation); jsonObject = saveImageOptions(); return "json"; } else if ("saveConfigOption".equals(operation)) { log.info("execute", "operation:" + operation); jsonObject = saveConfigOptions(); return "json"; } else if ("fetchImageInfo".equals(operation)) { log.info("operation: " + operation + ", selectedVersion: " + selectedVersion + ", selectedImage: " + selectedImage); jsonObject = fetchImageInfo(); return "json"; } else if ("fetchSignatureInfo".equals(operation)) { log.info("operation: " + operation + ", selectedVersion: " + selectedVersion + ", selectedImage: " + selectedImage); jsonObject = fetchSignatureInfo(); return "json"; } else if ("fetchImageList".equals(operation)) { log.info("operation: " + operation); jsonObject = fetchImageList(); return "json"; } else if ("fetchSignatureList".equals(operation)) { log.info("operation: " + operation); jsonObject = fetchSignatureList(); return "json"; } else if ("distributedDownloadList".equals(operation)) { log.info("execute", "operation:" + operation); Set<Long> selectedImageIds = getCurrentSelectedBoIds(AH_DOWNLOAD_IMAGE); storeIdListToSession(UPDATE_IMAGE_SELECTED_IDs, selectedImageIds, getPageIds()); jsonObject = getDistributedDownloadList(); return "json"; } else if ("saveSelectedDistServer".equals(operation)) { log.info("execute", "operation:" + operation); return "json"; } // else if("uploadMsg".equals(operation)){ // log.info("execute", "operation:" + operation); // jsonObject = getUploadWaitingMessage(); // return "json"; // } else if ("updateOptionEx".equals(operation)) { return "updateOptionEx"; } else if ("updateOptionJson".equals(operation)) { return "updateOptionJson"; } else if ("checkSelectedNWPolicy".equals(operation)) { jsonObject = new JSONObject(); if (selectedNWPolicy == null) { jsonObject.put("t", false); jsonObject.put("errorMsg", "Update selected Network Policy error"); } jsonObject.put(JSON_RESULT_TYPE_KEY, operation + JSON_RESULT_TYPE_SUFFIX); Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_SCRIPT_WIZARD); for (Long hiveApId : selectedConfigIds) { HiveAp hiveApBo = QueryUtil.findBoById(HiveAp.class, hiveApId, this); if (!hiveApBo.getConfigTemplate().getId().equals(selectedNWPolicy) && hiveApBo.getDeviceType() != HiveAp.Device_TYPE_VPN_GATEWAY) { jsonObject.put("t", true); jsonObject.put("update", true); return "json"; } } jsonObject.put("t", true); jsonObject.put("update", false); return "json"; } else if ("updateNetworkPolicy".equals(operation)) { jsonObject = new JSONObject(); jsonObject.put(JSON_RESULT_TYPE_KEY, operation + JSON_RESULT_TYPE_SUFFIX); if (selectedNWPolicy == null) { jsonObject.put("t", false); jsonObject.put("errorMsg", "Update selected Network Policy error"); } Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_SCRIPT_WIZARD); Set<Long> hiveApsNWPolicyChg = new HashSet<>(); List<Long> ignoreList = new ArrayList<>(); StringBuffer ignoreMsg = new StringBuffer(""); ConfigTemplate nwPolicyBo = QueryUtil.findBoById(ConfigTemplate.class, selectedNWPolicy); for (Long hiveApId : selectedConfigIds) { HiveAp hiveApBo = QueryUtil.findBoById(HiveAp.class, hiveApId, this); if (hiveApBo.getDeviceType() != HiveAp.Device_TYPE_VPN_GATEWAY && !hiveApBo.getConfigTemplate().getId().equals(selectedNWPolicy)) { if (isMatchingForDeviceAndNetworkPolicy(hiveApBo, nwPolicyBo, ignoreMsg)) { hiveApBo.setConfigTemplate(nwPolicyBo); //fix bug 22808 start // generate realm name when network policy changes Long topologyMapId = hiveApBo.getMapContainer() == null ? null : hiveApBo.getMapContainer().getId(); String realmName = HiveApAction.generateRealmName(nwPolicyBo.getId(), topologyMapId, hiveApBo.isLockRealmName(), hiveApBo.getRealmName()); hiveApBo.setRealmName(realmName); // end QueryUtil.updateBo(hiveApBo); hiveApsNWPolicyChg.add(hiveApId); //update device network history data final Long vHMdomain = hiveApBo.getOwner().getId(); String[] tags = null; List<String> tagsStr = new ArrayList<>(); if (null != hiveApBo.getClassificationTag1() && !"".equals(hiveApBo.getClassificationTag1())) { tagsStr.add(hiveApBo.getClassificationTag1()); } if (null != hiveApBo.getClassificationTag2() && !"".equals(hiveApBo.getClassificationTag2())) { tagsStr.add(hiveApBo.getClassificationTag2()); } if (null != hiveApBo.getClassificationTag3() && !"".equals(hiveApBo.getClassificationTag3())) { tagsStr.add(hiveApBo.getClassificationTag3()); } if (null != tagsStr && tagsStr.size() > 0) { tags = new String[tagsStr.size()]; tagsStr.toArray(tags); } if (hiveApBo.getMapContainer() == null) { String sql = "select id from map_node where parent_map_id = " + "(select id from map_node where parent_map_id is null) and owner=" + vHMdomain; List<?> list = QueryUtil.executeNativeQuery(sql, 1); if (!list.isEmpty()) { NetworkDeviceConfigTracking.topologyChanged(Calendar.getInstance(), vHMdomain, hiveApBo.getMacAddress(), hiveApBo.getTimeZoneOffset(), new long[] { Long.parseLong(list.get(0).toString()) }, tags); } } else { NetworkDeviceConfigTracking.topologyChanged(Calendar.getInstance(), vHMdomain, hiveApBo.getMacAddress(), hiveApBo.getTimeZoneOffset(), new long[] { hiveApBo.getMapContainer().getId() }, tags); //TODO topologyGroupPkFromTop(exclusive)ToBottom(inclusive) } } else { ignoreList.add(hiveApId); } } } MgrUtil.setSessionAttribute(UPDATE_HIVEAP_NETWORKPOLICY_CHANGED, hiveApsNWPolicyChg); jsonObject.put("t", true); jsonObject.put("ignore", ignoreList); if (!"".equals(ignoreMsg.toString())) { jsonObject.put("ignoreMsg", ignoreMsg.toString()); } return "json"; } else if ("rebootHiveAPs".equals(operation)) { String errorMsg = null; if (generateUpdateList() && addToUploadList()) { removeSessionAttrs(); } else { errorMsg = getAllActionErrorMsg(); } if (this.isJsonMode()) { jsonObject = new JSONObject(); if (errorMsg != null) { jsonObject.put("r", false); jsonObject.put("m", errorMsg); } else { jsonObject.put("r", true); } return "json"; } else { return UPDATE_RESULT_LIST; } } else if ("getDeviceCounts".equals(operation)) { jsonObject = new JSONObject(); jsonObject.put(JSON_RESULT_TYPE_KEY, operation + JSON_RESULT_TYPE_SUFFIX); //get all devices Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_REBOOT); jsonObject.put("all", selectedConfigIds == null ? 0 : selectedConfigIds.size()); //get image upgrade devices Map<Long, String> lowerDeviceMap = getSimpleUpdateImageIds(selectedConfigIds, false); jsonObject.put("lowerImage", lowerDeviceMap == null ? 0 : lowerDeviceMap.size()); //get image upgrade devices Map<Long, String> forceDeviceMap = getSimpleUpdateImageIds(selectedConfigIds, true); jsonObject.put("forceImage", forceDeviceMap == null ? 0 : forceDeviceMap.size()); String imageNote = getSimpleImageUpdateNotes(selectedConfigIds); if (StringUtils.isEmpty(imageNote)) { jsonObject.put("imageWarning", MgrUtil.getResourceString("geneva_06.update.ui.image.desc")); } else { jsonObject.put("imageWarning", imageNote); } //clear session removeSessionAttrs(); jsonObject.put("t", true); return "json"; } else if ("getRebootDevices".equals(operation)) { jsonObject = new JSONObject(); jsonObject.put("t", true); jsonObject.put(JSON_RESULT_TYPE_KEY, operation + JSON_RESULT_TYPE_SUFFIX); //get all devices Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_REBOOT); Map<Long, HiveAp> rebootAps = getSimpleUpdateRebootDevices(selectedConfigIds); jsonObject.put("counts", rebootAps == null ? 0 : rebootAps.size()); JSONArray jArray = new JSONArray(); jsonObject.put("names", jsonArray); for (HiveAp ap : rebootAps.values()) { jArray.put(ap.getHostName()); } //clear session removeSessionAttrs(); return "json"; } else if ("checkConnectStatus".equals(operation)) { Set<Long> selectedConfigIds = getCurrentSelectedBoIds(AH_DOWNLOAD_SCRIPT_WIZARD); jsonObject = getConnectionStatusCheckRes(selectedConfigIds); //clear session removeSessionAttrs(); return "json"; } else if (baseOperation()) { String listType = getStringSessionAttribute(UPDATE_LIST_TYPE); if (null == listType) { removeSessionAttrs(); return "managedHiveAps"; } else { preparePage(listType); return listType; } } else { removeSessionAttrs(); return "managedHiveAps"; } } catch (Exception e) { setL3Features(null); log.error("prepareActionError", MgrUtil.getUserMessage(e), e); addActionPermanentErrorMsg(MgrUtil.getUserMessage(e)); return "managedHiveAps"; } }
From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java
private CTEClause findCTEFromName(QB qb, String cteName) { StringBuilder qId = new StringBuilder(); if (qb.getId() != null) { qId.append(qb.getId());/*from w w w . j a v a 2 s .com*/ } while (qId.length() > 0) { String nm = qId + ":" + cteName; CTEClause cte = aliasToCTEs.get(nm); if (cte != null) { return cte; } int lastIndex = qId.lastIndexOf(":"); lastIndex = lastIndex < 0 ? 0 : lastIndex; qId.setLength(lastIndex); } return aliasToCTEs.get(cteName); }
From source file:forge.game.card.Card.java
private StringBuilder abilityTextInstantSorcery(CardState state) { final StringBuilder sb = new StringBuilder(); // Give spellText line breaks for easier reading sb.append(text.replaceAll("\\\\r\\\\n", "\r\n")); // NOTE:/* www . ja v a 2 s.c o m*/ if (sb.toString().contains(" (NOTE: ")) { sb.insert(sb.indexOf("(NOTE: "), "\r\n"); } if (sb.toString().contains("(NOTE: ") && sb.toString().endsWith(".)") && !sb.toString().endsWith("\r\n")) { sb.append("\r\n"); } // I think SpellAbilities should be displayed after Keywords // Add SpellAbilities for (final SpellAbility element : state.getSpellAbilities()) { sb.append(formatSpellAbility(element)); } // Add Keywords final List<String> kw = getKeywords(state); // Triggered abilities for (final Trigger trig : state.getTriggers()) { if (!trig.isSecondary()) { sb.append(trig.toString()).append("\r\n"); } } // Replacement effects for (final ReplacementEffect replacementEffect : state.getReplacementEffects()) { sb.append(replacementEffect.toString()).append("\r\n"); } // static abilities for (final StaticAbility stAb : state.getStaticAbilities()) { final String stAbD = stAb.toString(); if (!stAbD.equals("")) { sb.append(stAbD).append("\r\n"); } } // TODO A lot of these keywords should really show up before the SAs // keyword descriptions for (final String keyword : kw) { if ((keyword.startsWith("Ripple") && !sb.toString().contains("Ripple")) || (keyword.startsWith("Dredge") && !sb.toString().contains("Dredge")) || (keyword.startsWith("CARDNAME is ") && !sb.toString().contains("CARDNAME is "))) { sb.append(keyword.replace(":", " ")).append("\r\n"); } else if ((keyword.startsWith("Madness") && !sb.toString().contains("Madness")) || (keyword.startsWith("Recover") && !sb.toString().contains("Recover")) || (keyword.startsWith("Miracle") && !sb.toString().contains("Miracle"))) { String[] parts = keyword.split(":"); sb.append(parts[0]).append(" ").append(ManaCostParser.parse(parts[1])).append("\r\n"); } else if (keyword.equals("CARDNAME can't be countered.") || keyword.startsWith("May be played") || keyword.startsWith("Conspire") || keyword.startsWith("Cascade") || keyword.startsWith("Wither") || (keyword.startsWith("Epic") && !sb.toString().contains("Epic")) || (keyword.startsWith("Split second") && !sb.toString().contains("Split second")) || (keyword.startsWith("Devoid"))) { sb.append(keyword).append("\r\n"); } else if (keyword .equals("You may cast CARDNAME as though it had flash if you pay 2 more to cast it.")) { sb.append(keyword).append("\r\n"); } else if (keyword.startsWith("Flashback")) { sb.append("Flashback"); if (keyword.contains(" ")) { final Cost fbCost = new Cost(keyword.substring(10), true); if (!fbCost.isOnlyManaCost()) { sb.append(" -"); } sb.append(" ").append(fbCost.toString()).delete(sb.length() - 2, sb.length()); if (!fbCost.isOnlyManaCost()) { sb.append("."); } } sb.append("\r\n"); } else if (keyword.startsWith("Splice")) { final Cost cost = new Cost(keyword.substring(19), false); sb.append("Splice onto Arcane ").append(cost.toSimpleString()).append("\r\n"); } else if (keyword.startsWith("Buyback")) { final Cost cost = new Cost(keyword.substring(8), false); sb.append("Buyback ").append(cost.toSimpleString()); sb.append( " (You may pay an additional cost as you cast CARDNAME. If you do, put CARDNAME back into your hand as it resolves.)"); sb.append("\r\n"); } else if (keyword.startsWith("Entwine")) { final Cost cost = new Cost(keyword.substring(8), false); sb.append("Entwine ").append(cost.toSimpleString()); sb.append(" (Choose both if you pay the entwine cost.)"); sb.append("\r\n"); } else if (keyword.startsWith("Multikicker")) { if (!keyword.endsWith("Generic")) { final Cost cost = new Cost(keyword.substring(7), false); sb.append("Multikicker ").append(cost.toSimpleString()).append("\r\n"); } } else if (keyword.startsWith("Kicker")) { if (!keyword.endsWith("Generic")) { final Cost cost = new Cost(keyword.substring(7), false); sb.append("Kicker ").append(cost.toSimpleString()).append("\r\n"); } } else if (keyword.startsWith("AlternateAdditionalCost")) { final String costString1 = keyword.split(":")[1]; final String costString2 = keyword.split(":")[2]; final Cost cost1 = new Cost(costString1, false); final Cost cost2 = new Cost(costString2, false); sb.append("As an additional cost to cast ").append(state.getName()).append(", ") .append(cost1.toSimpleString()).append(" or pay ").append(cost2.toSimpleString()) .append(".\r\n"); } else if (keyword.startsWith("Storm")) { if (sb.toString().contains("Target") || sb.toString().contains("target")) { sb.insert(sb.indexOf( "Storm (When you cast this spell, copy it for each spell cast before it this turn.") + 81, " You may choose new targets for the copies."); } } else if (keyword.startsWith("Replicate") && !sb.toString().contains("you paid its replicate cost.")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append(keyword); sb.append(" (When you cast this spell, copy it for each time you paid its replicate cost."); if (sb.toString().contains("Target") || sb.toString().contains("target")) { sb.append(" You may choose new targets for the copies."); } sb.append(")\r\n"); } else if (keyword.startsWith("Haunt")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append("Haunt ("); if (state.getType().isCreature()) { sb.append("When this creature dies, exile it haunting target creature."); } else { sb.append("When this spell card is put into a graveyard after resolving, "); sb.append("exile it haunting target creature."); } sb.append(")\r\n"); } else if (keyword.equals("Convoke")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append( "Convoke (Each creature you tap while casting this spell pays for {1} or one mana of that creature's color.)\r\n"); } else if (keyword.equals("Delve")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append( "Delve (Each card you exile from your graveyard while casting this spell pays for {1}.)\r\n"); } else if (keyword.endsWith(" offering")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } String offeringType = keyword.split(" ")[0]; sb.append(keyword); sb.append(" (You may cast this card any time you could cast an instant by sacrificing a "); sb.append(offeringType); sb.append("and paying the difference in mana costs between this and the sacrificed "); sb.append(offeringType); sb.append(". Mana cost includes color.)"); } else if (keyword .equals("Remove CARDNAME from your deck before playing if you're not playing for ante.")) { if (sb.toString().endsWith("\r\n\r\n")) { sb.delete(sb.lastIndexOf("\r\n"), sb.lastIndexOf("\r\n") + 3); } sb.append("Remove CARDNAME from your deck before playing if you're not playing for ante.\r\n"); } else if (keyword.equals("Rebound")) { sb.append(keyword).append( " (If you cast this spell from your hand, exile it as it resolves. At the beginning of your next upkeep, you may cast this card from exile without paying its mana cost.)\r\n"); } } return sb; }