List of usage examples for javax.naming NamingException getMessage
public String getMessage()
From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java
private void populateDCMap() throws UserStoreException { try {/*from w ww. jav a 2 s .co m*/ //get the directory context for DNS DirContext dnsContext = new InitialDirContext(environmentForDNS); //compose the DNS service to be queried String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName; //query the DNS Attributes attributes = dnsContext.getAttributes(DNSServiceName, new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME }); Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME); //there can be multiple records with same domain name - get them all NamingEnumeration srvValues = srvRecords.getAll(); dcMap = new TreeMap<Integer, SRVRecord>(); //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap //int forcedPriority = 0; while (srvValues.hasMore()) { String value = srvValues.next().toString(); SRVRecord srvRecord = new SRVRecord(); String valueItems[] = value.split(" "); String priority = valueItems[0]; if (priority != null) { int priorityInt = Integer.parseInt(priority); /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) { forcedPriority++; priorityInt = forcedPriority; }*/ srvRecord.setPriority(priorityInt); } /* else { forcedPriority++; srvRecord.setPriority(forcedPriority); }*/ String weight = valueItems[1]; if (weight != null) { srvRecord.setWeight(Integer.parseInt(weight)); } String port = valueItems[2]; if (port != null) { srvRecord.setPort(Integer.parseInt(port)); } String host = valueItems[3]; if (host != null) { srvRecord.setHostName(host); } //we index dcMap on priority basis, therefore, priorities must be different dcMap.put(srvRecord.getPriority(), srvRecord); } //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the //host records for that for (SRVRecord srvRecord : dcMap.values()) { Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(), new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME }); Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME); //we know there is only one IP value for a given host. So we do just get, not getAll srvRecord.setHostIP((String) hostRecord.get()); } } catch (NamingException e) { log.error("Error obtaining information from DNS Server" + e.getMessage(), e); throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e); } }
From source file:org.wso2.carbon.ml.model.internal.DatabaseHandler.java
/** * DatabaseHandler constructor// w w w .j a va 2 s .co m * * @throws DatabaseHandlerException */ public DatabaseHandler() throws DatabaseHandlerException { try { Context initContext = new InitialContext(); dataSource = (DataSource) initContext.lookup(MLModelConstants.ML_DB); } catch (NamingException e) { throw new DatabaseHandlerException( "An error occured while obtaining the data source: " + e.getMessage(), e); } }
From source file:org.teiid.rhq.plugin.TranslatorComponent.java
@Override public Configuration loadResourceConfiguration() { ManagedComponent translator = null;/*from w w w. j a va2s .com*/ try { translator = ProfileServiceUtil.getManagedComponent(getConnection(), new ComponentType(PluginConstants.ComponentType.Translator.TYPE, PluginConstants.ComponentType.Translator.SUBTYPE), this.name); } catch (NamingException e) { final String msg = "NamingException in loadResourceConfiguration(): " + e.getExplanation(); //$NON-NLS-1$ LOG.error(msg, e); } catch (Exception e) { final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$ LOG.error(msg, e); } String translatorName = ProfileServiceUtil.getSimpleValue(translator, "name", String.class); String description = ProfileServiceUtil.getSimpleValue(translator, "description", String.class); Configuration c = resourceConfiguration; PropertyList list = new PropertyList("translatorList"); PropertyMap propMap = null; c.put(list); // First get translator specific properties ManagedProperty translatorProps = translator.getProperty("property"); try { getTranslatorValues(translatorProps.getValue(), propMap, list); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } // Now get common properties c.put(new PropertySimple("name", translatorName)); c.put(new PropertySimple("description", description)); return c; }
From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java
public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse, LDAPResolver ldapResolver) throws PIPException { /*/*from w w w . ja v a2s .co m*/ * Check with the resolver to get the base string */ String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder); if (stringBase == null) { this.logger.warn(this.getName() + " does not handle " + pipRequest.toString()); return; } /* * Get the filter string */ String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder); /* * Check the cache */ Cache<String, PIPResponse> cache = this.getCache(); String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter); if (cache != null) { PIPResponse pipResponse = cache.getIfPresent(cacheKey); if (pipResponse != null) { if (this.logger.isDebugEnabled()) { this.logger.debug("Returning cached response: " + pipResponse); } mutablePIPResponse.addAttributes(pipResponse.getAttributes()); return; } } /* * Not in the cache, so set up the LDAP query session */ DirContext dirContext = null; PIPResponse pipResponse = null; try { /* * Create the DirContext */ dirContext = new InitialDirContext(this.ldapEnvironment); /* * Set up the search controls */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(this.ldapScope); /* * Do the search */ NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter, searchControls); if (namingEnumeration != null && namingEnumeration.hasMore()) { while (namingEnumeration.hasMore()) { List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next()); if (listAttributes != null && listAttributes.size() > 0) { mutablePIPResponse.addAttributes(listAttributes); } } } /* * Put in the cache */ if (cache != null) { cache.put(cacheKey, pipResponse); } } catch (NamingException ex) { this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex); } finally { if (dirContext != null) { try { dirContext.close(); } catch (Exception ex) { this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex); } } } }
From source file:net.sf.ehcache.distribution.JNDIManualRMICacheManagerPeerProvider.java
/** * Register a new peer by looking it up in JNDI and storing * in a local cache the Context./* w ww .j a v a 2 s . c o m*/ * * @param jndiProviderUrl */ private Context registerPeerToContext(String jndiProviderUrl) { String initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (LOG.isDebugEnabled()) { LOG.debug("registerPeerToContext: " + jndiProviderUrl + " " + extractProviderUrl(jndiProviderUrl) + " with " + initialContextFactory); } Hashtable hashTable = new Hashtable(1); hashTable.put(Context.PROVIDER_URL, extractProviderUrl(jndiProviderUrl)); Context initialContext = null; try { initialContext = new InitialContext(hashTable); registerPeerToContext(jndiProviderUrl, initialContext); } catch (NamingException e) { LOG.warn(jndiProviderUrl + " " + e.getMessage()); registerPeerToContext(jndiProviderUrl, null); } return initialContext; }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
/** * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#createUser(org.apache.archiva.redback.users.User, javax.naming.directory.DirContext, boolean) *///from ww w .java2 s . c om public void createUser(User user, DirContext context, boolean encodePasswordIfChanged) throws LdapControllerException, MappingException { if (user == null) { return; } if (user.getUsername().equals(UserManager.GUEST_USERNAME)) { log.warn("skip user '{}' creation"); //We don't store guest return; } boolean userExists = userExists(user.getUsername(), context); if (userExists) { log.debug("user '{}' exists skip creation", user.getUsername()); return; } if (writableLdap) { try { bindUserObject(context, user); log.info("user {} created in ldap", user.getUsername()); } catch (NamingException e) { throw new LdapControllerException(e.getMessage(), e); } } }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the initial context/*w w w . j a va 2 s .c om*/ * * @param providerUrl * @param bindDN * @param bindPassword * @return */ public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) { List<String> trace = new ArrayList<String>(); LOGGER.debug("providerURL: " + providerUrl); trace.add("Attempting to connect to the LDAP server..."); if (providerUrl != null && providerUrl.startsWith("ldaps:")) { System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE); trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE); File ks = new File(PATH_TO_KEY_STORE); if (!ks.exists()) { trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE); } } if (providerUrl == null) { LOGGER.warn("LDAP provider URL should not be null."); return null; } Hashtable<String, Object> env = new Hashtable<String, Object>(); if (LOGGER.isDebugEnabled()) { env.put("com.sun.jndi.ldape.trace.ber", System.err); } env.put("java.naming.ldap.version", "3"); env.put("com.sun.jndi.ldap.connect.timeout", "10000"); env.put("com.sun.jndi.dns.timeout.initial", "2000"); env.put("com.sun.jndi.dns.timeout.retries", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); if ((bindDN != null) && !bindDN.equals("")) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDN); env.put(Context.SECURITY_CREDENTIALS, bindPassword); LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*")); trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****"); } else { LOGGER.debug("bind anonymous"); trace.add("Preparing to bind anonymously to the LDAP server"); } try { return new InitialLdapContext(env, null); } catch (NamingException e) { for (String msg : trace) { LOGGER.error(msg); } LOGGER.error("Getting the initial ldap context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); try { new InitialDirContext(env); } catch (NamingException e1) { LOGGER.error("Getting the initial dir context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; } }
From source file:org.air.standard.web.presentation.FileUploadHandler.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//from w w w. ja va2s .c om */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { _logger.debug("FileUploadhandler fired!"); String initParameterFileType = getServletConfig().getInitParameter("fileType"); String ooExecPath = null; String ooSpreadsheetPath = null; File uploadedFile = null; try { InitialContext context = new InitialContext(); ooExecPath = request.getSession().getServletContext().getInitParameter("ooExecPath"); ooSpreadsheetPath = request.getSession().getServletContext().getInitParameter("ooSpreadsheetPath"); // ooExecPath = container.getInitParameter("ooExecPath"); // ooSpreadsheetPath = container.getInitParameter("ooSpreadsheetPath"); // ooExecPath = (String) context.lookup("java:comp/env/ooExecPath"); // ooSpreadsheetPath = (String) context // .lookup("java:comp/env/ooSpreadsheetPath"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); // LoggerFactory.LogInfo("TEST File upload MANAGER", getClass()); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request _logger.debug("Before parseRequest"); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); BufferedInputStream buf = null; ServletOutputStream stream = null; while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); if (fileName.isEmpty()) throw new InvalidArgumentException("File to Upload ", "not empty"); _logger.debug("Parsed file file " + fileName); File uploadDirectory = new File(ooSpreadsheetPath); if (!uploadDirectory.exists()) { boolean status = uploadDirectory.mkdirs(); } if (!uploadDirectory.exists()) throw new ContentStandardException( "Problems accessing " + ooSpreadsheetPath + "server directory"); // just so that we do not have a name clash // we will prefix the current time stamp to the file // name. Date date = new Date(); String filePath = ooSpreadsheetPath + "/" + date.getTime() + fileName; uploadedFile = new File(filePath); /*if (!uploadedFile.canWrite() || !uploadedFile.canRead()) throw new ContentStandardException( "Problem with read or write access to files in " + ooSpreadsheetPath + " server directory"); */ /* * System.out.println(uploadedFile.getAbsolutePath()) * ; */ item.write(uploadedFile); _logger.debug("Wrote temp file " + uploadedFile.getAbsolutePath()); } } } catch (SecurityException se) { // can be thrown by canWrite, canRead, exists, mkdirs calls // if server is not configured with correct access rights _logger.error("Problem with access rights to " + ooSpreadsheetPath + " service directory. " + se.getMessage()); displayError(se, response); return; } catch (ContentStandardException cse) { _logger.error(cse.getMessage()); displayError(cse, response); return; } catch (InvalidArgumentException iae) { // EF: do not use displayError because it sets // SC_INTERNAL_SERVLET_ERROR and this is not the case! _logger.error("FileUploadException: " + iae.getMessage()); ReturnStatus<Exception> status = new ReturnStatus<Exception>("failed"); status.setPayload(null); status.appendToErrors(iae.getMessage()); ObjectMapper mapper = new ObjectMapper(); String statusJson = mapper.writeValueAsString(status); // serialize the status object. response.setContentType("application/json"); response.getOutputStream().print(statusJson); return; } catch (FileUploadException e) { e.printStackTrace(); _logger.error("FileUpload Exception: " + e.getMessage()); displayError(e, response); return; } catch (Exception e) { _logger.error("Problem parsing request/creating temp file : " + e.getMessage()); e.printStackTrace(); displayError(e, response); return; } } /* System.out.println("CONFIG FILE:::" + ooExecPath); */ } catch (NamingException ex) { /* System.out.println("exception in jndi lookup"); */ _logger.error("NamingException in jndi lookup" + ex.getMessage()); displayError(ex, response); return; } ObjectMapper mapper = new ObjectMapper(); String statusJson = null; try { ReturnStatus<String> status = new ReturnStatus<String>("success"); //TODO Shiva how to get the bean factory here so that we can remove (new WebUserInformation()) and call the bean instead? String sessionKey = (new WebUserInformation()).getSessionKey(); // clear out existing staging tables for this session key. LoaderTablesDAO dao = new LoaderTablesDAO(); dao.loaderClear(sessionKey); // tell DB what kind of upload we are doing - full or partial. PublicationDAO publicationDAO = new PublicationDAO(); if (initParameterFileType.equalsIgnoreCase("full")) { publicationDAO.importPublication(sessionKey); } else if (initParameterFileType.equalsIgnoreCase("partial")) { publicationDAO.partialImportPublication(sessionKey); } _logger.debug("About to call importFromFile for " + uploadedFile.getAbsolutePath()); OpenOfficeImporter openOfficeImporter = new OpenOfficeImporter(); openOfficeImporter.importFromFile(ooExecPath, uploadedFile.getAbsolutePath(), sessionKey, status); _logger.debug("Finished importFromFile for" + uploadedFile.getAbsolutePath() + " status is " + status.getStatus()); statusJson = mapper.writeValueAsString(status); // serialize the status object. response.setContentType("application/json"); response.getOutputStream().print(statusJson); _logger.debug("Sent json response "); } catch (Exception exp) { _logger.error("Exception after temp file created " + exp.getMessage()); exp.printStackTrace(); displayError(exp, response); } }
From source file:org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImpl.java
@Override public boolean check(String email) throws TalendSMTPRuntimeException { if (email == null) { if (LOG.isInfoEnabled()) { LOG.info("mail is empty."); //$NON-NLS-1$ }/* w ww . j a va 2 s . c o m*/ return false; } // Find the separator for the domain name int pos = email.indexOf('@'); // If the email does not contain an '@', it's not valid if (pos == -1) { if (LOG.isInfoEnabled()) { LOG.info("no @ charactor in the mail string."); } return false; } // check loose email regex final Matcher matcher = emailPattern.matcher(email); if (!matcher.find()) { if (LOG.isInfoEnabled()) { LOG.info(HEADER + "Invalid email syntax for " + email); //$NON-NLS-1$ } return false; } // Isolate the domain/machine name and get a list of mail exchangers String domain = email.substring(++pos); List<String> mxList = null; try { mxList = getMX(domain); } catch (NamingException ex) { if (LOG.isInfoEnabled()) { LOG.info(ex.getMessage()); } // talend email on the outside of office room case throw new TalendSMTPRuntimeException(ex.getMessage()); } // Just because we can send mail to the domain, doesn't mean that the // email is valid, but if we can't, it's a sure sign that it isn't if (mxList.isEmpty()) { if (LOG.isInfoEnabled()) { LOG.info("MX size is 0"); //$NON-NLS-1$ } return false; } // Now, do the SMTP validation, try each mail exchanger until we get // a positive acceptance. It *MAY* be possible for one MX to allow // a message [store and forwarder for example] and another [like // the actual mail server] to reject it. This is why we REALLY ought // to take the preference into account. String errorMessage = StringUtils.EMPTY; for (int mx = 0; mx < mxList.size(); mx++) { try { int res; Socket skt = new Socket(mxList.get(mx), port); BufferedReader rdr = new BufferedReader(new InputStreamReader(skt.getInputStream())); BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream())); res = getResponse(rdr); if (res != 220) { // SMTP Service ready. skt.close(); if (LOG.isInfoEnabled()) { LOG.info(HEADER + "Invalid header:" + mxList.get(mx)); //$NON-NLS-1$ } return false; } write(wtr, "EHLO " + domain); //$NON-NLS-1$ res = getResponse(rdr); if (res != 250) { skt.close(); if (LOG.isInfoEnabled()) { LOG.info(HEADER + "Not ESMTP: " + domain); //$NON-NLS-1$ } return false; } // validate the sender email write(wtr, "MAIL FROM: <" + email + ">"); //$NON-NLS-1$//$NON-NLS-2$ res = getResponse(rdr); if (res != 250) { skt.close(); if (LOG.isInfoEnabled()) { LOG.info(HEADER + "Sender rejected: " + email); //$NON-NLS-1$ } return false; } write(wtr, "RCPT TO: <" + email + ">"); //$NON-NLS-1$//$NON-NLS-2$ res = getResponse(rdr); // be polite write(wtr, "RSET"); //$NON-NLS-1$ getResponse(rdr); write(wtr, "QUIT"); //$NON-NLS-1$ getResponse(rdr); if (res != 250) { skt.close(); return false; } rdr.close(); wtr.close(); skt.close(); return true; } catch (IOException e) { // Do nothing but try next host if (LOG.isDebugEnabled()) { LOG.debug("Connection to " + mxList.get(mx) + " failed.", e); //$NON-NLS-1$ //$NON-NLS-2$ } errorMessage = e.getMessage(); continue; } } throw new TalendSMTPRuntimeException(errorMessage); }
From source file:net.sf.ehcache.distribution.JNDIManualRMICacheManagerPeerProvider.java
/** * @return a list of {@link CachePeer} peers, excluding the local peer. *///from w w w. j a v a 2s.c om public List listRemoteCachePeers(Ehcache cache) throws CacheException { List remoteCachePeers = new ArrayList(); List staleCachePeers = new ArrayList(); String jndiProviderUrl = null; synchronized (lock) { for (Iterator iterator = peerUrls.keySet().iterator(); iterator.hasNext();) { jndiProviderUrl = (String) iterator.next(); String providerUrlCacheName = extractCacheName(jndiProviderUrl); try { if (!providerUrlCacheName.equals(cache.getName())) { continue; } CachePeer cachePeer = lookupCachePeer(jndiProviderUrl); remoteCachePeers.add(cachePeer); } catch (NamingException ne) { LOG.debug(jndiProviderUrl + " " + ne.getMessage()); staleCachePeers.add(jndiProviderUrl); } catch (Exception ex) { LOG.error(ex.getMessage(), ex); throw new CacheException( jndiProviderUrl + " Unable to list remote cache peers. Error was " + ex.getMessage(), ex); } } } if (!staleCachePeers.isEmpty()) { // Do this after loop so don't modify peerUrls in it. unregisterStalePeers(staleCachePeers); } if (LOG.isDebugEnabled()) { try { LOG.debug("listRemoteCachePeers " + cache.getName() + " returning " + remoteCachePeers.size() + " " + printCachePeers(remoteCachePeers)); } catch (RemoteException e) { LOG.warn(e.getMessage(), e); LOG.debug("listRemoteCachePeers " + cache.getName() + " returning " + remoteCachePeers.size()); } } return remoteCachePeers; }