List of usage examples for java.util Vector contains
public boolean contains(Object o)
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Retrieves a list of attributes from an element. * @param ldap/*from w w w. j av a 2s . c o m*/ * A prepared LDAP context. Cannot be <code>null</code>. * @param rdn * The relative DN (to the DN in the LDAP context * <code>ldap</code>). Cannot be <code>null</code>. * @param attributes * The requested attribute's names. Also indirectly referenced * attributes on the form * <code>someReferenceAttribute:someIndirectAttribute</code>, * where the DN in the reference attribute * <code>someReferenceAttribute</code> is followed to look up * <code>someIndirectAttribute</code> from another element. * @return The requested attributes (<code>String</code> names and * <code>String[]</code> values), if they did exist in the * external backend. Otherwise returns those attributes that could * actually be read, this may be an empty <code>HashMap</code>. * Returns an empty <code>HashMap</code> if * <code>attributes</code> is <code>null</code> or an empty * array. Note that attribute values are mapped to * <code>String</code> using ISO-8859-1. * @throws BackendException * If unable to read the attributes from the backend. * @throws NullPointerException * If <code>ldap</code> or <code>rdn</code> is * <code>null</code>. * @see javax.naming.directory.InitialDirContext#getAttributes(java.lang.String, * java.lang.String[]) */ private HashMap<String, String[]> getAttributes(final InitialLdapContext ldap, final String rdn, final String[] attributes) throws BackendException { // Sanity checks. if (ldap == null) throw new NullPointerException("LDAP context cannot be NULL"); if (rdn == null) throw new NullPointerException("RDN cannot be NULL"); if ((attributes == null) || (attributes.length == 0)) return new HashMap<String, String[]>(); // Used to remember attributes to be read through references later on. Hashtable<String, Vector> attributeReferences = new Hashtable<String, Vector>(); // Strip down request, resolving references and removing duplicates. Vector<String> strippedAttributeRequest = new Vector<String>(); for (int i = 0; i < attributes.length; i++) { int indexOfSplitCharacter = attributes[i] .indexOf(DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR); if (indexOfSplitCharacter == -1) { // A regular attribute request. if (!strippedAttributeRequest.contains(attributes[i])) strippedAttributeRequest.add(attributes[i]); } else { // A referenced attribute request. final String referencingAttribute = attributes[i].substring(0, indexOfSplitCharacter); if (!strippedAttributeRequest.contains(referencingAttribute)) strippedAttributeRequest.add(referencingAttribute); // Add to list of attributes to be read through each reference. if (!attributeReferences.containsKey(referencingAttribute)) { // Add new reference. Vector<String> referencedAttribute = new Vector<String>(); referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1)); attributeReferences.put(referencingAttribute, referencedAttribute); } else { // Update existing reference. Vector<String> referencedAttribute = attributeReferences.get(referencingAttribute); if (!referencedAttribute.contains(attributes[i].substring(indexOfSplitCharacter + 1))) referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1)); } } } // The context provider URL and DN, for later logging. String url = "unknown backend"; String dn = "unknown dn"; // Get the attributes from an already initialized LDAP connection. Attributes rawAttributes = null; try { // Remember the URL and bind DN, for later logging. final Hashtable environment = ldap.getEnvironment(); url = (String) environment.get(Context.PROVIDER_URL); dn = (String) environment.get(Context.SECURITY_PRINCIPAL); // Get the attributes. rawAttributes = ldap.getAttributes(rdn, strippedAttributeRequest.toArray(new String[] {})); } catch (NameNotFoundException e) { // Successful authentication but missing user element; no attributes // returned and the event is logged. log.logWarn("No LDAP element found (DN was '" + dn + "')", mySessionTicket); rawAttributes = new BasicAttributes(); } catch (NamingException e) { String a = new String(); for (int i = 0; i < attributes.length; i++) a = a + attributes[i] + ", "; throw new BackendException("Unable to read attribute(s) '" + a.substring(0, a.length() - 2) + "' from '" + rdn + "' on '" + url + "'", e); } // Translate retrieved attributes from Attributes to HashMap. HashMap<String, String[]> convertedAttributes = new HashMap<String, String[]>(); for (int i = 0; i < attributes.length; i++) { // Did we get any attribute back at all? final String requestedAttribute = attributes[i]; Attribute rawAttribute = rawAttributes.get(requestedAttribute); if (rawAttribute == null) { // Attribute was not returned. log.logDebug("Requested attribute '" + requestedAttribute + "' not found on '" + url + "'", mySessionTicket); } else { // Map the attribute values to String[]. ArrayList<String> convertedAttributeValues = new ArrayList<String>(rawAttribute.size()); for (int j = 0; j < rawAttribute.size(); j++) { try { // We either have a String or a byte[]. String convertedAttributeValue = null; try { // Encode String. convertedAttributeValue = new String(((String) rawAttribute.get(j)).getBytes(), DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET); } catch (ClassCastException e) { // Encode byte[] to String. convertedAttributeValue = new String(Base64.encodeBase64((byte[]) rawAttribute.get(j)), DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET); } convertedAttributeValues.add(convertedAttributeValue); } catch (NamingException e) { throw new BackendException("Unable to read attribute value of '" + rawAttribute.getID() + "' from '" + url + "'", e); } catch (UnsupportedEncodingException e) { throw new BackendException( "Unable to use " + DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET + " encoding", e); } } convertedAttributes.put(requestedAttribute, convertedAttributeValues.toArray(new String[] {})); } } // Follow references to look up any indirectly referenced attributes. Enumeration<String> keys = attributeReferences.keys(); while (keys.hasMoreElements()) { // Do we have a reference? final String referencingAttribute = keys.nextElement(); final String[] referencingValues = convertedAttributes.get(referencingAttribute); if (referencingValues == null) { // No reference was found in this attribute. log.logDebug("Found no DN references in attribute '" + referencingAttribute + "'", mySessionTicket); } else { // One (or more) references was found in this attribute. if (referencingValues.length > 1) log.logDebug("Found " + referencingValues.length + " DN references in attribute '" + referencingAttribute + "'; ignoring all but first", mySessionTicket); log.logDebug("Following reference '" + referencingValues[0] + "' found in '" + referencingAttribute + "' to look up attribute(s) '" + attributeReferences.get(referencingAttribute).toString(), mySessionTicket); String providerURL = null; // To be used later. try { // Follow the reference. providerURL = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); providerURL = providerURL.substring(0, providerURL.lastIndexOf("/") + 1) + referencingValues[0]; ldap.addToEnvironment(Context.PROVIDER_URL, providerURL); } catch (NamingException e) { throw new BackendException("Unable to update provider URL in LDAP environment", e); } // Add any referenced attributes returned. HashMap additionalAttributes = getAttributes(ldap, providerURL, (String[]) attributeReferences.get(referencingAttribute).toArray(new String[] {})); Iterator i = additionalAttributes.keySet().iterator(); while (i.hasNext()) { String attributeName = (String) i.next(); convertedAttributes.put(referencingAttribute + DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR + attributeName, (String[]) additionalAttributes.get(attributeName)); } } } return convertedAttributes; }
From source file:org.wise.portal.presentation.web.controllers.ContactWiseController.java
@RequestMapping(method = RequestMethod.POST) public String onSubmit(@ModelAttribute("contactWISEForm") ContactWISEForm contactWISEForm, BindingResult result, HttpServletRequest request) throws Exception { contactWISEValidator.validate(contactWISEForm, result); checkRecaptcha(request, result);// www .ja v a 2 s.com getTeacherNameAndSetInForm(contactWISEForm); if (result.hasErrors()) { return "contact/contactwise"; } // get our user key for the user agent parse site String userKey = wiseProperties.getProperty("userAgentParseKey"); if (userKey != null && !userKey.equals("")) { // get the user agent from the request String userAgent = request.getParameter("usersystem"); HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(userAgentParseURL); // add the user_key and user_agent parameters to the POST request List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("user_key", userKey)); urlParameters.add(new BasicNameValuePair("user_agent", userAgent)); post.setEntity(new UrlEncodedFormEntity(urlParameters)); try { // execute the POST HttpResponse response = client.execute(post); // read the response BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer userAgentParseResult = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { userAgentParseResult.append(line); } String parseResultString = userAgentParseResult.toString(); try { // get the response as a JSON object JSONObject parseResultJSONObject = new JSONObject(parseResultString); // get whether the request succeeded String parseResult = parseResultJSONObject.getString("result"); if (parseResult != null && parseResult.equals("success")) { // the request succeeded so we will get the data JSONObject parse = parseResultJSONObject.getJSONObject("parse"); // get the operating system and browser values String operatingSystemName = parse.getString("operating_system_name"); String operatingSystemVersion = parse.getString("operating_system_version_full"); String browserName = parse.getString("browser_name"); String browserVersion = parse.getString("browser_version_full"); // set the values into the form so that we can use them later when creating the email message contactWISEForm.setOperatingSystemName(operatingSystemName); contactWISEForm.setOperatingSystemVersion(operatingSystemVersion); contactWISEForm.setBrowserName(browserName); contactWISEForm.setBrowserVersion(browserVersion); } } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //retrieves the contents of the email to be sent String[] recipients = getMailRecipients(); String[] cc = getMailCcs(contactWISEForm); String subject = contactWISEForm.getMailSubject(); String fromEmail = contactWISEForm.getEmail(); String message = contactWISEForm.getMailMessage(); //fromEmail will be null if the signed in user is a student if (fromEmail == null) { /* * set the fromEmail to a non null and non empty string otherwise * an exception will be thrown */ fromEmail = "null"; } //get the run id Long runId = contactWISEForm.getRunId(); /* * if a student is submitting the contactwiseproject form, the runId will * be set. if a teacher is submitting the contactwiseproject form, the * runId will not be set. this is ok because the teacher is the run * owner and their email is already in the cc array */ if (runId != null) { Run run = runService.retrieveById(runId); Vector<String> runOwnerEmailAddresses = new Vector<String>(); User runOwner = run.getOwner(); MutableUserDetails userDetails = runOwner.getUserDetails(); //get the run owner email address String emailAddress = userDetails.getEmailAddress(); if (emailAddress != null) { runOwnerEmailAddresses.add(emailAddress); } if (!runOwnerEmailAddresses.isEmpty()) { //we have run owner email addresses for (int x = 0; x < cc.length; x++) { if (!runOwnerEmailAddresses.contains(cc[x])) { //add the cc emails to the run owner emails to merge them runOwnerEmailAddresses.add(cc[x]); } } //create a new String array the same size as the runOwnerEmailAddresses cc = new String[runOwnerEmailAddresses.size()]; //put all the email addresses back into the cc array for (int x = 0; x < runOwnerEmailAddresses.size(); x++) { cc[x] = runOwnerEmailAddresses.get(x); } } } //for testing out the email functionality without spamming the groups if (DEBUG) { cc = new String[1]; cc[0] = fromEmail; recipients[0] = DEBUG_EMAIL; } //sends the email to the recipients mailService.postMail(recipients, subject, message, fromEmail, cc); return "contact/contactwiseconfirm"; }
From source file:gov.nih.nci.evs.browser.utils.TreeUtils.java
public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try {/* w w w. ja v a 2 s. c om*/ LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); java.lang.String[] ids = hierarchies[0].getAssociationIds(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; }
From source file:org.mahasen.node.MahasenNodeManager.java
/** * @param propertyName// w w w .j a v a 2 s .co m * @param propertyValue * @return * @throws InterruptedException */ public Vector<Id> getSearchResults(String propertyName, String propertyValue) throws InterruptedException { final Vector<Id> resultIds = new Vector<Id>(); // block until we get a result or time out. final BlockFlag blockFlag = new BlockFlag(true, 1500); mahasenPastTreeApp.getSearchResults(propertyName, propertyValue, new Continuation() { public void receiveResult(Object result) { if (result != null) { if (resultIds.isEmpty()) { resultIds.addAll((Vector<Id>) result); } else { Vector<Id> tempIdSet = (Vector<Id>) result; for (Id id : tempIdSet) { if (!resultIds.contains(id)) { resultIds.add(id); } } } } blockFlag.unblock(); } public void receiveException(Exception exception) { System.out.println(" Result not found "); blockFlag.unblock(); } }); while (blockFlag.isBlocked()) { env.getTimeSource().sleep(10); } return resultIds; }
From source file:org.mahasen.node.MahasenNodeManager.java
/** * @param propertyName//from w w w . j av a 2 s. c om * @param initialValue * @param lastValue * @return * @throws InterruptedException */ public Vector<Id> getRangeSearchResults(String propertyName, String initialValue, String lastValue) throws InterruptedException { final Vector<Id> resultIds = new Vector<Id>(); // block until we get a result or time out. final BlockFlag blockFlag = new BlockFlag(true, 1500); mahasenPastTreeApp.getRangeSearchResults(propertyName, initialValue, lastValue, new Continuation() { public void receiveResult(Object result) { if (result != null) { if (resultIds.isEmpty()) { resultIds.addAll((Vector<Id>) result); } else { Vector<Id> tempIdSet = (Vector<Id>) result; for (Id id : tempIdSet) { if (!resultIds.contains(id)) { resultIds.add(id); } } } } blockFlag.unblock(); } public void receiveException(Exception exception) { System.out.println(" Result not found "); blockFlag.unblock(); } }); while (blockFlag.isBlocked()) { env.getTimeSource().sleep(10); } return resultIds; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java
/** * @return // w w w . j a v a 2s . c o m */ protected String getAttachToTableName() { String attachToTableName = null; List<UploadTable> attachableTbls = wbPane.getAttachableTables(); if (attachableTbls == null || attachableTbls.size() == 0) { //XXX message about default attachment table } else { if (attachableTbls.size() == 1) { attachToTableName = attachableTbls.get(0).getTable().getName(); } else { Vector<Pair<String, String>> titleNamePairs = new Vector<Pair<String, String>>(); Vector<String> titles = new Vector<String>(); for (UploadTable ut : attachableTbls) { String tblTitle = ut.getTblClass().equals(Agent.class) ? ut.toString() : ut.getTblTitle(); if (!titles.contains(tblTitle)) ; { String tblSpec = ut.getTable().getName(); if (ut.getTblClass().equals(Agent.class) && ut.getRelationship() != null) { tblSpec += "." + ut.getRelationship().getRelatedField().getTable().getTableInfo().getName(); } titleNamePairs.add(new Pair<String, String>(tblTitle, tblSpec)); titles.add(tblTitle); } } ChooseFromListDlg<String> dlg = new ChooseFromListDlg<String>( (Frame) UIRegistry.getMostRecentWindow(), UIRegistry.getResourceString("ImageFrame.ChooseAttachTableDlgTitle"), titles); UIHelper.centerAndShow(dlg); if (!dlg.isCancelled()) { for (Pair<String, String> p : titleNamePairs) { if (p.getFirst().equals(dlg.getSelectedObject())) { attachToTableName = p.getSecond(); break; } } } else { attachToTableName = ""; } dlg.dispose(); } } return attachToTableName; }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.internal.jdbc.JDBCInternalStorage.java
/** * Update the supplied user profile in the profile table. * @param oConnection the connection// w w w .j ava2 s. c o m * @param user the user that must be updated * @throws UserException if update fails */ private void updateProfile(Connection oConnection, ProvisioningUser user) throws UserException { ResultSet oResultSet = null; PreparedStatement psRetrieve = null; PreparedStatement psInsert = null; try { Vector<String> vExistingMethodIDs = new Vector<String>(); psRetrieve = oConnection.prepareStatement(_sProfileSelect); psRetrieve.setString(1, user.getID()); oResultSet = psRetrieve.executeQuery(); String sUserID = user.getID(); while (oResultSet.next()) { sUserID = oResultSet.getString(COLUMN_PROFILE_ID); String sMethodID = oResultSet.getString(COLUMN_PROFILE_AUTHSPID); vExistingMethodIDs.add(sMethodID); } psInsert = oConnection.prepareStatement(_sProfileInsert); psInsert.setString(1, sUserID); for (String sMethod : user.getAuthenticationMethods()) { if (!vExistingMethodIDs.contains(sMethod)) { psInsert.setString(2, sMethod); psInsert.setBoolean(3, user.isAuthenticationRegistered(sMethod)); psInsert.addBatch(); } } int[] iInserts = psInsert.executeBatch(); _logger.debug("Total number of update queries performed in batch: " + iInserts.length); } catch (SQLException e) { _logger.error("Could not update profile for user with id: " + user.getID(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_UPDATE); } catch (Exception e) { _logger.fatal("Could not update profile", e); throw new UserException(SystemErrors.ERROR_INTERNAL); } finally { try { if (psRetrieve != null) psRetrieve.close(); } catch (Exception e) { _logger.error("Could not close retrieve statement", e); } try { if (psInsert != null) psInsert.close(); } catch (Exception e) { _logger.error("Could not close insert statement", e); } } }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.BarCharts.java
/** * Limits the dataset to a particular serie. * //from w ww . ja v a2 s.co m * @param dataset the dataset * @param serie the serie * * @return the dataset */ public Dataset filterDatasetSeries(Dataset dataset, Vector series) { logger.debug("IN"); DefaultCategoryDataset catDataset = (DefaultCategoryDataset) dataset; //keeps track of wich series has to be shown currentSeries = series; //List rowKeys=new Vector(); List rowKeys = new Vector(catDataset.getRowKeys()); for (Iterator iterator = rowKeys.iterator(); iterator.hasNext();) { String row = (String) iterator.next(); if (!(series.contains(row))) { catDataset.removeRow(row); seriesNames.remove(row); } } logger.debug("OUT"); return catDataset; }
From source file:org.openxdata.server.sms.FormSmsParser.java
/** * Get the validation error messages in a filled form. * // www . jav a 2 s. c o m * @param formData the form data to validate. * @param ruleRequiredQtns a list of questions which become required after a firing of some rules. * @return a comma separated list of validation error messages if any, else null. */ @SuppressWarnings("unchecked") private String getValidationErrorMsg(org.openxdata.model.FormData formData, Vector<QuestionData> ruleRequiredQtns) { String sErrors = null; //Check if form has any questions. Vector<PageData> pages = formData.getPages(); if (pages == null || pages.size() == 0) { sErrors = MSG_FORM_HAS_NO_QUESTIONS; return sErrors; } //First get error messages for required fields which have not been answered //and answers not allowed for the data type. for (byte i = 0; i < pages.size(); i++) { PageData page = (PageData) pages.elementAt(i); for (byte j = 0; j < page.getQuestions().size(); j++) { QuestionData qtn = (QuestionData) page.getQuestions().elementAt(j); if (!ruleRequiredQtns.contains(qtn) && !qtn.isValid()) sErrors = addErrorMsg(sErrors, MSG_ANSWER_REQUIRED_FOR + " " + qtn.getDef().getText()); //Do data type validation String msg = getTypeErrorMsg(qtn); if (msg != null) sErrors = addErrorMsg(sErrors, msg); } } //Check if form has any validation rules. Vector<ValidationRule> rules = formData.getDef().getValidationRules(); if (rules == null) return sErrors; //Deal with the user supplied validation rules for (int index = 0; index < rules.size(); index++) { ValidationRule rule = (ValidationRule) rules.elementAt(index); rule.setFormData(formData); if (!rule.isValid()) sErrors = addErrorMsg(sErrors, rule.getErrorMessage()); } return sErrors; }
From source file:gate.annotation.AnnotationSetImpl.java
@Override public synchronized void addGateListener(GateListener l) { @SuppressWarnings("unchecked") Vector<GateListener> v = gateListeners == null ? new Vector<GateListener>(2) : (Vector<GateListener>) gateListeners.clone(); if (!v.contains(l)) { v.addElement(l);//from ww w .jav a 2s. com gateListeners = v; } }