List of usage examples for java.util HashMap isEmpty
public boolean isEmpty()
From source file:edu.umass.cs.gigapaxos.PaxosInstanceStateMachine.java
private MessagingTask handleSyncDecisionsPacket(SyncDecisionsPacket syncReply) throws JSONException { int minMissingSlot = syncReply.missingSlotNumbers.get(0); log.log(Level.FINE, "{0} handling sync decisions request {1} when maxCommittedSlot = {2}", new Object[] { this, syncReply.getSummary(), this.paxosState.getMaxCommittedSlot() }); if (this.paxosState.getMaxCommittedSlot() - minMissingSlot < 0) return null; // I am worse than you // get checkpoint if minMissingSlot > last checkpointed slot MessagingTask checkpoint = null;// w ww .j ava 2 s . c om if (minMissingSlot - lastCheckpointSlot(this.paxosState.getSlot(), syncReply.getPaxosID()) <= 0) { checkpoint = handleCheckpointRequest(syncReply); if (checkpoint != null) // only get decisions beyond checkpoint minMissingSlot = ((StatePacket) (checkpoint.msgs[0])).slotNumber + 1; } // try to get decisions from memory first HashMap<Integer, PValuePacket> missingDecisionsMap = new HashMap<Integer, PValuePacket>(); for (PValuePacket pvalue : this.paxosState.getCommitted(syncReply.missingSlotNumbers)) missingDecisionsMap.put(pvalue.slot, pvalue.setNoCoalesce()); // get decisions from database as unlikely to have all of them in memory ArrayList<PValuePacket> missingDecisions = this.paxosManager.getPaxosLogger().getLoggedDecisions( this.getPaxosID(), this.getVersion(), minMissingSlot, /* If maxDecision <= minMissingSlot, sender is probably * doing a creation sync. But we need min < max for the * database query to return nonzero results, so we * adjust up the max if needed. Note that * getMaxCommittedSlot() at this node may not be greater * than minMissingDecision either. For example, the * sender may be all caught up at slot 0 and request a * creation sync for 1 and this node may have committed * up to 1; if so, it should return decision 1. */ syncReply.maxDecisionSlot > minMissingSlot ? syncReply.maxDecisionSlot : Math.max(minMissingSlot + 1, this.paxosState.getMaxCommittedSlot() + 1)); // filter non-missing from database decisions if (syncReply.maxDecisionSlot > minMissingSlot) for (Iterator<PValuePacket> pvalueIterator = missingDecisions.iterator(); pvalueIterator.hasNext();) { PValuePacket pvalue = pvalueIterator.next(); if (!syncReply.missingSlotNumbers.contains(pvalue.slot)) pvalueIterator.remove(); // filter non-missing else pvalue.setNoCoalesce(); // send as-is, no compacting // isRecovery() true only in rollForward assert (!pvalue.isRecovery()); } // copy over database decisions not in memory for (PValuePacket pvalue : missingDecisions) if (!missingDecisionsMap.containsKey(pvalue.slot)) missingDecisionsMap.put(pvalue.slot, pvalue); // replace meta decisions with actual decisions getActualDecisions(missingDecisionsMap); assert (missingDecisionsMap.isEmpty() || missingDecisionsMap.values().toArray(new PaxosPacket[0]).length > 0) : missingDecisions; for (PValuePacket pvalue : missingDecisionsMap.values()) { pvalue.setNoCoalesce(); assert (pvalue.hasRequestValue()); } // the list of missing decisions to be sent MessagingTask unicasts = missingDecisionsMap.isEmpty() ? null : new MessagingTask(syncReply.nodeID, (missingDecisionsMap.values().toArray(new PaxosPacket[0]))); log.log(Level.INFO, "{0} sending {1} missing decision(s) to node {2} in response to {3}", new Object[] { this, unicasts == null ? 0 : unicasts.msgs.length, syncReply.nodeID, syncReply.getSummary() }); if (checkpoint != null) log.log(Level.INFO, "{0} sending checkpoint for slot {1} to node {2} in response to {3}", new Object[] { this, minMissingSlot - 1, syncReply.nodeID, syncReply.getSummary() }); // combine checkpoint and missing decisions in unicasts MessagingTask mtask = // both nonempty => combine (checkpoint != null && unicasts != null && !checkpoint.isEmpty() && !unicasts.isEmpty()) ? mtask = new MessagingTask(syncReply.nodeID, MessagingTask.toPaxosPacketArray(checkpoint.msgs, unicasts.msgs)) : // nonempty checkpoint (checkpoint != null && !checkpoint.isEmpty()) ? checkpoint : // unicasts (possibly also empty or null) unicasts; log.log(Level.FINE, "{0} sending mtask: ", new Object[] { this, mtask }); return mtask; }
From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java
public ActionForward issueNoteSaveJson(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String strNote = request.getParameter("value"); String appointmentNo = request.getParameter("appointment_no"); String providerNo = LoggedInInfo.loggedInInfo.get().loggedInProvider.getProviderNo(); String noteId = request.getParameter("noteId"); String demographicNo = request.getParameter("demographic_no"); String issueCode = request.getParameter("issue_id"); String issueAlphaCode = request.getParameter("issue_code"); String archived = request.getParameter("archived"); Date noteDate = new Date(); strNote = org.apache.commons.lang.StringUtils.trimToNull(strNote); if ((archived == null || !archived.equalsIgnoreCase("true")) && (strNote == null || strNote.equals(""))) return null; CaseManagementNote note = new CaseManagementNote(); if (!noteId.equals("0")) { note = this.caseManagementMgr.getNote(noteId); if ((archived == null || !archived.equalsIgnoreCase("true")) && (request.getParameter("sign") == null || !request.getParameter("sign").equalsIgnoreCase("true")) && note.getNote().equalsIgnoreCase(strNote)) return null; note.setRevision(ConversionUtils.fromIntString(note.getRevision()) + 1 + ""); if (archived != null && archived.equalsIgnoreCase("true")) note.setArchived(true);//from w w w. ja v a2 s . c o m } else { note.setDemographic_no(demographicNo); CaseManagementIssue cIssue; if (issueAlphaCode != null && issueAlphaCode.length() > 0) cIssue = this.caseManagementMgr.getIssueByIssueCode(demographicNo, issueAlphaCode); else cIssue = this.caseManagementMgr.getIssueById(demographicNo, issueCode); Set<CaseManagementIssue> issueSet = new HashSet<CaseManagementIssue>(); Set<CaseManagementNote> noteSet = new HashSet<CaseManagementNote>(); if (cIssue == null) { Issue issue; if (issueAlphaCode != null && issueAlphaCode.length() > 0) issue = this.caseManagementMgr.getIssueByCode(issueAlphaCode); else issue = this.caseManagementMgr.getIssue(issueCode); cIssue = this.newIssueToCIssue(demographicNo, issue, ConversionUtils.fromIntString("10016")); cIssue.setNotes(noteSet); } issueSet.add(cIssue); note.setIssues(issueSet); note.setCreate_date(noteDate); note.setObservation_date(noteDate); note.setRevision("1"); } try { note.setAppointmentNo(ConversionUtils.fromIntString(appointmentNo)); } catch (Exception e) { // No appointment number set for this encounter } if (strNote != null) note.setNote(strNote); note.setProviderNo(providerNo); note.setProvider(LoggedInInfo.loggedInInfo.get().loggedInProvider); if (request.getParameter("sign") != null && request.getParameter("sign").equalsIgnoreCase("true")) { note.setSigning_provider_no(providerNo); note.setSigned(true); if (request.getParameter("appendSignText") != null && request.getParameter("appendSignText").equalsIgnoreCase("true")) { SimpleDateFormat dt = new SimpleDateFormat("dd-MMM-yyyy H:mm", Locale.ENGLISH); Date now = new Date(); ResourceBundle props = ResourceBundle.getBundle("oscarResources", Locale.ENGLISH); ProviderDao providerDao = (ProviderDao) SpringUtils.getBean("providerDao"); String providerName = providerDao.getProviderName(providerNo); String signature = "[" + props.getString("oscarEncounter.class.EctSaveEncounterAction.msgSigned") + " " + dt.format(now) + " " + props.getString("oscarEncounter.class.EctSaveEncounterAction.msgSigBy") + " " + providerName + "]"; note.setNote(note.getNote() + "\n" + signature); } if (request.getParameter("signAndExit") != null && request.getParameter("signAndExit").equalsIgnoreCase("true")) { OscarAppointmentDao appointmentDao = (OscarAppointmentDao) SpringUtils .getBean("oscarAppointmentDao"); try { Appointment appointment = appointmentDao.find(ConversionUtils.fromIntString(appointmentNo)); if (appointment != null) { ApptStatusData statusData = new ApptStatusData(); appointment.setStatus(statusData.signStatus()); appointmentDao.merge(appointment); } } catch (Exception e) { logger.error("Couldn't parse appointmentNo: " + appointmentNo, e); } } } else if (!note.isSigned() && (archived == null || !archived.equalsIgnoreCase("true"))) { note.setSigned(false); note.setSigning_provider_no(""); } // Determines what program & role to assign the note to ProgramProviderDAO programProviderDao = (ProgramProviderDAO) SpringUtils.getBean("programProviderDAO"); ProviderDefaultProgramDao defaultProgramDao = (ProviderDefaultProgramDao) SpringUtils .getBean("providerDefaultProgramDao"); boolean programSet = false; List<ProviderDefaultProgram> programs = defaultProgramDao.getProgramByProviderNo(providerNo); HashMap<Program, List<Secrole>> rolesForDemo = NotePermissionsAction .getAllProviderAccessibleRolesForDemo(providerNo, demographicNo); for (ProviderDefaultProgram pdp : programs) { for (Program p : rolesForDemo.keySet()) { if (pdp.getProgramId() == p.getId().intValue()) { List<ProgramProvider> programProviderList = programProviderDao .getProgramProviderByProviderProgramId(providerNo, (long) pdp.getProgramId()); note.setProgram_no("" + pdp.getProgramId()); note.setReporter_caisi_role("" + programProviderList.get(0).getRoleId()); programSet = true; } } } if (!programSet && !rolesForDemo.isEmpty()) { Program program = rolesForDemo.keySet().iterator().next(); ProgramProvider programProvider = programProviderDao.getProgramProvider(providerNo, (long) program.getId()); note.setProgram_no("" + programProvider.getProgramId()); note.setReporter_caisi_role("" + programProvider.getRoleId()); } note.setReporter_program_team("0"); CaseManagementCPP cpp = this.caseManagementMgr.getCPP(demographicNo); if (cpp == null) { cpp = new CaseManagementCPP(); cpp.setDemographic_no(demographicNo); } String savedStr = caseManagementMgr.saveNote(cpp, note, providerNo, null, null, null); addNewNoteLink(note.getId()); HashMap<String, Object> hashMap = new HashMap<String, Object>(); hashMap.put("id", note.getId()); JSONObject json = JSONObject.fromObject(hashMap); response.getOutputStream().write(json.toString().getBytes()); return null; }
From source file:imitationNLG.SFX.java
public Object[] createTrainingDatasets(ArrayList<DatasetInstance> trainingData, HashMap<String, HashSet<String>> availableAttributeActions, HashMap<String, HashMap<String, HashSet<Action>>> availableWordActions, HashMap<Integer, HashSet<String>> nGrams) { HashMap<String, ArrayList<Instance>> predicateAttrTrainingData = new HashMap<>(); HashMap<String, HashMap<String, ArrayList<Instance>>> predicateWordTrainingData = new HashMap<>(); if (!availableWordActions.isEmpty() && !predicates.isEmpty()/* && !arguments.isEmpty()*/) { for (String predicate : predicates) { predicateAttrTrainingData.put(predicate, new ArrayList<Instance>()); predicateWordTrainingData.put(predicate, new HashMap<String, ArrayList<Instance>>()); }//w w w.ja v a 2 s . c om for (DatasetInstance di : trainingData) { //System.out.println("BEGIN"); String predicate = di.getMeaningRepresentation().getPredicate(); //for (ArrayList<Action> realization : di.getEvalRealizations()) { ArrayList<Action> realization = di.getTrainRealization(); //System.out.println(realization); HashSet<String> attrValuesAlreadyMentioned = new HashSet<>(); HashSet<String> attrValuesToBeMentioned = new HashSet<>(); for (String attribute : di.getMeaningRepresentation().getAttributes().keySet()) { //int a = 0; for (String value : di.getMeaningRepresentation().getAttributes().get(attribute)) { /*if (value.startsWith("\"x")) { value = "x" + a; a++; } else if (value.startsWith("\"")) { value = value.substring(1, value.length() - 1).replaceAll(" ", "_"); }*/ attrValuesToBeMentioned.add(attribute.toLowerCase() + "=" + value.toLowerCase()); } } if (attrValuesToBeMentioned.isEmpty()) { attrValuesToBeMentioned.add("empty=empty"); } ArrayList<String> attrs = new ArrayList<>(); boolean isValueMentioned = false; String valueTBM = ""; String attrValue = ""; ArrayList<String> subPhrase = new ArrayList<>(); for (int w = 0; w < realization.size(); w++) { if (!realization.get(w).getAttribute().equals(SFX.TOKEN_PUNCT)) { if (!realization.get(w).getAttribute().equals(attrValue)) { if (!attrValue.isEmpty()) { attrValuesToBeMentioned.remove(attrValue); } Instance attrTrainingVector = SFX.this.createAttrInstance(predicate, realization.get(w).getAttribute(), attrs, new ArrayList<Action>(realization.subList(0, w)), attrValuesAlreadyMentioned, attrValuesToBeMentioned, di.getMeaningRepresentation(), availableAttributeActions); if (attrTrainingVector != null) { /*System.out.println(realization.get(w).getAttribute() + " >>>> " + attrTrainingVector.getCorrectLabels()); for (String f : attrTrainingVector.getGeneralFeatureVector().keySet()) { if (f.startsWith("feature_attrValue_5gram_") || f.startsWith("feature_word_5gram_")) { System.out.println(">> " + f); } }*/ predicateAttrTrainingData.get(predicate).add(attrTrainingVector); } attrs.add(realization.get(w).getAttribute()); attrValue = realization.get(w).getAttribute(); subPhrase = new ArrayList<>(); isValueMentioned = false; valueTBM = ""; if (attrValue.contains("=")) { valueTBM = attrValue.substring(attrValue.indexOf('=') + 1); } if (valueTBM.isEmpty()) { isValueMentioned = true; } } if (!attrValue.equals(SFX.TOKEN_END)) { ArrayList<String> predictedAttributesForInstance = new ArrayList<>(); for (int i = 0; i < attrs.size() - 1; i++) { predictedAttributesForInstance.add(attrs.get(i)); } if (!attrs.get(attrs.size() - 1).equals(attrValue)) { predictedAttributesForInstance.add(attrs.get(attrs.size() - 1)); } Instance wordTrainingVector = createWordInstance(predicate, realization.get(w), predictedAttributesForInstance, new ArrayList<Action>(realization.subList(0, w)), isValueMentioned, attrValuesAlreadyMentioned, attrValuesToBeMentioned, di.getMeaningRepresentation(), availableWordActions.get(predicate), nGrams, false); if (wordTrainingVector != null) { String attribute = attrValue; if (attribute.contains("=")) { attribute = attrValue.substring(0, attrValue.indexOf('=')); } if (!predicateWordTrainingData.get(predicate).containsKey(attribute)) { predicateWordTrainingData.get(predicate).put(attribute, new ArrayList<Instance>()); } /*System.out.println(realization.get(w) + " >>>> " + wordTrainingVector.getCorrectLabels()); for (String f : wordTrainingVector.getGeneralFeatureVector().keySet()) { if (f.startsWith("feature_attrValue_5gram_") || f.startsWith("feature_word_5gram_")) { System.out.println(">> " + f); } }*/ predicateWordTrainingData.get(predicate).get(attribute).add(wordTrainingVector); if (!realization.get(w).getWord().equals(SFX.TOKEN_START) && !realization.get(w).getWord().equals(SFX.TOKEN_END)) { subPhrase.add(realization.get(w).getWord()); } } if (!isValueMentioned) { if (realization.get(w).getWord().startsWith(SFX.TOKEN_X) && (valueTBM.matches("[xX][0-9]+") || valueTBM.matches("\"[xX][0-9]+\"") || valueTBM.startsWith(SFX.TOKEN_X))) { isValueMentioned = true; } else if (!realization.get(w).getWord().startsWith(SFX.TOKEN_X) && !(valueTBM.matches("[xX][0-9]+") || valueTBM.matches("\"[xX][0-9]+\"") || valueTBM.startsWith(SFX.TOKEN_X))) { String valueToCheck = valueTBM; if (valueToCheck.equals("no") || valueToCheck.equals("yes") || valueToCheck.equals("yes or no") || valueToCheck.equals("none") || valueToCheck.equals("dont_care") || valueToCheck.equals("empty")) { String attribute = attrValue; if (attribute.contains("=")) { attribute = attrValue.substring(0, attrValue.indexOf('=')); } valueToCheck = attribute + ":" + valueTBM; } if (!valueToCheck.equals("empty:empty") && valueAlignments.containsKey(valueToCheck)) { for (ArrayList<String> alignedStr : valueAlignments.get(valueToCheck) .keySet()) { if (endsWith(subPhrase, alignedStr)) { isValueMentioned = true; break; } } } } if (isValueMentioned) { attrValuesAlreadyMentioned.add(attrValue); attrValuesToBeMentioned.remove(attrValue); } } String mentionedAttrValue = ""; if (!realization.get(w).getWord().startsWith(SFX.TOKEN_X)) { for (String attrValueTBM : attrValuesToBeMentioned) { if (attrValueTBM.contains("=")) { String value = attrValueTBM.substring(attrValueTBM.indexOf('=') + 1); if (!(value.matches("\"[xX][0-9]+\"") || value.matches("[xX][0-9]+") || value.startsWith(SFX.TOKEN_X))) { String valueToCheck = value; if (valueToCheck.equals("no") || valueToCheck.equals("yes") || valueToCheck.equals("yes or no") || valueToCheck.equals("none") || valueToCheck.equals("dont_care") || valueToCheck.equals("empty")) { valueToCheck = attrValueTBM.replace("=", ":"); } if (!valueToCheck.equals("empty:empty") && valueAlignments.containsKey(valueToCheck)) { for (ArrayList<String> alignedStr : valueAlignments .get(valueToCheck).keySet()) { if (endsWith(subPhrase, alignedStr)) { mentionedAttrValue = attrValueTBM; break; } } } } } } } if (!mentionedAttrValue.isEmpty()) { attrValuesAlreadyMentioned.add(mentionedAttrValue); attrValuesToBeMentioned.remove(mentionedAttrValue); } } } } //} } } Object[] results = new Object[2]; results[0] = predicateAttrTrainingData; results[1] = predicateWordTrainingData; return results; }
From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java
@Override public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request) throws ProvisioningException { int approvalID = 0; if (request.containsKey("APPROVAL_ID")) { approvalID = (Integer) request.get("APPROVAL_ID"); }/*from ww w .j av a2 s.co m*/ Workflow workflow = (Workflow) request.get("WORKFLOW"); HttpCon con = null; Gson gson = new Gson(); try { con = this.createClient(); KSToken token = this.getToken(con); UserAndID fromKS = this.lookupUser(user.getUserID(), attributes, request, token, con); if (fromKS == null) { this.createUser(user, attributes, request); } else { //check attributes HashMap<String, String> attrsUpdate = new HashMap<String, String>(); KSUser toPatch = new KSUser(); if (!rolesOnly) { if (attributes.contains("email")) { String fromKSVal = null; String newVal = null; if (fromKS.getUser().getAttribs().get("email") != null) { fromKSVal = fromKS.getUser().getAttribs().get("email").getValues().get(0); } if (user.getAttribs().get("email") != null) { newVal = user.getAttribs().get("email").getValues().get(0); } if (newVal != null && (fromKSVal == null || !fromKSVal.equalsIgnoreCase(newVal))) { toPatch.setEmail(newVal); attrsUpdate.put("email", newVal); } else if (!addOnly && newVal == null && fromKSVal != null) { toPatch.setEmail(""); attrsUpdate.put("email", ""); } } if (attributes.contains("enabled")) { String fromKSVal = null; String newVal = null; if (fromKS.getUser().getAttribs().get("enabled") != null) { fromKSVal = fromKS.getUser().getAttribs().get("enabled").getValues().get(0); } if (user.getAttribs().get("enabled") != null) { newVal = user.getAttribs().get("enabled").getValues().get(0); } if (newVal != null && (fromKSVal == null || !fromKSVal.equalsIgnoreCase(newVal))) { toPatch.setName(newVal); attrsUpdate.put("enabled", newVal); } else if (!addOnly && newVal == null && fromKSVal != null) { toPatch.setEnabled(false); attrsUpdate.put("enabled", ""); } } if (attributes.contains("description")) { String fromKSVal = null; String newVal = null; if (fromKS.getUser().getAttribs().get("description") != null) { fromKSVal = fromKS.getUser().getAttribs().get("description").getValues().get(0); } if (user.getAttribs().get("description") != null) { newVal = user.getAttribs().get("description").getValues().get(0); } if (newVal != null && (fromKSVal == null || !fromKSVal.equalsIgnoreCase(newVal))) { toPatch.setDescription(newVal); attrsUpdate.put("description", newVal); } else if (!addOnly && newVal == null && fromKSVal != null) { toPatch.setDescription(""); attrsUpdate.put("description", ""); } } if (!attrsUpdate.isEmpty()) { UserHolder holder = new UserHolder(); holder.setUser(toPatch); String json = gson.toJson(holder); StringBuffer b = new StringBuffer(); b.append(this.url).append("/users/").append(fromKS.getId()); json = this.callWSPotch(token.getAuthToken(), con, b.toString(), json); for (String attr : attrsUpdate.keySet()) { String val = attrsUpdate.get(attr); this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Replace, approvalID, workflow, attr, val); } } for (String group : user.getGroups()) { if (!fromKS.getUser().getGroups().contains(group)) { String groupID = this.getGroupID(token.getAuthToken(), con, group); StringBuffer b = new StringBuffer(); b.append(this.url).append("/groups/").append(groupID).append("/users/") .append(fromKS.getId()); if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) { this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "group", group); } else { throw new ProvisioningException("Could not add group " + group); } } } if (!addOnly) { for (String group : fromKS.getUser().getGroups()) { if (!user.getGroups().contains(group)) { String groupID = this.getGroupID(token.getAuthToken(), con, group); StringBuffer b = new StringBuffer(); b.append(this.url).append("/groups/").append(groupID).append("/users/") .append(fromKS.getId()); this.callWSDelete(token.getAuthToken(), con, b.toString()); this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Delete, approvalID, workflow, "group", group); } } } } if (attributes.contains("roles")) { HashSet<Role> currentRoles = new HashSet<Role>(); if (fromKS.getUser().getAttribs().get("roles") != null) { Attribute attr = fromKS.getUser().getAttribs().get("roles"); for (String jsonRole : attr.getValues()) { currentRoles.add(gson.fromJson(jsonRole, Role.class)); } } if (user.getAttribs().containsKey("roles")) { StringBuffer b = new StringBuffer(); Attribute attr = user.getAttribs().get("roles"); for (String jsonRole : attr.getValues()) { Role role = gson.fromJson(jsonRole, Role.class); if (!currentRoles.contains(role)) { if (role.getScope().equalsIgnoreCase("project")) { String projectid = this.getProjectID(token.getAuthToken(), con, role.getProject()); if (projectid == null) { throw new ProvisioningException( "Project " + role.getDomain() + " does not exist"); } String roleid = this.getRoleID(token.getAuthToken(), con, role.getName()); if (roleid == null) { throw new ProvisioningException( "Role " + role.getName() + " does not exist"); } b.setLength(0); b.append(this.url).append("/projects/").append(projectid).append("/users/") .append(fromKS.getId()).append("/roles/").append(roleid); if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) { this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "role", jsonRole); } else { throw new ProvisioningException("Could not add role " + jsonRole); } } else { String domainid = this.getDomainID(token.getAuthToken(), con, role.getDomain()); if (domainid == null) { throw new ProvisioningException( "Domain " + role.getDomain() + " does not exist"); } String roleid = this.getRoleID(token.getAuthToken(), con, role.getName()); if (roleid == null) { throw new ProvisioningException( "Role " + role.getName() + " does not exist"); } b.setLength(0); b.append(this.url).append("/domains/").append(domainid).append("/users/") .append(fromKS.getId()).append("/roles/").append(roleid); if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) { this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "role", jsonRole); } else { throw new ProvisioningException("Could not add role " + jsonRole); } } } } } } if (!addOnly) { if (attributes.contains("roles")) { HashSet<Role> currentRoles = new HashSet<Role>(); if (user.getAttribs().get("roles") != null) { Attribute attr = user.getAttribs().get("roles"); for (String jsonRole : attr.getValues()) { currentRoles.add(gson.fromJson(jsonRole, Role.class)); } } if (fromKS.getUser().getAttribs().containsKey("roles")) { StringBuffer b = new StringBuffer(); Attribute attr = fromKS.getUser().getAttribs().get("roles"); for (String jsonRole : attr.getValues()) { Role role = gson.fromJson(jsonRole, Role.class); if (!currentRoles.contains(role)) { if (role.getScope().equalsIgnoreCase("project")) { String projectid = this.getProjectID(token.getAuthToken(), con, role.getProject()); if (projectid == null) { throw new ProvisioningException( "Project " + role.getDomain() + " does not exist"); } String roleid = this.getRoleID(token.getAuthToken(), con, role.getName()); if (roleid == null) { throw new ProvisioningException( "Role " + role.getName() + " does not exist"); } b.setLength(0); b.append(this.url).append("/projects/").append(projectid).append("/users/") .append(fromKS.getId()).append("/roles/").append(roleid); this.callWSDelete(token.getAuthToken(), con, b.toString()); this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Delete, approvalID, workflow, "role", jsonRole); } else { String domainid = this.getDomainID(token.getAuthToken(), con, role.getDomain()); if (domainid == null) { throw new ProvisioningException( "Domain " + role.getDomain() + " does not exist"); } String roleid = this.getRoleID(token.getAuthToken(), con, role.getName()); if (roleid == null) { throw new ProvisioningException( "Role " + role.getName() + " does not exist"); } b.setLength(0); b.append(this.url).append("/domains/").append(domainid).append("/users/") .append(fromKS.getId()).append("/roles/").append(roleid); this.callWSDelete(token.getAuthToken(), con, b.toString()); this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Delete, approvalID, workflow, "role", jsonRole); } } } } } } } } catch (Exception e) { throw new ProvisioningException("Could not work with keystone", e); } finally { if (con != null) { con.getBcm().shutdown(); } } }
From source file:Commands.AddShoesCommand.java
@Override public String executeCommand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String forwardToJsp = ""; HttpSession session = request.getSession(true); ShoesDao sd = new ShoesDao(); boolean check = true; ArrayList<String> addList = new ArrayList<>(); ArrayList<Shoes> list = new ArrayList<>(); HashMap<Integer, LinkedList<String>> status = new HashMap<>(); HashMap<Integer, LinkedList<Integer>> color = new HashMap<>(); LinkedList<String> s = null; LinkedList<Integer> c = null; if (session.getAttribute("userLogin") != null && ((User) session.getAttribute("userLogin")).is_Admin()) { if (request.getParameter("number") != null) { int num = Integer.parseInt(request.getParameter("number")); for (int n = 1; n < num; n++) { s = new LinkedList<>(); c = new LinkedList<>(); boolean check1 = true; if (request.getParameter("name-" + n) != null && request.getParameter("brand-" + n) != null && request.getParameter("sport-" + n) != null) { if (request.getParameter("name-" + n).isEmpty()) { session.setAttribute("errorMsg", "The name cannot be empty"); return forwardToJsp = "AddShoes.jsp"; }/*from ww w . ja v a 2 s . c o m*/ String name = (String) request.getParameter("name-" + n).substring(0, 1).toUpperCase() + request.getParameter("name-" + n).substring(1).toLowerCase(); int brand = Integer.parseInt(request.getParameter("brand-" + n)); int sport = Integer.parseInt(request.getParameter("sport-" + n)); if (request.getParameter("price-" + n).isEmpty()) { s.add("price cannot be empty"); } double price = Double.parseDouble(request.getParameter("price-" + n)); if (price < 1 || price > 200) { s.add("price range is between 1 to 200"); } if (!sd.findShoes(name).isEmpty()) { s.add("The name is repeated"); } boolean repeat = false; for (int i = 1; i < 4; i++) { if (request.getParameter("color" + i + "-" + n) != null) { int id = Integer.parseInt(request.getParameter("color" + i + "-" + n)); if (c.contains(id)) { repeat = true; } c.add(id); } } if (repeat) { s.add("The color is repeated"); } // String[] files1 = request.getParameterValues("file1-" + n); // String[] files2 = request.getParameterValues("file2-" + n); // String[] files3 = request.getParameterValues("file3-" + n); // long a=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count(); // long b=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count(); // long d=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count(); // if(a==0 || b==0 || d==0){ // s.add("Images is not uploaded"); // } // p.add(files1); // p.add(files2); // p.add(files3); if (!s.isEmpty()) { status.put(n, s); } color.put(n, c); list.add(new Shoes(n, brand, 0, sport, name, price, "")); } else { check = false; break; } } ColorDao cd = new ColorDao(); response.setContentType("text/html"); session.setAttribute("list", list); session.setAttribute("status", status); session.setAttribute("allcolor", color); if (status.isEmpty() && check) { for (int i = 0; i < list.size(); i++) { c = color.get(i + 1); Iterator<Integer> iter = c.iterator(); int count = 1; while (iter.hasNext()) { String name = list.get(i).getName(); int colorId = iter.next(); String colorName = cd.findColorById(colorId).getColor_Name(); String pic = name + "-" + colorName + "-"; sd.addShoes(list.get(i).getBrandID(), colorId, list.get(i).getTypeID(), name, list.get(i).getPrice(), pic); String colo = request.getParameter("cr" + count + "-" + (i + 1)); String[] col = colo.split(","); String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("") + File.separator + "img" + File.separator; int count1 = 1; for (String str : col) { File file = new File(UPLOAD_DIRECTORY + str.substring(4)); File f = new File(UPLOAD_DIRECTORY + pic + count1 + ".jpg"); try { boolean check1 = file.renameTo(f); if (check1 == false) { session.setAttribute("errorMsg", str.substring(4) + " " + UPLOAD_DIRECTORY + pic); return "AddShoes.jsp"; } } catch (SecurityException | NullPointerException se) { session.setAttribute("errorMsg", Arrays.toString(se.getStackTrace())); return "AddShoes.jsp"; } count1++; } count++; } } session.setAttribute("errorMsg", "Shoes is successful added"); // session.removeAttribute("list"); // session.removeAttribute("allcolor"); // session.removeAttribute("status"); } else { session.setAttribute("errorMsg", "Please fill the form with correct information"); forwardToJsp = "AddShoes.jsp"; } } else { session.setAttribute("errorMsg", "Fail to save changes, please refresh the page and try again"); forwardToJsp = "shoes.jsp"; } } else { session.setAttribute("errorMsg", "You are not allowed to access this page"); forwardToJsp = "index.jsp"; } return forwardToJsp; }
From source file:com.chocolatefactory.newrelic.plugins.hadoop.NewRelicSink.java
@Override public void putMetrics(MetricsRecord record) { HashMap<String, Float> summaryMetrics = new HashMap<String, Float>(); // Create new one for each record Request request = new Request(context); for (MetricsTag tag : record.tags()) { if ((tag.value() == null) || tag.value().isEmpty()) continue; else if (useInsights) insightsMetrics.put(tag.name().toLowerCase(), tag.value()); }/*from w ww . jav a2s . co m*/ for (AbstractMetric metric : record.metrics()) { if ((metric.value() == null) || (metric.name() == null) || metric.name().isEmpty() || metric.value().toString().isEmpty()) { // NOT skipping "imax" and "imin" metrics, though they are constant and rather large // || metric.name().contains("_imin_") || metric.name().contains("_imax_")) { continue; } String metricName, metricType; String metricHashCode = record.context() + "_" + metric.name(); Float metricValue = metric.value().floatValue(); if (metricNames.containsKey(metricHashCode)) { metricName = metricNames.get(metricHashCode)[0]; metricType = metricNames.get(metricHashCode)[1]; } else { metricName = getMetricName(metric); metricType = getMetricType(metric); metricNames.put(metricHashCode, new String[] { metricName, metricType }); // Get groupings for new metrics only if (debugEnabled && getGroupings) { addMetricGroup(getMetricBaseName(record, categoryName), metricType); addMetricGroup(getMetricBaseName(record, categoryName + div + deltaName), metricType); } } if (useInsights) { insightsMetrics.put(metricName, metricValue); } // Debug // logger.info("metric name: " + metricName); // logger.info("metric type: " + metricType); // logger.info("metric value: " + metricValue); // logger.info("metric hashcode: " + metricHashCode); // If old metric value exists, use it to compute delta. If not, delta is metric value. // In any case, set oldValue to use for next delta. Float oldMetricValue = (float) 0; if (oldMetricValues.containsKey(metricHashCode)) { oldMetricValue = oldMetricValues.get(metricHashCode); // logger.info("metric OLD value: " + oldMetricValue); } Float deltaMetricValue = metricValue - oldMetricValue; // logger.info("delta value: " + deltaMetricValue); if (deltaMetricValue < 0.0) { // logger.info("delta is less than 0"); deltaMetricValue = (float) 0; } if (metricValue > 0) { oldMetricValues.put(metricHashCode + "", metricValue); // logger.info("putting value to OLD: " + metricValue); } addMetric(request, getMetricBaseName(record, categoryName) + div + metricName, metric.name(), metricType, metricValue); addMetric(request, getMetricBaseName(record, categoryName + div + deltaName) + div + metricName, metric.name(), metricType, deltaMetricValue); // If this is a metric to be included in summary metrics... include it! if (record.name().equalsIgnoreCase(hadoopProcType) && NewRelicMetrics.HadoopOverviewMetrics.contains(metricType)) { if (!summaryMetrics.containsKey(metricType)) { summaryMetrics.put(metricType, deltaMetricValue); // logger.info("putting NEW summary metric: " + deltaMetricValue); } else { Float newValue = summaryMetrics.get(metricType) + deltaMetricValue; summaryMetrics.put(metricType, newValue); // logger.info("putting UPDATED summary metric: " + newValue); } // Summary metrics are also included in the 2 top graphs in the "Overview" dashboard addMetric(request, getMetricBaseName(record, categoryName + div + overviewName) + div + metricName, metric.name(), metricType, metricValue); addMetric(request, getMetricBaseName(record, categoryName + div + overviewName + "_" + deltaName) + div + metricName, metric.name(), metricType, deltaMetricValue); } } // Get summary metrics, reset each one after output. if (!summaryMetrics.isEmpty()) { for (Entry<String, Float> summaryMetric : summaryMetrics.entrySet()) { addMetric(request, categoryName + div + overviewName + div + "total " + summaryMetric.getKey(), summaryMetric.getKey(), summaryMetric.getKey(), summaryMetric.getValue()); } } if (debugEnabled) { logger.info("Debug is enabled on New Relic Hadoop Extension. Metrics will not be sent."); if (getGroupings) { logger.info("Outputting metric groupings from the current Metrics Record."); for (Map.Entry<String, Integer> grouping : metricGroupings.entrySet()) { logger.info(grouping.getKey() + " : " + grouping.getValue()); } } } else { request.deliver(); if (useInsights) { insightsService.submitToInsights(hadoopProcType + "Event", insightsMetrics); } } }
From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java
/** * Checks each object being deleted to make sure that it does not have any currently existing references. * Objects must be fetched from the Cache or Server and not from the RequestContext?? * * @throws ReferencesExistException if references exist to any of the RegistryObject ids specified in roIds * *///from ww w. j av a2 s.com public void checkIfReferencesExist(ServerRequestContext context, List roIds) throws RegistryException { if (skipReferenceCheckOnRemove) { return; } Iterator iter = roIds.iterator(); HashMap idToReferenceSourceMap = new HashMap(); while (iter.hasNext()) { String id = (String) iter.next(); StringBuffer query = new StringBuffer(); query.append("SELECT id FROM RegistryObject WHERE objectType = ? UNION "); query.append("SELECT id FROM ClassificationNode WHERE parent = ? UNION "); query.append( "SELECT id FROM Classification WHERE classificationNode = ? OR classificationScheme = ? OR classifiedObject = ? UNION "); query.append( "SELECT id FROM ExternalIdentifier WHERE identificationScheme = ? OR registryObject = ? UNION "); query.append( "SELECT id FROM Association WHERE associationType = ? OR sourceObject = ? OR targetObject= ? UNION "); query.append("SELECT id FROM AuditableEvent WHERE user_ = ? OR requestId = ? UNION "); query.append("SELECT id FROM Organization WHERE parent = ? UNION "); query.append("SELECT id FROM Registry where operator = ? UNION "); query.append("SELECT id FROM ServiceBinding WHERE service = ? OR targetBinding = ? UNION "); query.append( "SELECT id FROM SpecificationLink WHERE serviceBinding = ? OR specificationObject = ? UNION "); query.append("SELECT id FROM Subscription WHERE selector = ? UNION "); query.append("SELECT s.parent FROM Slot s WHERE s.slotType = '" + bu.CANONICAL_DATA_TYPE_ID_ObjectRef + "' AND s.value = ?"); PreparedStatement stmt = null; try { stmt = context.getConnection().prepareStatement(query.toString()); stmt.setString(1, id); stmt.setString(2, id); stmt.setString(3, id); stmt.setString(4, id); stmt.setString(5, id); stmt.setString(6, id); stmt.setString(7, id); stmt.setString(8, id); stmt.setString(9, id); stmt.setString(10, id); stmt.setString(11, id); stmt.setString(12, id); stmt.setString(13, id); stmt.setString(14, id); stmt.setString(15, id); stmt.setString(16, id); stmt.setString(17, id); stmt.setString(18, id); stmt.setString(19, id); stmt.setString(20, id); log.trace("SQL = " + query.toString()); // HIEOS/BHT: (DEBUG) ResultSet rs = stmt.executeQuery(); boolean result = false; ArrayList referenceSourceIds = new ArrayList(); while (rs.next()) { String referenceSourceId = rs.getString(1); if (!roIds.contains(referenceSourceId)) { referenceSourceIds.add(referenceSourceId); } } if (!referenceSourceIds.isEmpty()) { idToReferenceSourceMap.put(id, referenceSourceIds); } } catch (SQLException e) { throw new RegistryException(e); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException sqle) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), sqle); } } } if (!idToReferenceSourceMap.isEmpty()) { //At least one ref exists to at least one object so throw exception String msg = ServerResourceBundle.getInstance().getString("message.referencesExist"); msg += "\n" + idToReferenceSourceMap.toString(); throw new ReferencesExistException(msg); } }
From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java
/** * Checks each object being deleted to make sure that it does not have any * currently existing references. Objects must be fetched from the Cache or * Server and not from the RequestContext?? * //from w ww . j a v a 2s .c o m * @throws ReferencesExistException * if references exist to any of the RegistryObject ids * specified in roIds * */ @SuppressWarnings("static-access") public void checkIfReferencesExist(ServerRequestContext context, List<String> roIds) throws RegistryException { if (skipReferenceCheckOnRemove) { return; } Iterator<String> iter = roIds.iterator(); HashMap<String, ArrayList<String>> idToReferenceSourceMap = new HashMap<String, ArrayList<String>>(); while (iter.hasNext()) { String id = iter.next(); StringBuffer query = new StringBuffer(); query.append("SELECT id FROM RegistryObject WHERE objectType = ? UNION "); query.append("SELECT id FROM ClassificationNode WHERE parent = ? UNION "); query.append( "SELECT id FROM Classification WHERE classificationNode = ? OR classificationScheme = ? OR classifiedObject = ? UNION "); query.append( "SELECT id FROM ExternalIdentifier WHERE identificationScheme = ? OR registryObject = ? UNION "); query.append( "SELECT id FROM Association WHERE associationType = ? OR sourceObject = ? OR targetObject= ? UNION "); query.append("SELECT id FROM AuditableEvent WHERE user_ = ? OR requestId = ? UNION "); query.append("SELECT id FROM Organization WHERE parent = ? UNION "); query.append("SELECT id FROM Registry where operator = ? UNION "); query.append("SELECT id FROM ServiceBinding WHERE service = ? OR targetBinding = ? UNION "); query.append( "SELECT id FROM SpecificationLink WHERE serviceBinding = ? OR specificationObject = ? UNION "); query.append("SELECT id FROM Subscription WHERE selector = ? UNION "); query.append("SELECT s.parent FROM Slot s WHERE s.slotType = '" + bu.CANONICAL_DATA_TYPE_ID_ObjectRef + "' AND s.value = ?"); PreparedStatement stmt = null; try { stmt = context.getConnection().prepareStatement(query.toString()); stmt.setString(1, id); stmt.setString(2, id); stmt.setString(3, id); stmt.setString(4, id); stmt.setString(5, id); stmt.setString(6, id); stmt.setString(7, id); stmt.setString(8, id); stmt.setString(9, id); stmt.setString(10, id); stmt.setString(11, id); stmt.setString(12, id); stmt.setString(13, id); stmt.setString(14, id); stmt.setString(15, id); stmt.setString(16, id); stmt.setString(17, id); stmt.setString(18, id); stmt.setString(19, id); stmt.setString(20, id); ResultSet rs = stmt.executeQuery(); @SuppressWarnings("unused") boolean result = false; ArrayList<String> referenceSourceIds = new ArrayList<String>(); while (rs.next()) { String referenceSourceId = rs.getString(1); if (!roIds.contains(referenceSourceId)) { referenceSourceIds.add(referenceSourceId); } } if (!referenceSourceIds.isEmpty()) { idToReferenceSourceMap.put(id, referenceSourceIds); } } catch (SQLException e) { throw new RegistryException(e); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException sqle) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), sqle); } } } if (!idToReferenceSourceMap.isEmpty()) { // At least one ref exists to at least one object so throw exception String msg = ServerResourceBundle.getInstance().getString("message.referencesExist"); msg += "\n" + idToReferenceSourceMap.toString(); throw new ReferencesExistException(msg); } }
From source file:org.telegram.android.MessagesController.java
public void getDifference() { registerForPush(UserConfig.pushString); if (MessagesStorage.lastPtsValue == 0) { loadCurrentState();// ww w .j a v a2s .co m return; } if (gettingDifference) { return; } if (!firstGettingTask) { getNewDeleteTask(null); firstGettingTask = true; } gettingDifference = true; TLRPC.TL_updates_getDifference req = new TLRPC.TL_updates_getDifference(); req.pts = MessagesStorage.lastPtsValue; req.date = MessagesStorage.lastDateValue; req.qts = MessagesStorage.lastQtsValue; if (req.date == 0) { req.date = ConnectionsManager.getInstance().getCurrentTime(); } FileLog.e("tmessages", "start getDifference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue); if (ConnectionsManager.getInstance().getConnectionState() == 0) { ConnectionsManager.getInstance().setConnectionState(3); final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance() .postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { gettingDifferenceAgain = false; if (error == null) { final TLRPC.updates_Difference res = (TLRPC.updates_Difference) response; gettingDifferenceAgain = res instanceof TLRPC.TL_updates_differenceSlice; final HashMap<Integer, TLRPC.User> usersDict = new HashMap<>(); for (TLRPC.User user : res.users) { usersDict.put(user.id, user); } final ArrayList<TLRPC.TL_updateMessageID> msgUpdates = new ArrayList<>(); if (!res.other_updates.isEmpty()) { for (int a = 0; a < res.other_updates.size(); a++) { TLRPC.Update upd = res.other_updates.get(a); if (upd instanceof TLRPC.TL_updateMessageID) { msgUpdates.add((TLRPC.TL_updateMessageID) upd); res.other_updates.remove(a); a--; } } } AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { putUsers(res.users, false); putChats(res.chats, false); } }); MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { if (!msgUpdates.isEmpty()) { final HashMap<Integer, Integer> corrected = new HashMap<>(); for (TLRPC.TL_updateMessageID update : msgUpdates) { Integer oldId = MessagesStorage.getInstance() .updateMessageStateAndId(update.random_id, null, update.id, 0, false); if (oldId != null) { corrected.put(oldId, update.id); } } if (!corrected.isEmpty()) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { for (HashMap.Entry<Integer, Integer> entry : corrected.entrySet()) { Integer oldId = entry.getKey(); SendMessagesHelper.getInstance().processSentMessage(oldId); Integer newId = entry.getValue(); NotificationCenter.getInstance().postNotificationName( NotificationCenter.messageReceivedByServer, oldId, newId, null, false); } } }); } } Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { if (!res.new_messages.isEmpty() || !res.new_encrypted_messages.isEmpty()) { final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<>(); for (TLRPC.EncryptedMessage encryptedMessage : res.new_encrypted_messages) { ArrayList<TLRPC.Message> decryptedMessages = SecretChatHelper .getInstance().decryptMessage(encryptedMessage); if (decryptedMessages != null && !decryptedMessages.isEmpty()) { for (TLRPC.Message message : decryptedMessages) { res.new_messages.add(message); } } } ImageLoader.saveMessagesThumbs(res.new_messages); final ArrayList<MessageObject> pushMessages = new ArrayList<>(); for (TLRPC.Message message : res.new_messages) { MessageObject obj = new MessageObject(message, usersDict, true); long dialog_id = obj.messageOwner.dialog_id; if (dialog_id == 0) { if (obj.messageOwner.to_id.chat_id != 0) { dialog_id = -obj.messageOwner.to_id.chat_id; } else { dialog_id = obj.messageOwner.to_id.user_id; } } if (!obj.isOut() && obj.isUnread()) { pushMessages.add(obj); } long uid; if (message.dialog_id != 0) { uid = message.dialog_id; } else { if (message.to_id.chat_id != 0) { uid = -message.to_id.chat_id; } else { if (message.to_id.user_id == UserConfig.getClientUserId()) { message.to_id.user_id = message.from_id; } uid = message.to_id.user_id; } } ArrayList<MessageObject> arr = messages.get(uid); if (arr == null) { arr = new ArrayList<>(); messages.put(uid, arr); } arr.add(obj); } AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages .entrySet()) { Long key = pair.getKey(); ArrayList<MessageObject> value = pair.getValue(); updateInterfaceWithMessages(key, value); } NotificationCenter.getInstance() .postNotificationName(NotificationCenter.dialogsNeedReload); } }); MessagesStorage.getInstance().getStorageQueue() .postRunnable(new Runnable() { @Override public void run() { if (!pushMessages.isEmpty()) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationsController.getInstance() .processNewMessages(pushMessages, !(res instanceof TLRPC.TL_updates_differenceSlice)); } }); } MessagesStorage.getInstance().startTransaction(false); MessagesStorage.getInstance().putMessages(res.new_messages, false, false, false, MediaController.getInstance() .getAutodownloadMask()); MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, false); MessagesStorage.getInstance().commitTransaction(false); } }); SecretChatHelper.getInstance().processPendingEncMessages(); } if (res != null && !res.other_updates.isEmpty()) { processUpdateArray(res.other_updates, res.users, res.chats); } gettingDifference = false; if (res instanceof TLRPC.TL_updates_difference) { MessagesStorage.lastSeqValue = res.state.seq; MessagesStorage.lastDateValue = res.state.date; MessagesStorage.lastPtsValue = res.state.pts; MessagesStorage.lastQtsValue = res.state.qts; ConnectionsManager.getInstance().setConnectionState(0); boolean done = true; for (int a = 0; a < 3; a++) { if (!processUpdatesQueue(a, 1)) { done = false; } } if (done) { final int stateCopy = ConnectionsManager.getInstance() .getConnectionState(); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance().postNotificationName( NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } } else if (res instanceof TLRPC.TL_updates_differenceSlice) { MessagesStorage.lastDateValue = res.intermediate_state.date; MessagesStorage.lastPtsValue = res.intermediate_state.pts; MessagesStorage.lastQtsValue = res.intermediate_state.qts; gettingDifferenceAgain = true; getDifference(); } else if (res instanceof TLRPC.TL_updates_differenceEmpty) { MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastDateValue = res.date; ConnectionsManager.getInstance().setConnectionState(0); boolean done = true; for (int a = 0; a < 3; a++) { if (!processUpdatesQueue(a, 1)) { done = false; } } if (done) { final int stateCopy = ConnectionsManager.getInstance() .getConnectionState(); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance().postNotificationName( NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } } MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); FileLog.e("tmessages", "received difference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue); FileLog.e("tmessages", "messages = " + res.new_messages.size() + " users = " + res.users.size() + " chats = " + res.chats.size() + " other updates = " + res.other_updates.size()); } }); } }); } else { gettingDifference = false; ConnectionsManager.getInstance().setConnectionState(0); final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { NotificationCenter.getInstance() .postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy); } }); } } }); }
From source file:com.silverpeas.jobDomainPeas.servlets.JobDomainPeasRequestRouter.java
/** * This method has to be implemented by the component request rooter it has to compute a * destination page//from ww w .ja v a 2s .c o m * * @param function The entering request function (ex : "Main.jsp") * @param jobDomainSC The component Session Control, build and initialised. * @param request * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, JobDomainPeasSessionController jobDomainSC, HttpRequest request) { String destination = ""; SilverTrace.info("jobDomainPeas", "JobDomainPeasRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "User=" + jobDomainSC.getUserId() + " Function=" + function); try { if (!jobDomainSC.isAccessGranted()) { throw new JobDomainPeasException("JobDomainPeasRequestRouter.getDestination", SilverpeasException.ERROR, "root.EX_BAD_USER_RIGHT", "MODULE JOBDOMAIN : user " + jobDomainSC.getUserId()); } // 1) Performs the action // ---------------------- if (function.startsWith("selectUserOrGroup")) { String id; function = "domainContent"; id = jobDomainSC.getSelectedUserId(); if (id != null) { jobDomainSC.setTargetUser(id); function = "userContent"; } else { id = jobDomainSC.getSelectedGroupId(); if (id != null) { jobDomainSC.goIntoGroup(id); function = "groupContent"; } } } if (function.startsWith("Main")) { jobDomainSC.returnIntoGroup(null); jobDomainSC.setDefaultTargetDomain(); destination = "jobDomain.jsp"; } // USER Actions -------------------------------------------- else if (function.startsWith("user")) { if (function.startsWith("userContent")) { if ((request.getParameter("Iduser") != null) && (request.getParameter("Iduser").length() > 0)) { jobDomainSC.setTargetUser(request.getParameter("Iduser")); } } else if (function.equals("userGetP12")) { String userId = request.getParameter("Iduser"); jobDomainSC.getP12(userId); } else if (function.startsWith("userCreate")) { boolean userPasswordValid = false; if ((request.getParameter("userPasswordValid") != null) && (request.getParameter("userPasswordValid").equals("true"))) { userPasswordValid = true; } // process extra properties HashMap<String, String> properties = getExtraPropertyValues(request); String sendEmailParam = request.getParameter("sendEmail"); boolean sendEmail = (StringUtil.isDefined(sendEmailParam) && "true".equals(sendEmailParam)); jobDomainSC.createUser(EncodeHelper.htmlStringToJavaString(request.getParameter("userLogin")), EncodeHelper.htmlStringToJavaString(request.getParameter("userLastName")), EncodeHelper.htmlStringToJavaString(request.getParameter("userFirstName")), EncodeHelper.htmlStringToJavaString(request.getParameter("userEMail")), UserAccessLevel.from(request.getParameter("userAccessLevel")), userPasswordValid, EncodeHelper.htmlStringToJavaString(request.getParameter("userPassword")), properties, request.getParameter("GroupId"), request, sendEmail); } else if (function.startsWith("usersCsvImport")) { List<FileItem> fileItems = request.getFileItems(); FileItem fileItem = FileUploadUtil.getFile(fileItems, "file_upload"); String sendEmailParam = FileUploadUtil.getParameter(fileItems, "sendEmail"); boolean sendEmail = (StringUtil.isDefined(sendEmailParam) && "true".equals(sendEmailParam)); if (fileItem != null) { jobDomainSC.importCsvUsers(fileItem, sendEmail, request); } destination = "domainContent.jsp"; } else if (function.startsWith("userModify")) { boolean userPasswordValid = false; if ((request.getParameter("userPasswordValid") != null) && (request.getParameter("userPasswordValid").equals("true"))) { userPasswordValid = true; } // process extra properties HashMap<String, String> properties = getExtraPropertyValues(request); String sendEmailParam = request.getParameter("sendEmail"); boolean sendEmail = (StringUtil.isDefined(sendEmailParam) && "true".equals(sendEmailParam)); jobDomainSC.modifyUser(request.getParameter("Iduser"), EncodeHelper.htmlStringToJavaString(request.getParameter("userLastName")), EncodeHelper.htmlStringToJavaString(request.getParameter("userFirstName")), EncodeHelper.htmlStringToJavaString(request.getParameter("userEMail")), UserAccessLevel.from(request.getParameter("userAccessLevel")), userPasswordValid, EncodeHelper.htmlStringToJavaString(request.getParameter("userPassword")), properties, request, sendEmail); } else if (function.startsWith("userBlock")) { jobDomainSC.blockUser(request.getParameter("Iduser")); } else if (function.startsWith("userUnblock")) { jobDomainSC.unblockUser(request.getParameter("Iduser")); } else if (function.startsWith("userDelete")) { jobDomainSC.deleteUser(request.getParameter("Iduser")); } else if (function.startsWith("userMS")) { String userId = request.getParameter("Iduser"); UserAccessLevel accessLevel = UserAccessLevel.from(request.getParameter("userAccessLevel")); // process extra properties HashMap<String, String> properties = getExtraPropertyValues(request); if (properties.isEmpty()) { jobDomainSC.modifySynchronizedUser(userId, accessLevel); } else { // extra properties have been set, modify user full jobDomainSC.modifyUserFull(userId, accessLevel, properties); } } else if (function.startsWith("userSearchToImport")) { Hashtable<String, String> query; List<UserDetail> users; jobDomainSC.clearListSelectedUsers(); jobDomainSC.setIndexOfFirstItemToDisplay("0"); String fromArray = request.getParameter("FromArray"); if (StringUtil.isDefined(fromArray)) { query = jobDomainSC.getQueryToImport(); users = jobDomainSC.getUsersToImport(); } else { query = new Hashtable<String, String>(); Enumeration<String> parameters = request.getParameterNames(); String paramName; String paramValue; while (parameters.hasMoreElements()) { paramName = parameters.nextElement(); if (!paramName.startsWith("Pagination")) { paramValue = request.getParameter(paramName); if (StringUtil.isDefined(paramValue)) { query.put(paramName, paramValue); } } } users = jobDomainSC.searchUsers(query); } request.setAttribute("Query", query); request.setAttribute("Users", users); destination = getDestination("displayUserImport", jobDomainSC, request); } else if (function.equals("userImport")) { String[] specificIds = request.getParameterValues("specificIds"); // Massive users import if (specificIds != null) { processSelection(request, jobDomainSC); specificIds = new String[jobDomainSC.getListSelectedUsers().size()]; jobDomainSC.getListSelectedUsers().toArray(specificIds); jobDomainSC.importUsers(specificIds); } // Unitary user Import else { String specificId = request.getParameter("specificIds"); if (StringUtil.isDefined(specificId)) { jobDomainSC.importUser(specificId); } } } else if (function.equals("userImportAll")) { Iterator<UserDetail> usersIt = jobDomainSC.getUsersToImport().iterator(); ArrayList<String> listSelectedUsersIds = new ArrayList<String>(); while (usersIt.hasNext()) { listSelectedUsersIds.add(usersIt.next().getSpecificId()); } jobDomainSC.setListSelectedUsers(listSelectedUsersIds); String[] specificIds = new String[jobDomainSC.getListSelectedUsers().size()]; jobDomainSC.getListSelectedUsers().toArray(specificIds); jobDomainSC.importUsers(specificIds); } else if (function.equals("userView")) { String specificId = request.getParameter("specificId"); UserFull user = jobDomainSC.getUser(specificId); request.setAttribute("UserFull", user); destination = "userView.jsp"; } else if (function.startsWith("userSynchro")) { jobDomainSC.synchroUser(request.getParameter("Iduser")); } else if (function.startsWith("userUnSynchro")) { jobDomainSC.unsynchroUser(request.getParameter("Iduser")); } else if (function.equals("userOpen")) { String userId = request.getParameter("userId"); OrganisationController orgaController = jobDomainSC.getOrganisationController(); UserDetail user = orgaController.getUserDetail(userId); String domainId = user.getDomainId(); if (domainId == null) { domainId = "-1"; } // not refresh the domain jobDomainSC.setRefreshDomain(false); // domaine jobDomainSC.setTargetDomain(domainId); // rinitialise les groupes jobDomainSC.returnIntoGroup(null); // groupe d'appartenance AdminController adminController = new AdminController(jobDomainSC.getUserId()); String[] groupIds = adminController.getDirectGroupsIdsOfUser(userId); if (groupIds != null && groupIds.length > 0) { for (final String groupId : groupIds) { Group group = orgaController.getGroup(groupId); String groupDomainId = group.getDomainId(); if (groupDomainId == null) { groupDomainId = "-1"; } if (!groupDomainId.equals("-1")) { jobDomainSC.goIntoGroup(group.getId()); break; } } } // user jobDomainSC.setTargetUser(userId); } if (destination.length() <= 0) { if (jobDomainSC.getTargetUserDetail() != null) { destination = "userContent.jsp"; } else { destination = getDestination("groupContent", jobDomainSC, request); } } } // GROUP Actions -------------------------------------------- else if (function.startsWith("group")) { boolean bHaveToRefreshDomain = false; jobDomainSC.setTargetUser(null); // Browse functions // ---------------- if (function.startsWith("groupContent")) { String groupId = request.getParameter("Idgroup"); if (StringUtil.isDefined(groupId)) { jobDomainSC.goIntoGroup(groupId); } } else if (function.startsWith("groupExport.txt")) { String groupId = request.getParameter("Idgroup"); if (StringUtil.isDefined(groupId)) { jobDomainSC.goIntoGroup(request.getParameter("Idgroup")); destination = "exportgroup.jsp"; } } else if (function.startsWith("groupReturn")) { jobDomainSC.returnIntoGroup(request.getParameter("Idgroup")); } else if (function.startsWith("groupSet")) { jobDomainSC.returnIntoGroup(null); jobDomainSC.goIntoGroup(request.getParameter("Idgroup")); } // Operation functions else if (function.startsWith("groupCreate")) { bHaveToRefreshDomain = jobDomainSC.createGroup(request.getParameter("Idparent"), EncodeHelper.htmlStringToJavaString(request.getParameter("groupName")), EncodeHelper.htmlStringToJavaString(request.getParameter("groupDescription")), request.getParameter("groupRule")); } else if (function.startsWith("groupModify")) { bHaveToRefreshDomain = jobDomainSC.modifyGroup(request.getParameter("Idgroup"), EncodeHelper.htmlStringToJavaString(request.getParameter("groupName")), EncodeHelper.htmlStringToJavaString(request.getParameter("groupDescription")), request.getParameter("groupRule")); } else if (function.startsWith("groupAddRemoveUsers")) { bHaveToRefreshDomain = jobDomainSC.updateGroupSubUsers(jobDomainSC.getTargetGroup().getId(), jobDomainSC.getSelectedUsersIds()); } else if (function.startsWith("groupDelete")) { bHaveToRefreshDomain = jobDomainSC.deleteGroup(request.getParameter("Idgroup")); } else if (function.startsWith("groupSynchro")) { bHaveToRefreshDomain = jobDomainSC.synchroGroup(request.getParameter("Idgroup")); } else if (function.startsWith("groupUnSynchro")) { bHaveToRefreshDomain = jobDomainSC.unsynchroGroup(request.getParameter("Idgroup")); } else if (function.startsWith("groupImport")) { bHaveToRefreshDomain = jobDomainSC .importGroup(EncodeHelper.htmlStringToJavaString(request.getParameter("groupName"))); } else if (function.equals("groupManagersView")) { List<List> groupManagers = jobDomainSC.getGroupManagers(); request.setAttribute("Users", groupManagers.get(0).iterator()); request.setAttribute("Groups", groupManagers.get(1).iterator()); destination = "groupManagers.jsp"; } else if (function.equals("groupManagersChoose")) { try { jobDomainSC.initUserPanelForGroupManagers((String) request.getAttribute("myComponentURL")); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("groupManagersDelete")) { jobDomainSC.deleteGroupProfile(); destination = getDestination("groupManagersView", jobDomainSC, request); } else if (function.equals("groupManagersUpdate")) { jobDomainSC.updateGroupProfile(); request.setAttribute("urlToReload", "groupManagersView"); destination = "closeWindow.jsp"; } else if (function.equals("groupManagersCancel")) { request.setAttribute("urlToReload", "groupManagersView"); destination = "closeWindow.jsp"; } else if (function.equals("groupOpen")) { String groupId = request.getParameter("groupId"); if (jobDomainSC.isAccessGranted() || jobDomainSC.isGroupManagerOnGroup(groupId)) { OrganisationController orgaController = jobDomainSC.getOrganisationController(); Group group = orgaController.getGroup(groupId); String domainId = group.getDomainId(); if (domainId == null) { domainId = "-1"; } // not refresh the domain jobDomainSC.setRefreshDomain(false); // domaine jobDomainSC.setTargetDomain(domainId); jobDomainSC.returnIntoGroup(null); // groupe(s) pre(s) List<String> groupList = orgaController.getPathToGroup(groupId); for (String elementGroupId : groupList) { jobDomainSC.goIntoGroup(elementGroupId); } // groupe jobDomainSC.goIntoGroup(groupId); destination = "groupContent.jsp"; } else { destination = "/admin/jsp/accessForbidden.jsp"; } } if (destination.length() <= 0) { if (bHaveToRefreshDomain) { destination = getDestination("domainRefresh", jobDomainSC, request); } else if (jobDomainSC.getTargetGroup() != null) { destination = "groupContent.jsp"; } else { destination = getDestination("domainContent", jobDomainSC, request); } } // DOMAIN Actions -------------------------------------------- } else if (function.startsWith("domain")) { jobDomainSC.setTargetUser(null); if (function.startsWith("domainNavigation")) { jobDomainSC.setTargetDomain(request.getParameter("Iddomain")); jobDomainSC.returnIntoGroup(null); jobDomainSC.setRefreshDomain(true); destination = "domainNavigation.jsp"; } else { if (function.startsWith("domainContent")) { jobDomainSC.returnIntoGroup(null); } // Operation functions else if (function.startsWith("domainCreate")) { String newDomainId = jobDomainSC.createDomain( EncodeHelper.htmlStringToJavaString(request.getParameter("domainName")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainDescription")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainDriver")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainProperties")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainAuthentication")), EncodeHelper.htmlStringToJavaString(request.getParameter("silverpeasServerURL")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainTimeStamp"))); request.setAttribute("URLForContent", "domainNavigation?Iddomain=" + newDomainId); destination = "goBack.jsp"; } else if (function.startsWith("domainSQLCreate")) { String newDomainId = jobDomainSC.createSQLDomain( EncodeHelper.htmlStringToJavaString(request.getParameter("domainName")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainDescription")), EncodeHelper.htmlStringToJavaString(request.getParameter("silverpeasServerURL")), request.getParameter("userDomainQuotaMaxCount")); request.setAttribute("URLForContent", "domainNavigation?Iddomain=" + newDomainId); destination = "goBack.jsp"; } else if (function.startsWith("domainModify")) { String modifiedDomainId = jobDomainSC.modifyDomain( EncodeHelper.htmlStringToJavaString(request.getParameter("domainName")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainDescription")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainDriver")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainProperties")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainAuthentication")), EncodeHelper.htmlStringToJavaString(request.getParameter("silverpeasServerURL")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainTimeStamp"))); request.setAttribute("URLForContent", "domainNavigation?Iddomain=" + modifiedDomainId); destination = "goBack.jsp"; } else if (function.startsWith("domainSQLModify")) { String modifiedDomainId = jobDomainSC.modifySQLDomain( EncodeHelper.htmlStringToJavaString(request.getParameter("domainName")), EncodeHelper.htmlStringToJavaString(request.getParameter("domainDescription")), EncodeHelper.htmlStringToJavaString(request.getParameter("silverpeasServerURL")), request.getParameter("userDomainQuotaMaxCount")); request.setAttribute("URLForContent", "domainNavigation?Iddomain=" + modifiedDomainId); destination = "goBack.jsp"; } else if (function.startsWith("domainDelete")) { jobDomainSC.deleteDomain(); request.setAttribute("URLForContent", "domainNavigation"); destination = "goBack.jsp"; } else if (function.startsWith("domainSQLDelete")) { jobDomainSC.deleteSQLDomain(); request.setAttribute("URLForContent", "domainNavigation"); destination = "goBack.jsp"; } else if (function.startsWith("domainPingSynchro")) { if (jobDomainSC.isEnCours()) { destination = "domainSynchroPing.jsp"; } else { String strSynchroReport = jobDomainSC.getSynchroReport(); jobDomainSC.refresh(); SilverTrace.info("jobDomainPeas", "JobDomainPeasRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "SynchroReport=" + strSynchroReport); request.setAttribute("SynchroReport", strSynchroReport); destination = "domainSynchroReport.jsp"; } } else if (function.startsWith("domainSynchro")) { jobDomainSC.synchroDomain(Integer.parseInt(request.getParameter("IdTraceLevel"))); destination = "domainSynchroPing.jsp"; } else if (function.startsWith("domainSQLSynchro")) { jobDomainSC.synchroSQLDomain(); destination = "domainSynchroPing.jsp"; } else if (function.startsWith("domainRefresh")) { request.setAttribute("URLForContent", "domainNavigation?Iddomain=" + jobDomainSC.getTargetDomain().getId()); destination = "goBack.jsp"; } if (destination.length() <= 0) { if (jobDomainSC.getTargetDomain() != null) { destination = "domainContent.jsp"; } else { destination = getDestination("welcome", jobDomainSC, request); } } } } else if (function.startsWith("display")) { if (function.startsWith("displayGroupCreate")) { Group newGroup = new Group(); newGroup.setSuperGroupId(request.getParameter("Idgroup")); request.setAttribute("groupObject", newGroup); request.setAttribute("action", "groupCreate"); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.groupAdd") + "...")); destination = "groupCreate.jsp"; } else if (function.startsWith("displayGroupModify")) { request.setAttribute("groupObject", jobDomainSC.getTargetGroup()); request.setAttribute("action", "groupModify"); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.groupUpdate") + "...")); destination = "groupCreate.jsp"; } else if (function.startsWith("displayGroupImport")) { request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.groupImport") + "...")); destination = "groupImport.jsp"; } else if (function.startsWith("displaySelectUserOrGroup")) { destination = jobDomainSC .initSelectionPeasForOneGroupOrUser((String) request.getAttribute("myComponentURL")); } else if (function.startsWith("displayAddRemoveUsers")) { destination = jobDomainSC .initSelectionPeasForGroups((String) request.getAttribute("myComponentURL")); } else if (function.startsWith("displayUserCreate")) { long domainRight = jobDomainSC.getDomainActions(); request.setAttribute("isUserRW", (domainRight & DomainDriver.ACTION_CREATE_USER) != 0); DomainDriverManager domainDriverManager = new DomainDriverManager(); DomainDriver domainDriver = domainDriverManager .getDomainDriver(Integer.parseInt(jobDomainSC.getTargetDomain().getId())); UserFull newUser = new UserFull(domainDriver); newUser.setPasswordAvailable(true); request.setAttribute("userObject", newUser); request.setAttribute("action", "userCreate"); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.userAdd") + "...")); request.setAttribute("minLengthLogin", jobDomainSC.getMinLengthLogin()); request.setAttribute("CurrentUser", jobDomainSC.getUserDetail()); // if community management is activated, add groups on this user is manager if (JobDomainSettings.m_UseCommunityManagement) { request.setAttribute("GroupsManagedByCurrentUser", jobDomainSC.getUserManageableGroups()); } destination = "userCreate.jsp"; } else if (function.startsWith("displayUsersCsvImport")) { request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.csvImport") + "...")); destination = "usersCsvImport.jsp"; } else if (function.startsWith("displayUserModify")) { long domainRight = jobDomainSC.getDomainActions(); request.setAttribute("isUserRW", (domainRight & DomainDriver.ACTION_UPDATE_USER) != 0); request.setAttribute("userObject", jobDomainSC.getTargetUserFull()); request.setAttribute("action", "userModify"); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.userUpdate") + "...")); request.setAttribute("minLengthLogin", jobDomainSC.getMinLengthLogin()); request.setAttribute("CurrentUser", jobDomainSC.getUserDetail()); destination = "userCreate.jsp"; } else if (function.startsWith("displayUserMS")) { request.setAttribute("userObject", jobDomainSC.getTargetUserFull()); request.setAttribute("action", "userMS"); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.userUpdate") + "...")); request.setAttribute("minLengthLogin", jobDomainSC.getMinLengthLogin()); request.setAttribute("CurrentUser", jobDomainSC.getUserDetail()); destination = "userCreate.jsp"; } else if (function.startsWith("displayUserImport")) { request.setAttribute("SelectedIds", jobDomainSC.getListSelectedUsers()); request.setAttribute("FirstUserIndex", jobDomainSC.getIndexOfFirstItemToDisplay()); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), jobDomainSC.getString("JDP.userImport") + "...")); request.setAttribute("properties", jobDomainSC.getPropertiesToImport()); destination = "userImport.jsp"; } else if (function.startsWith("displayDomainCreate")) { Domain theNewDomain = new Domain(); theNewDomain.setDriverClassName("com.stratelia.silverpeas.domains.ldapdriver.LDAPDriver"); theNewDomain.setPropFileName("com.stratelia.silverpeas.domains.domain"); theNewDomain.setAuthenticationServer("autDomain"); request.setAttribute("domainObject", theNewDomain); request.setAttribute("action", "domainCreate"); destination = "domainCreate.jsp"; } else if (function.startsWith("displayDomainSQLCreate")) { Domain theNewDomain = new Domain(); request.setAttribute("domainObject", theNewDomain); request.setAttribute("action", "domainSQLCreate"); destination = "domainSQLCreate.jsp"; } else if (function.startsWith("displayDomainModify")) { request.setAttribute("action", "domainModify"); destination = "domainCreate.jsp"; } else if (function.startsWith("displayDomainSQLModify")) { request.setAttribute("action", "domainSQLModify"); destination = "domainSQLCreate.jsp"; } else if (function.startsWith("displayDomainSynchro")) { destination = "domainSynchro.jsp"; } else if (function.startsWith("displayDynamicSynchroReport")) { SynchroReport.setTraceLevel(Integer.parseInt(request.getParameter("IdTraceLevel"))); destination = "dynamicSynchroReport.jsp"; } } else if (function.startsWith("welcome")) { jobDomainSC.returnIntoGroup(null); request.setAttribute("DisplayOperations", jobDomainSC.getUserDetail().isAccessAdmin()); ResourceLocator rs = new ResourceLocator( "com.silverpeas.jobDomainPeas.settings.jobDomainPeasSettings", ""); Properties configuration = new Properties(); configuration.setProperty(SilverpeasTemplate.TEMPLATE_ROOT_DIR, rs.getString("templatePath")); configuration.setProperty(SilverpeasTemplate.TEMPLATE_CUSTOM_DIR, rs.getString("customersTemplatePath")); SilverpeasTemplate template = SilverpeasTemplateFactory.createSilverpeasTemplate(configuration); // setting domains to welcome template List<Domain> allDomains = jobDomainSC.getAllDomains(); // do not return mixed domain String[] domainsByList = new String[allDomains.size() - 1]; for (int n = 1; n < allDomains.size(); n++) { domainsByList[n - 1] = allDomains.get(n).getName(); } template.setAttribute("listDomains", domainsByList); request.setAttribute("Content", template.applyFileTemplate("register_" + jobDomainSC.getLanguage())); destination = "welcome.jsp"; } else if (function.equals("Pagination")) { processSelection(request, jobDomainSC); // traitement de la pagination : passage des parametres String index = request.getParameter("Pagination_Index"); if (index != null && index.length() > 0) { jobDomainSC.setIndexOfFirstItemToDisplay(index); } // retour a l'album courant request.setAttribute("Query", jobDomainSC.getQueryToImport()); request.setAttribute("Users", jobDomainSC.getUsersToImport()); destination = getDestination("displayUserImport", jobDomainSC, request); } else { destination = function; } // 2) Prepare the pages // -------------------- if (jobDomainSC.getTargetDomain() != null) { request.setAttribute("domainObject", jobDomainSC.getTargetDomain()); } if (destination.equals("domainContent.jsp")) { jobDomainSC.refresh(); long domainRight = jobDomainSC.getDomainActions(); request.setAttribute("theUser", jobDomainSC.getUserDetail()); request.setAttribute("subGroups", jobDomainSC.getSubGroups(false)); request.setAttribute("subUsers", jobDomainSC.getSubUsers(false)); request.setAttribute("isDomainRW", ((domainRight & DomainDriver.ACTION_CREATE_GROUP) != 0) || ((domainRight & DomainDriver.ACTION_CREATE_USER) != 0)); request.setAttribute("isUserRW", (domainRight & DomainDriver.ACTION_CREATE_USER) != 0); request.setAttribute("isDomainSync", ((domainRight & DomainDriver.ACTION_SYNCHRO_USER) != 0) || ((domainRight & DomainDriver.ACTION_SYNCHRO_GROUP) != 0)); request.setAttribute("isOnlyGroupManager", jobDomainSC.isOnlyGroupManager()); request.setAttribute("isUserAddingAllowedForGroupManager", jobDomainSC.isUserAddingAllowedForGroupManager()); } else if (destination.equals("groupContent.jsp") || destination.equals("exportgroup.jsp")) { long domainRight = jobDomainSC.getDomainActions(); request.setAttribute("groupObject", jobDomainSC.getTargetGroup()); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), null)); request.setAttribute("subGroups", jobDomainSC.getSubGroups(true)); request.setAttribute("subUsers", jobDomainSC.getSubUsers(true)); request.setAttribute("isDomainRW", ((domainRight & DomainDriver.ACTION_CREATE_GROUP) != 0) || ((domainRight & DomainDriver.ACTION_CREATE_USER) != 0)); request.setAttribute("isUserRW", (domainRight & DomainDriver.ACTION_CREATE_USER) != 0); request.setAttribute("isDomainSync", ((domainRight & DomainDriver.ACTION_SYNCHRO_USER) != 0) || ((domainRight & DomainDriver.ACTION_SYNCHRO_GROUP) != 0)); request.setAttribute("isGroupManagerOnThisGroup", jobDomainSC.isGroupManagerOnCurrentGroup()); request.setAttribute("isGroupManagerDirectlyOnThisGroup", jobDomainSC.isGroupManagerDirectlyOnCurrentGroup()); request.setAttribute("isOnlyGroupManager", jobDomainSC.isOnlyGroupManager()); } else if (destination.equals("userContent.jsp")) { request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), null)); if (jobDomainSC.getTargetDomain() != null) { long domainRight = jobDomainSC.getDomainActions(); SilverTrace.info("jobDomainPeas", "JobDomainPeasRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "domainRight=" + domainRight + " & DomainDriver.ACTION_X509_USER = " + DomainDriver.ACTION_X509_USER); request.setAttribute("isDomainRW", ((domainRight & DomainDriver.ACTION_CREATE_GROUP) != 0) || ((domainRight & DomainDriver.ACTION_CREATE_USER) != 0)); request.setAttribute("isUserRW", (domainRight & DomainDriver.ACTION_CREATE_USER) != 0); request.setAttribute("isDomainSync", ((domainRight & DomainDriver.ACTION_SYNCHRO_USER) != 0) || ((domainRight & DomainDriver.ACTION_SYNCHRO_GROUP) != 0)); request.setAttribute("isX509Enabled", (domainRight & DomainDriver.ACTION_X509_USER) != 0); request.setAttribute("isOnlyGroupManager", jobDomainSC.isOnlyGroupManager()); request.setAttribute("userManageableByGroupManager", jobDomainSC.isUserInAtLeastOneGroupManageableByCurrentUser()); } request.setAttribute("userObject", jobDomainSC.getTargetUserFull()); } else if (destination.equals("domainNavigation.jsp")) { List<Domain> domains = jobDomainSC.getAllDomains(); if (domains.size() == 1) { jobDomainSC.setTargetDomain(domains.get(0).getId()); } request.setAttribute("allDomains", domains); request.setAttribute("allRootGroups", jobDomainSC.getAllRootGroups()); request.setAttribute("CurrentDomain", jobDomainSC.getTargetDomain()); if (jobDomainSC.getTargetDomain() != null) { request.setAttribute("URLForContent", "domainContent"); } else { request.setAttribute("URLForContent", "welcome"); } } else if (destination.equals("groupManagers.jsp")) { request.setAttribute("groupObject", jobDomainSC.getTargetGroup()); request.setAttribute("groupsPath", jobDomainSC.getPath((String) request.getAttribute("myComponentURL"), null)); } // 3) Concat the path // ------------------ if (!destination.startsWith("/")) { destination = "/jobDomainPeas/jsp/" + destination; } } catch (Exception e) { request.setAttribute("javax.servlet.jsp.jspException", e); if (e instanceof SilverpeasTrappedException) { destination = "/admin/jsp/errorpageTrapped.jsp"; } else { destination = "/admin/jsp/errorpageMain.jsp"; } } SilverTrace.info("jobDomainPeas", "JobDomainPeasRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Destination=" + destination); return destination; }