Example usage for javax.naming NamingException toString

List of usage examples for javax.naming NamingException toString

Introduction

In this page you can find the example usage for javax.naming NamingException toString.

Prototype

public String toString() 

Source Link

Document

Generates the string representation of this exception.

Usage

From source file:org.apache.cocoon.transformation.LDAPTransformer.java

/**
 * This will be the meat of LDAPTransformer, where the query is run.
 *//*from ww  w  .ja  va  2  s  .  c  o m*/
protected void executeQuery(int index) throws SAXException {
    this.contentHandler.startPrefixMapping("", LDAPTransformer.my_uri);
    LDAPQuery query = (LDAPQuery) queries.elementAt(index);
    try {
        query.execute();
    } catch (NamingException e) {
        getLogger().error(e.toString());
        throw new SAXException(e);
    } catch (Exception e) {
        getLogger().error(e.toString());
        throw new SAXException(e);
    }
    this.contentHandler.endPrefixMapping("");
}

From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/** {@inheritDoc} */
public void init(FilterConfig filterConfig) throws ServletException {
    ServletContext context = filterConfig.getServletContext();

    contextPath = context.getContextPath();

    Configuration conf = new Configuration(false);
    conf.addResource("hdfsproxy-default.xml");
    conf.addResource("hdfsproxy-site.xml");
    // extract namenode from source conf.
    String nn = getNamenode(conf);

    InetSocketAddress nAddr = NetUtils.createSocketAddr(nn);
    context.setAttribute("name.node.address", nAddr);
    context.setAttribute("name.conf", conf);
    context.setAttribute(JspHelper.CURRENT_CONF, conf);

    // for storing hostname <--> cluster mapping to decide which source cluster
    // to forward
    context.setAttribute("org.apache.hadoop.hdfsproxy.conf", conf);

    if (lctx == null) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(InitialLdapContext.INITIAL_CONTEXT_FACTORY,
                conf.get("hdfsproxy.ldap.initial.context.factory", "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(InitialLdapContext.PROVIDER_URL, conf.get("hdfsproxy.ldap.provider.url"));

        try {/* w w w.  ja  va  2 s. c o m*/
            lctx = new InitialLdapContext(env, null);
        } catch (NamingException ne) {
            throw new ServletException("NamingException in initializing ldap" + ne.toString());
        }

        baseName = conf.get("hdfsproxy.ldap.role.base");
        hdfsIpSchemaStr = conf.get("hdfsproxy.ldap.ip.schema.string", "uniqueMember");
        hdfsIpSchemaStrPrefix = conf.get("hdfsproxy.ldap.ip.schema.string.prefix", "cn=");
        hdfsUidSchemaStr = conf.get("hdfsproxy.ldap.uid.schema.string", "uid");
        hdfsPathSchemaStr = conf.get("hdfsproxy.ldap.hdfs.path.schema.string", "documentLocation");
    }
    LOG.info(contextPath + ":: LdapIpDirFilter initialization successful");
}

From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    String prevThreadName = Thread.currentThread().getName();
    try {//  w  ww.  ja  v  a  2s .  c  om
        Thread.currentThread().setName(contextPath);
        HttpServletRequest rqst = (HttpServletRequest) request;
        HttpServletResponse rsp = (HttpServletResponse) response;

        if (LOG.isDebugEnabled()) {
            StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/")
                    .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort());
            b.append("\n The Scheme is " + rqst.getScheme());
            b.append("\n The Path Info is " + rqst.getPathInfo());
            b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
            b.append("\n The Context Path is " + rqst.getContextPath());
            b.append("\n The Query String is " + rqst.getQueryString());
            b.append("\n The Request URI is " + rqst.getRequestURI());
            b.append("\n The Request URL is " + rqst.getRequestURL());
            b.append("\n The Servlet Path is " + rqst.getServletPath());
            LOG.debug(b.toString());
        }
        LdapRoleEntry ldapent = new LdapRoleEntry();
        // check ip address
        String userIp = rqst.getRemoteAddr();
        try {
            boolean isAuthorized = getLdapRoleEntryFromUserIp(userIp, ldapent);
            if (!isAuthorized) {
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN,
                        "IP " + userIp + " is not authorized to access");
                return;
            }
        } catch (NamingException ne) {
            throw new IOException("NamingException while searching ldap" + ne.toString());
        }

        // since we cannot pass ugi object cross context as they are from
        // different classloaders in different war file, we have to use String attribute.
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ldapent.userId);
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.paths", ldapent.paths);

        LOG.info("User: " + ldapent.userId + " Request: " + rqst.getPathInfo() + " From: "
                + rqst.getRemoteAddr());

        chain.doFilter(request, response);
    } finally {
        Thread.currentThread().setName(prevThreadName);
    }
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

@Override
public SampleResult sample(Entry e) {
    XMLBuffer xmlBuffer = new XMLBuffer();
    xmlBuffer.openTag("ldapanswer"); // $NON-NLS-1$
    SampleResult res = new SampleResult();
    res.setResponseData("successfull", null);
    res.setResponseMessage("Success"); // $NON-NLS-1$
    res.setResponseCode("0"); // $NON-NLS-1$
    res.setContentType("text/xml");// $NON-NLS-1$
    boolean isSuccessful = true;
    res.setSampleLabel(getName());/*from   w w  w .  j a  va 2  s .co m*/
    DirContext dirContext = ldapContexts.get(getThreadName());

    try {
        xmlBuffer.openTag("operation"); // $NON-NLS-1$
        final String testType = getTest();
        xmlBuffer.tag("opertype", testType); // $NON-NLS-1$
        log.debug("performing test: " + testType);
        if (testType.equals(UNBIND)) {
            res.setSamplerData("Unbind");
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            unbindOp(dirContext, res);
        } else if (testType.equals(BIND)) {
            res.setSamplerData("Bind as " + getUserDN());
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut()); // $NON-NLS-1$
            bindOp(res);
        } else if (testType.equals(SBIND)) {
            res.setSamplerData("SingleBind as " + getUserDN());
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut()); // $NON-NLS-1$
            singleBindOp(res);
        } else if (testType.equals(COMPARE)) {
            res.setSamplerData(
                    "Compare " + getPropertyAsString(COMPAREFILT) + " " + getPropertyAsString(COMPAREDN));
            xmlBuffer.tag("comparedn", getPropertyAsString(COMPAREDN)); // $NON-NLS-1$
            xmlBuffer.tag("comparefilter", getPropertyAsString(COMPAREFILT)); // $NON-NLS-1$
            NamingEnumeration<SearchResult> cmp = null;
            try {
                res.sampleStart();
                cmp = LdapExtClient.compare(dirContext, getPropertyAsString(COMPAREFILT),
                        getPropertyAsString(COMPAREDN));
                if (!cmp.hasMore()) {
                    res.setResponseCode("5"); // $NON-NLS-1$
                    res.setResponseMessage("compareFalse");
                    isSuccessful = false;
                }
            } finally {
                res.sampleEnd();
                if (cmp != null) {
                    cmp.close();
                }
            }
        } else if (testType.equals(ADD)) {
            res.setSamplerData("Add object " + getBaseEntryDN());
            xmlBuffer.tag("attributes", getArguments().toString()); // $NON-NLS-1$
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            addTest(dirContext, res);
        } else if (testType.equals(DELETE)) {
            res.setSamplerData("Delete object " + getBaseEntryDN());
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            deleteTest(dirContext, res);
        } else if (testType.equals(MODIFY)) {
            res.setSamplerData("Modify object " + getBaseEntryDN());
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            xmlBuffer.tag("attributes", getLDAPArguments().toString()); // $NON-NLS-1$
            modifyTest(dirContext, res);
        } else if (testType.equals(RENAME)) {
            res.setSamplerData(
                    "ModDN object " + getPropertyAsString(MODDDN) + " to " + getPropertyAsString(NEWDN));
            xmlBuffer.tag("dn", getPropertyAsString(MODDDN)); // $NON-NLS-1$
            xmlBuffer.tag("newdn", getPropertyAsString(NEWDN)); // $NON-NLS-1$
            renameTest(dirContext, res);
        } else if (testType.equals(SEARCH)) {
            final String scopeStr = getScope();
            final int scope = getScopeAsInt();
            final String searchFilter = getPropertyAsString(SEARCHFILTER);
            final String searchBase = getPropertyAsString(SEARCHBASE);
            final String timeLimit = getTimelim();
            final String countLimit = getCountlim();

            res.setSamplerData("Search with filter " + searchFilter);
            xmlBuffer.tag("searchfilter", StringEscapeUtils.escapeXml10(searchFilter)); // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("searchbase", searchBase);// $NON-NLS-1$
            xmlBuffer.tag("scope", scopeStr); // $NON-NLS-1$
            xmlBuffer.tag("countlimit", countLimit); // $NON-NLS-1$
            xmlBuffer.tag("timelimit", timeLimit); // $NON-NLS-1$

            NamingEnumeration<SearchResult> srch = null;
            try {
                res.sampleStart();
                srch = LdapExtClient.searchTest(dirContext, searchBase, searchFilter, scope,
                        getCountlimAsLong(), getTimelimAsInt(), getRequestAttributes(getAttrs()), isRetobj(),
                        isDeref());
                if (isParseFlag()) {
                    try {
                        xmlBuffer.openTag("searchresults"); // $NON-NLS-1$
                        writeSearchResults(xmlBuffer, srch);
                    } finally {
                        xmlBuffer.closeTag("searchresults"); // $NON-NLS-1$
                    }
                } else {
                    xmlBuffer.tag("searchresults", // $NON-NLS-1$
                            "hasElements=" + srch.hasMoreElements()); // $NON-NLS-1$
                }
            } finally {
                if (srch != null) {
                    srch.close();
                }
                res.sampleEnd();
            }

        }

    } catch (NamingException ex) {
        // TODO: tidy this up
        String returnData = ex.toString();
        final int indexOfLDAPErrCode = returnData.indexOf("LDAP: error code");
        if (indexOfLDAPErrCode >= 0) {
            res.setResponseMessage(returnData.substring(indexOfLDAPErrCode + 21, returnData.indexOf(']'))); // $NON-NLS-1$
            res.setResponseCode(returnData.substring(indexOfLDAPErrCode + 17, indexOfLDAPErrCode + 19));
        } else {
            res.setResponseMessage(returnData);
            res.setResponseCode("800"); // $NON-NLS-1$
        }
        isSuccessful = false;
    } finally {
        xmlBuffer.closeTag("operation"); // $NON-NLS-1$
        xmlBuffer.tag("responsecode", res.getResponseCode()); // $NON-NLS-1$
        xmlBuffer.tag("responsemessage", res.getResponseMessage()); // $NON-NLS-1$
        res.setResponseData(xmlBuffer.toString(), null);
        res.setDataType(SampleResult.TEXT);
        res.setSuccessful(isSuccessful);
    }
    return res;
}

From source file:org.lsc.beans.LscBean.java

/**
 * Set an attribute. API CHANGE: Do nothing if attribute is empty
 * /*from  w  ww.j a  va 2 s  .co  m*/
 * @param attr
 *            the attribute to set
 */
public final void setAttribute(final Attribute attr) {
    if (attr != null && attr.size() > 0) {
        // convert the Attribute into a Set of values
        try {
            setAttribute(attr.getID(), SetUtils.attributeToSet(attr));
        } catch (NamingException e) {
            LOGGER.error("Error storing the attribute {}: {}", attr.getID(), e.toString());
            LOGGER.debug(e.toString(), e);
        }
    }
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Check if the entry with the specified distinguish name exists (or
 * not)./* w  ww.  j  a v  a 2s  .  c o m*/
 *
 * @param dn the entry's distinguish name
 * @param filter look at the dn according this filter
 * @return entry existence (or false if something goes wrong)
 */
public boolean exists(final String dn, final String filter) {
    try {
        return (readEntry(dn, filter, true) != null);
    } catch (NamingException e) {
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
    }
    return false;
}

From source file:org.lsc.jndi.JndiServices.java

private SearchResult doReadEntry(final String base, final String filter, final boolean allowError,
        final SearchControls sc) throws NamingException {
    NamingEnumeration<SearchResult> ne = null;
    sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    try {//from  w  w  w.ja  va  2  s. c om
        ne = ctx.search(rewriteBase(base), filter, sc);
    } catch (NamingException nex) {
        if (nex instanceof CommunicationException || nex instanceof ServiceUnavailableException) {
            throw nex;
        }
        if (!allowError) {
            LOGGER.error("Error while reading entry {}: {}", base, nex);
            LOGGER.debug(nex.toString(), nex);
        }
        return null;
    }

    SearchResult sr = null;
    if (ne.hasMore()) {
        sr = (SearchResult) ne.next();
        if (ne.hasMore()) {
            LOGGER.error("Too many entries returned (base: \"{}\")", base);
        } else {
            return sr;
        }
    }
    return sr;
}

From source file:org.lsc.jndi.JndiServices.java

private List<String> doGetDnList(final String base, final String filter, final int scope)
        throws NamingException {
    NamingEnumeration<SearchResult> ne = null;
    List<String> iist = new ArrayList<String>();
    try {/*w w  w .j  a  v  a  2  s. c  o m*/
        SearchControls sc = new SearchControls();
        sc.setDerefLinkFlag(false);
        sc.setReturningAttributes(new String[] { "1.1" });
        sc.setSearchScope(scope);
        sc.setReturningObjFlag(true);
        ne = ctx.search(base, filter, sc);

        String completedBaseDn = "";
        if (base.length() > 0) {
            completedBaseDn = "," + base;
        }
        while (ne.hasMoreElements()) {
            iist.add(((SearchResult) ne.next()).getName() + completedBaseDn);
        }
    } catch (NamingException e) {
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
        throw e;
    }
    return iist;
}

From source file:org.lsc.jndi.JndiServices.java

private boolean doApply(final JndiModifications jm) throws CommunicationException {
    if (jm == null) {
        return true;
    }//from   w w w.j a v  a 2 s .  c  o m

    try {
        switch (jm.getOperation()) {

        case ADD_ENTRY:
            ctx.createSubcontext(new LdapName(rewriteBase(jm.getDistinguishName())),
                    getAttributes(jm.getModificationItems(), true));
            break;

        case DELETE_ENTRY:
            if (recursiveDelete) {
                deleteChildrenRecursively(rewriteBase(jm.getDistinguishName()));
            } else {
                ctx.destroySubcontext(new LdapName(rewriteBase(jm.getDistinguishName())));
            }
            break;

        case MODIFY_ENTRY:
            Object[] table = jm.getModificationItems().toArray();
            ModificationItem[] mis = new ModificationItem[table.length];
            System.arraycopy(table, 0, mis, 0, table.length);
            ctx.modifyAttributes(new LdapName(rewriteBase(jm.getDistinguishName())), mis);
            break;

        case MODRDN_ENTRY:
            //We do not display this warning if we do not apply the modification with the option modrdn = false
            LOGGER.warn(
                    "WARNING: updating the RDN of the entry will cancel other modifications! Relaunch synchronization to complete update.");
            ctx.rename(new LdapName(rewriteBase(jm.getDistinguishName())),
                    new LdapName(rewriteBase(jm.getNewDistinguishName())));
            break;

        default:
            LOGGER.error("Unable to identify the right modification type: {}", jm.getOperation());
            return false;
        }
        return true;

    } catch (ContextNotEmptyException e) {
        LOGGER.error(
                "Object {} not deleted because it has children (LDAP error code 66 received). To delete this entry and it's subtree, set the dst.java.naming.recursivedelete property to true",
                jm.getDistinguishName());
        return false;

    } catch (NamingException ne) {
        if (LOGGER.isErrorEnabled()) {
            StringBuilder errorMessage = new StringBuilder("Error while ");
            switch (jm.getOperation()) {
            case ADD_ENTRY:
                errorMessage.append("adding");
                break;
            case MODIFY_ENTRY:
                errorMessage.append("modifying");
                break;
            case MODRDN_ENTRY:
                errorMessage.append("renaming");
                break;
            case DELETE_ENTRY:
                if (recursiveDelete) {
                    errorMessage.append("recursively ");
                }
                errorMessage.append("deleting");
                break;
            }
            errorMessage.append(" entry ").append(jm.getDistinguishName());
            errorMessage.append(" in directory :").append(ne.toString());

            LOGGER.error(errorMessage.toString());
        }

        if (ne instanceof CommunicationException) {
            // we lost the connection to the source or destination, stop everything!
            throw (CommunicationException) ne;
        }
        if (ne instanceof ServiceUnavailableException) {
            // we lost the connection to the source or destination, stop everything!
            CommunicationException ce = new CommunicationException(ne.getExplanation());
            ce.setRootCause(ne);
            throw ce;
        }

        return false;
    }
}

From source file:org.mobicents.slee.service.alerting.SmsAlertingSbb.java

/**
 * implements javax.slee.Sbb Please refer to JSLEE v1.1 Specification, Early
 * Draft Review Page 54 for further information. <br>
 * The SLEE invokes this method after a new instance of the SBB abstract
 * class is created. During this method, an SBB entity has not been assigned
 * to the SBB object. The SBB object can take advantage of this method to
 * allocate and initialize state or connect to resources that are to be held
 * by the SBB object during its lifetime. Such state and resources cannot be
 * specific to an SBB entity because the SBB object might be reused during
 * its lifetime to serve multiple SBB entities. <br>
 * This method indicates a transition from state "DOES NOT EXIST" to
 * "POOLED" (see page 52)/*from w ww.ja  va 2s .com*/
 */
public void setSbbContext(SbbContext sbbContext) {
    this.sbbContext = sbbContext;
    try {
        Context ctx = (Context) new InitialContext().lookup("java:comp/env");

        smppProvider = (SmppProvider) ctx.lookup("slee/resources/smpp/3.4/smppinterface");
        smppAcif = (ActivityContextInterfaceFactory) ctx.lookup("slee/resources/smpp/3.4/factoryprovider");
    } catch (NamingException ne) {
        logger.error("Could not set SBB context: " + ne.toString(), ne);
    }
}