List of usage examples for java.lang StringBuffer setLength
@Override public synchronized void setLength(int newLength)
From source file:org.openecomp.sdc.ci.tests.execute.imports.CsarUtilsTest.java
private void validateServiceCsar(Component certifiedVFC1, Component certifiedVFC2, Service fetchedService, byte[] resultByte, int toscaEntryIndexToPass, int generatorEntryIndexToPass, int deploymentArtifactIndexToPass) { // TODO Test to validate everything is right (comment out after testing) /*/*ww w. j av a2s . c om*/ * try { FileUtils.writeByteArrayToFile(new File("c:/TestCSAR/" + fetchedService.getName() + ".zip"), resultByte); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); } */ try (ByteArrayInputStream ins = new ByteArrayInputStream(resultByte); ZipInputStream zip = new ZipInputStream(ins);) { String resourceYaml = null; byte[] buffer = new byte[1024]; ZipEntry nextEntry = zip.getNextEntry(); StringBuffer sb = new StringBuffer(); int len; while ((len = zip.read(buffer)) > 0) { sb.append(new String(buffer, 0, len)); } assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta")); YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); int toscaEntryIndex = 0; int generatorEntryIndex = 0; int deploymentArtifactIndex = 0; String fileName = null; ArtifactDefinition artifactDefinition; Component componentToValidate = null; artifactDefinition = fetchedService.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); String serviceFileName = artifactDefinition.getArtifactName(); artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); String vfc1FileName = artifactDefinition.getArtifactName(); artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE); String vfc2FileName = artifactDefinition.getArtifactName(); while ((nextEntry = zip.getNextEntry()) != null) { sb.setLength(0); while ((len = zip.read(buffer)) > 0) { sb.append(new String(buffer, 0, len)); } String entryName = nextEntry.getName(); resourceYaml = sb.toString(); if (entryName.contains(serviceFileName)) { componentToValidate = fetchedService; fileName = "Definitions/" + serviceFileName; assertEquals("Validate entry Name", (fileName), nextEntry.getName()); assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); validateContent(resourceYaml, componentToValidate); ++toscaEntryIndex; continue; } if (entryName.contains(vfc1FileName)) { componentToValidate = certifiedVFC1; fileName = "Definitions/" + vfc1FileName; assertEquals("Validate entry Name", (fileName), nextEntry.getName()); assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); validateContent(resourceYaml, componentToValidate); ++toscaEntryIndex; continue; } if (entryName.contains(vfc2FileName)) { componentToValidate = certifiedVFC2; fileName = "Definitions/" + vfc2FileName; assertEquals("Validate entry Name", (fileName), nextEntry.getName()); assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes())); validateContent(resourceYaml, componentToValidate); ++toscaEntryIndex; continue; } if (entryName.contains(".xml") && !entryName.startsWith("Artifacts/AAI")) { ++deploymentArtifactIndex; continue; } if (entryName.startsWith("Artifacts/AAI")) { ++generatorEntryIndex; continue; } assertTrue("Unexpected entry: " + entryName, true); } assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex); assertEquals("Validate amount of generated AAI artifacts", generatorEntryIndexToPass, generatorEntryIndex); assertEquals("Validate amount of generated Deployment artifacts", deploymentArtifactIndexToPass, deploymentArtifactIndex); ins.close(); zip.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:helma.framework.core.RequestEvaluator.java
/** * Check if an action with a given name is defined for a scripted object. If it is, * return the action's function name. Otherwise, return null. *///w w w . java 2s .c o m public String getAction(Object obj, String action, RequestTrans req) { if (obj == null) return null; if (action == null) action = "main"; StringBuffer buffer = new StringBuffer(action).append("_action"); // record length so we can check without method // afterwards for GET, POST, HEAD requests int length = buffer.length(); if (req.checkXmlRpc()) { // append _methodname buffer.append("_xmlrpc"); if (scriptingEngine.hasFunction(obj, buffer.toString(), false)) { // handle as XML-RPC request req.setMethod(RequestTrans.XMLRPC); return buffer.toString(); } // cut off method in case it has been appended buffer.setLength(length); } String method = req.getMethod(); // append HTTP method to action name if (method != null) { // append _methodname buffer.append('_').append(method.toLowerCase()); if (scriptingEngine.hasFunction(obj, buffer.toString(), false)) return buffer.toString(); // cut off method in case it has been appended buffer.setLength(length); } // if no method specified or "ordinary" request try action without method if (method == null || "GET".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method)) { if (scriptingEngine.hasFunction(obj, buffer.toString(), false)) return buffer.toString(); } return null; }
From source file:com.clustercontrol.hub.view.action.LogTransferDisableAction.java
@Override public Object execute(ExecutionEvent event) throws ExecutionException { this.window = HandlerUtil.getActiveWorkbenchWindow(event); // In case this action has been disposed if (null == this.window || !isEnabled()) { return null; }//from w ww . j av a 2s . c o m // ??? this.viewPart = HandlerUtil.getActivePart(event); if (!(viewPart instanceof TransferView)) { return null; } TransferView logTransferView = null; try { logTransferView = (TransferView) viewPart.getAdapter(TransferView.class); } catch (Exception e) { m_log.info("execute " + e.getMessage()); return null; } if (logTransferView == null) { return null; } StructuredSelection selection = null; if (logTransferView.getLogTransferComposite().getTableViewer() .getSelection() instanceof StructuredSelection) { selection = (StructuredSelection) logTransferView.getLogTransferComposite().getTableViewer() .getSelection(); } if (selection == null) { return null; } List<?> sList = (List<?>) selection.toList(); Map<String, List<String>> transferIdMap = new ConcurrentHashMap<String, List<String>>(); for (Object obj : sList) { List<?> list = (List<?>) obj; String managerName = null; if (list == null) { continue; } managerName = (String) list.get(GetTransferTableDefine.MANAGER_NAME); if (transferIdMap.get(managerName) == null) { transferIdMap.put(managerName, new ArrayList<String>()); } } StringBuffer idbuf = new StringBuffer(); int size = 0; for (Object obj : sList) { List<?> list = (List<?>) obj; String transferId = null; String managerName = null; if (list != null) { transferId = (String) list.get(GetTransferTableDefine.TRANSFER_ID); managerName = (String) list.get(GetTransferTableDefine.MANAGER_NAME); transferIdMap.get(managerName).add(transferId); if (size > 0) { idbuf.append(", "); } idbuf.append(transferId); size++; } } if (MessageDialog.openConfirm(null, Messages.getString("confirmed"), Messages.getString("message.hub.log.transfer.confirm.action", new Object[] { Messages.getString("hub.log.transfer.id"), Messages.getString("hub.log.transfer.disable.setting"), idbuf.toString() })) == false) { return null; } StringBuffer sucTransferIds = new StringBuffer(); StringBuffer failTransferIds = new StringBuffer(); for (Map.Entry<String, List<String>> entry : transferIdMap.entrySet()) { String managerName = entry.getKey(); HubEndpointWrapper wrapper = HubEndpointWrapper.getWrapper(managerName); for (String transferId : entry.getValue()) { try { TransferInfo info = wrapper.getTransferInfo(transferId); info.setValidFlg(false); try { wrapper.modifyTransferInfo(info); sucTransferIds.append(transferId + "(" + managerName + "), "); } catch (InvalidRole_Exception | InvalidUserPass_Exception | InvalidSetting_Exception | LogTransferNotFound_Exception e) { m_log.debug("execute modifyLogTransfer, " + e.getMessage()); failTransferIds.append(transferId + ", "); } } catch (HinemosUnknown_Exception | InvalidRole_Exception | InvalidUserPass_Exception e) { m_log.debug("execute getLogTransfer, " + e.getMessage()); failTransferIds.append(transferId + ", "); } } } //????? if (sucTransferIds.length() > 0) { sucTransferIds.setLength(sucTransferIds.length() - 2); MessageDialog.openInformation(null, Messages.getString("successful"), Messages.getString("message.hub.log.transfer.action.result", new Object[] { Messages.getString("hub.log.transfer.id"), Messages.getString("hub.log.transfer.disable.setting"), Messages.getString("successful"), sucTransferIds })); } //???? if (failTransferIds.length() > 0) { failTransferIds.setLength(failTransferIds.length() - 2); MessageDialog.openError(null, Messages.getString("failed"), Messages.getString("message.hub.log.transfer.action.result", new Object[] { Messages.getString("hub.log.transfer.id"), Messages.getString("hub.log.transfer.disable.setting"), Messages.getString("failed"), failTransferIds })); } logTransferView.update(); return null; }
From source file:edu.cornell.mannlib.vitro.webapp.search.documentBuilding.IndividualToSearchDocument.java
protected void addAllText(Individual ind, SearchInputDocument doc, StringBuffer classPublicNames, StringBuffer objectNames) { String t = null;//from www .jav a 2 s.c om //ALLTEXT, all of the 'full text' StringBuffer allTextValue = new StringBuffer(); try { //collecting data property statements List<DataPropertyStatement> dataPropertyStatements = ind.getDataPropertyStatements(); if (dataPropertyStatements != null) { Iterator<DataPropertyStatement> dataPropertyStmtIter = dataPropertyStatements.iterator(); while (dataPropertyStmtIter.hasNext()) { DataPropertyStatement dataPropertyStmt = dataPropertyStmtIter.next(); if (dataPropertyStmt.getDatapropURI().equals(label)) { // we don't want label to be added to alltext continue; } allTextValue.append(" "); allTextValue.append(((t = dataPropertyStmt.getData()) == null) ? "" : t); } } } catch (JenaException je) { //VIVO-15 Trap for characters that cause search indexing to abort log.error(String.format("Continuing to index %s but could not get all dataproperties because %s", ind.getURI(), je.getMessage())); } allTextValue.append(objectNames.toString()); allTextValue.append(' '); allTextValue.append(classPublicNames); try { String stripped = Jsoup.parse(allTextValue.toString()).text(); allTextValue.setLength(0); allTextValue.append(stripped); } catch (Exception e) { log.debug("Could not strip HTML during search indexing. " + e); } String alltext = allTextValue.toString(); doc.addField(ALLTEXT, alltext); doc.addField(ALLTEXTUNSTEMMED, alltext); }
From source file:com.pureinfo.studio.db.xls2srm.ref.ResCenterMapRef.java
public Object convert(DolphinObject _old, DolphinObject _new, String _sFromProperty, String _sToProperty, ISession _fromSession, ISession _toSession, EntityMetadata _metadata, String _sKey, String _sToTable) throws PureException { int nImportType = Integer.parseInt(_sToProperty); // // ww w .j a v a 2s. c om if (Xls2srmForm.JUSTFORCHECK == nImportType) return null; String sValue = _old.getStrProperty(_sFromProperty); int nOrgType = 1; if ("".equals(_sFromProperty)) nOrgType = OrganizationConstants.ORG_TYPE_LAB; else nOrgType = OrganizationConstants.ORG_TYPE_RESERCH_CENTER; int nUserId = 0; // if (Xls2srmForm.COVERDATAWHENREPEAT == nImportType || Xls2srmForm.LEAPDATAWHENREPEAT == nImportType) { if (sValue != null && sValue.trim().length() > 0) { // _sKey*.xls.xml<match-properties/>; if (_sKey != null && _sKey.trim().length() > 0) { StringBuffer sbuff = new StringBuffer(); String[] sPropertyNames = StrUtil.split(_sKey, ","); ISRMUserMgr mgr = (ISRMUserMgr) ArkContentHelper.getContentMgrOf(SRMUser.class); for (int i = 0; i < sPropertyNames.length; i++) { sbuff.append(" AND {this.").append(sPropertyNames[i]).append("} = '"); sbuff.append(_new.getProperty(sPropertyNames[i])).append('\''); } String strSQL = sbuff.toString(); if (sbuff.length() > 5) strSQL = strSQL.substring(5); IStatement stat = null; IObjects results = null; try { stat = mgr.createQuery("SELECT {this.id} FROM {this} WHERE " + strSQL, 1); results = stat.executeQuery(false); SRMUser user = (SRMUser) results.next(); results.clear(); stat.clear(false); if (user != null) { nUserId = user.getId(); if (Xls2srmForm.COVERDATAWHENREPEAT == nImportType) { SRMHelper.deleteAllOf(UserOrgMap.class, "userId", nUserId); } } } finally { if (sbuff != null) sbuff.setLength(0); DolphinHelper.clear(results, stat); } } } } // if (sValue != null) { // if (!(Xls2srmForm.LEAPDATAWHENREPEAT == nImportType && nUserId > 0)) { String[] names = StringUtils.split(sValue, ","); IUserOrgMapMgr mapMgr; try { mapMgr = (IUserOrgMapMgr) ArkContentHelper.getContentMgrOf(UserOrgMap.class); LocalContextHelper.currentSession().autoGenerateProperty(_new, "id"); } catch (PureException e) { e.printStackTrace(); return null; } int nId = _new.getIntProperty("id", -1); if (Xls2srmForm.COVERDATAWHENREPEAT == nImportType) { if (nUserId > 0) { nId = nUserId; } } IContentMgr mgr = null; if (nOrgType == OrganizationConstants.ORG_TYPE_LAB) { mgr = ArkContentHelper.getContentMgrOf(Institute.class); } else { mgr = ArkContentHelper.getContentMgrOf(ResearchCenter.class); } for (int i = 0; i < names.length; i++) { String sName = names[i].trim(); UserOrgMap uo = new UserOrgMap(); uo.setUserId(nId); uo.setOrgType(nOrgType); uo.setCreateUser("system"); try { ArkContent obj; IObjects result = null; IStatement query = null; try { String strSQL; if (nOrgType == OrganizationConstants.ORG_TYPE_LAB) { strSQL = "SELECT * FROM {this} WHERE {this.name}=? AND {this.type}=1"; } else { strSQL = "SELECT * FROM {this} WHERE {this.name}=?"; } query = mgr.createQuery(strSQL, 1); query.setString(0, sName); result = query.executeQuery(); obj = (ArkContent) result.next(); } finally { DolphinHelper.clear(result, query); } if (obj != null) { uo.setOrgId(obj.getId()); } else { uo.setOrgId(0); } mapMgr.save(uo); } catch (PureException e) { e.printStackTrace(System.err); } } return null; } } return null; }
From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java
private void insertCreate(User user, Set<String> attributes, Map<String, Attribute> attrs, Connection con, Map<String, Object> request) throws SQLException, ProvisioningException { int approvalID = 0; if (request.containsKey("APPROVAL_ID")) { approvalID = (Integer) request.get("APPROVAL_ID"); }/*from w w w . j a v a 2 s . c o m*/ Workflow workflow = (Workflow) request.get("WORKFLOW"); StringBuffer insert = new StringBuffer(); insert.append("INSERT INTO ").append(this.userTable).append(" ("); for (String attr : attributes) { if (attrs.get(attr) != null) { getFieldName(attr, insert).append(","); } } insert.setLength(insert.length() - 1); insert.append(") values ("); for (String attr : attributes) { if (attrs.get(attr) != null) { insert.append("?,"); } } insert.setLength(insert.length() - 1); insert.append(")"); PreparedStatement ps = con.prepareStatement(insert.toString(), Statement.RETURN_GENERATED_KEYS); int i = 1; for (String attr : attributes) { if (attrs.get(attr) != null) { Attribute.DataType dataType = attrs.get(attr).getDataType(); switch (dataType) { case string: ps.setString(i, attrs.get(attr).getValues().get(0)); break; case intNum: ps.setInt(i, Integer.parseInt(attrs.get(attr).getValues().get(0))); break; case longNum: ps.setLong(i, Long.parseLong(attrs.get(attr).getValues().get(0))); break; case date: ps.setDate(i, new Date(ISODateTimeFormat.date() .parseDateTime(attrs.get(attr).getValues().get(0)).getMillis())); break; case timeStamp: ps.setTimestamp(i, new Timestamp(ISODateTimeFormat.dateTime() .parseDateTime(attrs.get(attr).getValues().get(0)).getMillis())); break; } i++; } } ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); int id; if (rs.next() && !this.driver.contains("oracle")) { id = (int) rs.getInt(1); } else { StringBuffer select = new StringBuffer(); select.append("SELECT "); this.getFieldName(this.userPrimaryKey, select).append(" FROM ").append(this.userTable) .append(" WHERE "); this.getFieldName(this.userName, select).append("=?"); PreparedStatement getUserId = con.prepareStatement(select.toString()); //con.prepareStatement( + this.userPrimaryKey + " FROM " + this.userTable + " WHERE " + this.userName + "=?"); getUserId.setString(1, user.getUserID()); ResultSet userResult = getUserId.executeQuery(); userResult.next(); id = (int) userResult.getInt(this.userPrimaryKey); userResult.close(); getUserId.close(); } this.cfgMgr.getProvisioningEngine().logAction(this.name, true, ActionType.Add, approvalID, workflow, "userName", user.getUserID()); for (String attr : attributes) { if (attrs.get(attr) != null) { this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, attr, attrs.get(attr).getValues().get(0)); } } if (user.getGroups().size() > 0) { switch (this.groupMode) { case None: break; case One2Many: insert.setLength(0); insert.append("INSERT INTO ").append(this.groupTable).append(" (").append(this.groupUserKey) .append(",").append(this.groupName).append(") VALUES (?,?)"); ps = con.prepareStatement(insert.toString()); for (String groupName : user.getGroups()) { ps.setInt(1, id); ps.setString(2, groupName); ps.executeUpdate(); this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "group", groupName); } break; case Many2Many: many2manySetGroupsCreate(user, insert, con, id, request); break; } } }
From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java
private void many2manySetGroupsCreate(User user, StringBuffer insert, Connection con, int id, Map<String, Object> request) throws SQLException, ProvisioningException { int approvalID = 0; if (request.containsKey("APPROVAL_ID")) { approvalID = (Integer) request.get("APPROVAL_ID"); }//from w ww . j a v a 2 s.c om Workflow workflow = (Workflow) request.get("WORKFLOW"); int i; ResultSet rs; StringBuffer select = new StringBuffer("SELECT "); this.getFieldName(this.groupPrimaryKey, select).append(","); this.getFieldName(this.groupName, select).append(" FROM ").append(this.groupTable).append(" WHERE "); for (String group : user.getGroups()) { this.getFieldName(this.groupName, select).append("=? OR "); } select.setLength(select.length() - 3); PreparedStatement psSearch = con.prepareStatement(select.toString()); i = 1; for (String group : user.getGroups()) { psSearch.setString(i, group); i++; } rs = psSearch.executeQuery(); insert.setLength(0); insert.append("INSERT INTO ").append(this.groupLinkTable).append(" ("); this.getFieldName(this.groupGroupKey, insert).append(","); this.getFieldName(this.groupUserKey, insert).append(") VALUES (?,?)"); PreparedStatement psExec = con.prepareStatement(insert.toString()); while (rs.next()) { psExec.setInt(1, rs.getInt(this.groupPrimaryKey)); psExec.setInt(2, id); psExec.executeUpdate(); this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "group", rs.getString(this.groupName)); } }
From source file:com.clustercontrol.hub.view.action.LogTransferEnableAction.java
@Override public Object execute(ExecutionEvent event) throws ExecutionException { this.window = HandlerUtil.getActiveWorkbenchWindow(event); // In case this action has been disposed if (null == this.window || !isEnabled()) { return null; }//from w w w .j a v a 2s .c om // ??? this.viewPart = HandlerUtil.getActivePart(event); if (!(viewPart instanceof TransferView)) { return null; } TransferView logTransfarView = null; try { logTransfarView = (TransferView) viewPart.getAdapter(TransferView.class); } catch (Exception e) { m_log.info("execute " + e.getMessage()); return null; } if (logTransfarView == null) { return null; } StructuredSelection selection = null; if (logTransfarView.getLogTransferComposite().getTableViewer() .getSelection() instanceof StructuredSelection) { selection = (StructuredSelection) logTransfarView.getLogTransferComposite().getTableViewer() .getSelection(); } if (selection == null) { return null; } List<?> sList = (List<?>) selection.toList(); Map<String, List<String>> transferIdMap = new ConcurrentHashMap<String, List<String>>(); for (Object obj : sList) { List<?> list = (List<?>) obj; String managerName = null; if (list == null) { continue; } managerName = (String) list.get(GetTransferTableDefine.MANAGER_NAME); if (transferIdMap.get(managerName) == null) { transferIdMap.put(managerName, new ArrayList<String>()); } } StringBuffer idbuf = new StringBuffer(); int size = 0; for (Object obj : sList) { List<?> list = (List<?>) obj; String transferId = null; String managerName = null; if (list != null) { transferId = (String) list.get(GetTransferTableDefine.TRANSFER_ID); managerName = (String) list.get(GetTransferTableDefine.MANAGER_NAME); transferIdMap.get(managerName).add(transferId); if (size > 0) { idbuf.append(", "); } idbuf.append(transferId); size++; } } if (MessageDialog.openConfirm(null, Messages.getString("confirmed"), Messages.getString("message.hub.log.transfer.confirm.action", new Object[] { Messages.getString("hub.log.transfer.id"), Messages.getString("hub.log.transfer.enable.setting"), idbuf.toString() })) == false) { return null; } StringBuffer sucTransferIds = new StringBuffer(); StringBuffer failTransferIds = new StringBuffer(); for (Map.Entry<String, List<String>> entry : transferIdMap.entrySet()) { String managerName = entry.getKey(); HubEndpointWrapper wrapper = HubEndpointWrapper.getWrapper(managerName); for (String transferId : entry.getValue()) { try { TransferInfo info = wrapper.getTransferInfo(transferId); info.setValidFlg(true); try { wrapper.modifyTransferInfo(info); sucTransferIds.append(transferId + "(" + managerName + ")" + ", "); } catch (InvalidSetting_Exception | HinemosUnknown_Exception | InvalidRole_Exception | InvalidUserPass_Exception | LogTransferNotFound_Exception e) { m_log.debug("execute modifyLogTransfer, " + e.getMessage()); failTransferIds.append(transferId + ", "); } } catch (HinemosUnknown_Exception | InvalidRole_Exception | InvalidUserPass_Exception e) { m_log.debug("execute getLogTransfer, " + e.getMessage()); failTransferIds.append(transferId + ", "); } } } //????? if (sucTransferIds.length() > 0) { sucTransferIds.setLength(sucTransferIds.length() - 2); MessageDialog.openInformation(null, Messages.getString("successful"), Messages.getString("message.hub.log.transfer.action.result", new Object[] { Messages.getString("hub.log.transfer.id"), Messages.getString("hub.log.transfer.enable.setting"), Messages.getString("successful"), sucTransferIds })); } //???? if (failTransferIds.length() > 0) { failTransferIds.setLength(failTransferIds.length() - 2); MessageDialog.openError(null, Messages.getString("failed"), Messages.getString("message.hub.log.transfer.action.result", new Object[] { Messages.getString("hub.log.transfer.id"), Messages.getString("hub.log.transfer.enable.setting"), Messages.getString("failed"), failTransferIds })); } logTransfarView.update(); return null; }
From source file:edu.arizona.kra.kim.impl.identity.PersonServiceImpl.java
/** * @see org.kuali.rice.kim.api.identity.PersonService#resolvePrincipalNamesToPrincipalIds(org.kuali.rice.krad.bo.BusinessObject, java.util.Map) *//*from w w w. j av a 2 s . c o m*/ @SuppressWarnings("unchecked") @Override public Map<String, String> resolvePrincipalNamesToPrincipalIds(BusinessObject businessObject, Map<String, String> fieldValues) { if (fieldValues == null) { return null; } if (businessObject == null) { return fieldValues; } StringBuffer resolvedPrincipalIdPropertyName = new StringBuffer(); // save off all criteria which are not references to Person properties // leave person properties out so they can be resolved and replaced by this method Map<String, String> processedFieldValues = getNonPersonSearchCriteria(businessObject, fieldValues); for (String propertyName : fieldValues.keySet()) { if (!StringUtils.isBlank(fieldValues.get(propertyName)) // property has a value && isPersonProperty(businessObject, propertyName) // is a property on a Person object ) { // strip off the prefix on the property String personPropertyName = ObjectUtils.getNestedAttributePrimitive(propertyName); // special case - the user ID if (StringUtils.equals(KIMPropertyConstants.Person.PRINCIPAL_NAME, personPropertyName)) { @SuppressWarnings("rawtypes") Class targetBusinessObjectClass = null; BusinessObject targetBusinessObject = null; resolvedPrincipalIdPropertyName.setLength(0); // clear the buffer without requiring a new object allocation on each iteration // get the property name up until the ".principalName" // this should be a reference to the Person object attached to the BusinessObject String personReferenceObjectPropertyName = ObjectUtils.getNestedAttributePrefix(propertyName); // check if the person was nested within another BO under the master BO. If so, go up one more level // otherwise, use the passed in BO class as the target class if (ObjectUtils.isNestedAttribute(personReferenceObjectPropertyName)) { String targetBusinessObjectPropertyName = ObjectUtils .getNestedAttributePrefix(personReferenceObjectPropertyName); targetBusinessObject = (BusinessObject) ObjectUtils.getPropertyValue(businessObject, targetBusinessObjectPropertyName); if (targetBusinessObject != null) { targetBusinessObjectClass = targetBusinessObject.getClass(); resolvedPrincipalIdPropertyName.append(targetBusinessObjectPropertyName).append("."); } else { LOG.error("Could not find target property '" + propertyName + "' in class " + businessObject.getClass().getName() + ". Property value was null."); } } else { // not a nested Person property targetBusinessObjectClass = businessObject.getClass(); targetBusinessObject = businessObject; } if (targetBusinessObjectClass != null) { // use the relationship metadata in the KNS to determine the property on the // host business object to put back into the map now that the principal ID // (the value stored in application tables) has been resolved String propName = ObjectUtils .getNestedAttributePrimitive(personReferenceObjectPropertyName); DataObjectRelationship rel = getBusinessObjectMetaDataService() .getBusinessObjectRelationship(targetBusinessObject, propName); if (rel != null) { String sourcePrimitivePropertyName = rel .getParentAttributeForChildAttribute(KIMPropertyConstants.Person.PRINCIPAL_ID); resolvedPrincipalIdPropertyName.append(sourcePrimitivePropertyName); // get the principal - for translation of the principalName to principalId String principalName = fieldValues.get(propertyName); Principal principal = getIdentityService().getPrincipalByPrincipalName(principalName); if (principal != null) { processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), principal.getPrincipalId()); } else { processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null); try { // if the principalName is bad, then we need to clear out the Person object // and base principalId property // so that their values are no longer accidentally used or re-populate // the object ObjectUtils.setObjectProperty(targetBusinessObject, resolvedPrincipalIdPropertyName.toString(), null); ObjectUtils.setObjectProperty(targetBusinessObject, propName, null); ObjectUtils.setObjectProperty(targetBusinessObject, propName + ".principalName", principalName); } catch (Exception ex) { LOG.error( "Unable to blank out the person object after finding that the person with the given principalName does not exist.", ex); } } } else { LOG.error("Missing relationship for " + propName + " on " + targetBusinessObjectClass.getName()); } } else { // no target BO class - the code below probably will not work processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null); } } // if the property does not seem to match the definition of a Person property but it // does end in principalName then... // this is to handle the case where the user ID is on an ADD line - a case excluded from isPersonProperty() } else if (propertyName.endsWith("." + KIMPropertyConstants.Person.PRINCIPAL_NAME)) { // if we're adding to a collection and we've got the principalName; let's populate universalUser String principalName = fieldValues.get(propertyName); if (StringUtils.isNotEmpty(principalName)) { String containerPropertyName = propertyName; if (containerPropertyName.startsWith(KRADConstants.MAINTENANCE_ADD_PREFIX)) { containerPropertyName = StringUtils.substringAfter(propertyName, KRADConstants.MAINTENANCE_ADD_PREFIX); } // get the class of the object that is referenced by the property name // if this is not true then there's a principalName collection or primitive attribute // directly on the BO on the add line, so we just ignore that since something is wrong here if (ObjectUtils.isNestedAttribute(containerPropertyName)) { // the first part of the property is the collection name String collectionName = StringUtils.substringBefore(containerPropertyName, "."); // what is the class held by that collection? // JHK: I don't like this. This assumes that this method is only used by the maintenance // document service. If that will always be the case, this method should be moved over there. Class<? extends BusinessObject> collectionBusinessObjectClass = getMaintenanceDocumentDictionaryService() .getCollectionBusinessObjectClass(getMaintenanceDocumentDictionaryService() .getDocumentTypeName(businessObject.getClass()), collectionName); if (collectionBusinessObjectClass != null) { // we are adding to a collection; get the relationships for that object; // is there one for personUniversalIdentifier? List<DataObjectRelationship> relationships = getBusinessObjectMetaDataService() .getBusinessObjectRelationships(collectionBusinessObjectClass); // JHK: this seems like a hack - looking at all relationships for a BO does not guarantee that we get the right one // JHK: why not inspect the objects like above? Is it the property path problems because of the .add. portion? for (DataObjectRelationship rel : relationships) { String parentAttribute = rel.getParentAttributeForChildAttribute( KIMPropertyConstants.Person.PRINCIPAL_ID); if (parentAttribute == null) { continue; } // there is a relationship for personUserIdentifier; use that to find the universal user processedFieldValues.remove(propertyName); String fieldPrefix = StringUtils .substringBeforeLast(StringUtils.substringBeforeLast(propertyName, "." + KIMPropertyConstants.Person.PRINCIPAL_NAME), "."); String relatedPrincipalIdPropertyName = fieldPrefix + "." + parentAttribute; // KR-683 Special handling for extension objects if (EXTENSION.equals(StringUtils.substringAfterLast(fieldPrefix, ".")) && EXTENSION.equals(StringUtils.substringBefore(parentAttribute, "."))) { relatedPrincipalIdPropertyName = fieldPrefix + "." + StringUtils.substringAfter(parentAttribute, "."); } String currRelatedPersonPrincipalId = processedFieldValues .get(relatedPrincipalIdPropertyName); if (StringUtils.isBlank(currRelatedPersonPrincipalId)) { Principal principal = getIdentityService() .getPrincipalByPrincipalName(principalName); if (principal != null) { processedFieldValues.put(relatedPrincipalIdPropertyName, principal.getPrincipalId()); } else { processedFieldValues.put(relatedPrincipalIdPropertyName, null); } } } // relationship loop } else { if (LOG.isDebugEnabled()) { LOG.debug( "Unable to determine class for collection referenced as part of property: " + containerPropertyName + " on " + businessObject.getClass().getName()); } } } else { if (LOG.isDebugEnabled()) { LOG.debug("Non-nested property ending with 'principalName': " + containerPropertyName + " on " + businessObject.getClass().getName()); } } } } } return processedFieldValues; }
From source file:org.openadaptor.auxil.expression.ExpressionTokenReader.java
/** * Fetch the next token from the reader. Logic is crudely as follows: <code> * skip whitespace/*from w w w . j ava2s . c o m*/ * if not end of data try these in order: * (1) See if it is a number. If it is, check if it had a decimal point. * Return a value token with a Double or Long accordingly. * * (2) If current char is '{' Then read a variable (possibly with * nested variables enclosed in '{' '}') to a corresponding '}' * Return a value token with a Variable. * * (3)Check if it is an operator. If it is, return it. * * (4)See is it a literal, enclosed in quotes. If it is, read until a * quote which matches the opening quote. Return value token with literal. * * (5)Must be an operator alias. Read it, and see if it is. Throw exception if not. * Return corresponding operator token. * * </code> Step (5) may be relaxed to allow other values which might correspond to, say, user supplied function * implementation or simiar. * * @return The next parsed <code>ExpressionToken</code> * @throws ExpressionException */ private ExpressionToken nextToken() throws ExpressionException { // log.debug("nextToken() ch is ["+ch+"] "+(char)ch); ExpressionToken token = ExpressionToken.EOF; // Skip whitespace try { while (isWhitespace(ch)) { ch = reader.read(); } if (ch >= 0) { // Not end of input sb.setLength(0); // Check if it is a number first. if (isNumeric(ch)) {// Get thee a number // log.debug("Reading a number"); boolean decimal = false; while (isNumeric(ch)) { if (ch == '.') { if (decimal) { // Already have a decimal point. break; } else { decimal = true; } } sb.append((char) ch); ch = reader.read(); } if (decimal) { return new ExpressionToken(new Double(sb.toString())); } else { return new ExpressionToken(new Long(sb.toString())); } // log.debug("Number is: "+token.value); } // It's not numeric if we get this far. if (ExpressionToken.OP_L_BRACE == ch) { // It's a variable. log.debug("Reading a variable"); int braceCount = 1; StringBuffer sb = new StringBuffer(); sb.append((char) ch); // Add the opening brace. while (braceCount > 0) { ch = reader.read(); switch (ch) { case -1: throw new ExpressionException( "Variable has no closing " + ((char) ExpressionToken.OP_R_BRACE)); // break; case ExpressionToken.OP_L_BRACE: braceCount++; break; case ExpressionToken.OP_R_BRACE: braceCount--; break; default: break; } sb.append((char) ch); } log.debug("Variable name is " + sb.toString()); ch = reader.read(); // Move on. return new ExpressionToken(sb.toString(), false); } // Ok, so it's not a variable either. Try for an operator next. token = ExpressionToken.getOperator(ch); if (token != null) { // Bingo. ch = reader.read(); return token; } // Now we're getting desperate. Get a word. // log.debug("reading a word"); if (isQuote(ch)) { // Need to read quoted word log.debug("Reading quoted word"); int quoteCh = ch; // This is the opening quote. StringBuffer sb = new StringBuffer(); while (((ch = reader.read()) >= 0) && (quoteCh != ch)) { sb.append((char) ch); } if (quoteCh != ch) { throw new ExpressionException("Literal value has no closing quote - " + ((char) quoteCh)); } log.debug("Quoted literal value is " + sb.toString()); ch = reader.read(); // Skip the closing brace. return new ExpressionToken(sb.toString()); } // Not a quoted literal - try for a bog standard literal. while ((ch >= 0) && (ch != ExpressionToken.OP_L_BRACE) && (!isNumeric(ch) && (!isWhitespace(ch))) && (ExpressionToken.getOperator(ch) == null)) { sb.append((char) ch); ch = reader.read(); } String word = sb.toString(); // Look up any operator aliases - eg GE LE etc. token = ExpressionToken.getOperator(word); if (token == null) { // See if there's a registered function. if (allowFunctions) { token = ExpressionToken.getFunction(word); } if (token == null) { throw new ExpressionException("Unrecognised token: " + word); } } } } catch (IOException ioe) { ExpressionTokenReader.log.error("Failed to read a token - " + ioe.toString()); throw new ExpressionException("Failed to read a token - " + ioe.toString(), ioe); } return token; }