Java Code Examples for javax.naming.NamingException

The following are top voted examples for showing how to use javax.naming.NamingException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: kinota-server   File: Application.java   Source Code and License 8 votes vote down vote up
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    String jndiName = "java:comp/env/" + env.getProperty("sta.datasource.name", "jdbc/sensorThings");
    bean.setJndiName(jndiName);
    bean.setProxyInterface(DataSource.class);
    bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}
 
Example 2
Project: jboss-eap7.1-playground   File: WildFlyICConfigClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws NamingException {
	checkArgs(args);
	
	// Option is to use the WF context with no properties, this is not working because of JBEAP-xxxx at this moment
	InitialContext ic = new WildFlyInitialContext();
	
	Simple proxy = (Simple) ic.lookup("ejb:EAP71-PLAYGROUND-server/ejb/SimpleBean!" + Simple.class.getName());
	
	try {
		if(proxy.checkApplicationUser("admin")) {
			log.info("Expected 'admin'");
		} else {
			log.severe("Unexpected user, see server.log");
		}
	} catch (EJBException e) {
		throw e;
	}
}
 
Example 3
Project: tomcat7   File: JNDIRealm.java   Source Code and License 6 votes vote down vote up
/**
 * Return a String representing the value of the specified attribute.
 *
 * @param attrId Attribute name
 * @param attrs Attributes containing the required value
 *
 * @exception NamingException if a directory server error occurs
 */
private String getAttributeValue(String attrId, Attributes attrs)
    throws NamingException {

    if (containerLog.isTraceEnabled())
        containerLog.trace("  retrieving attribute " + attrId);

    if (attrId == null || attrs == null)
        return null;

    Attribute attr = attrs.get(attrId);
    if (attr == null)
        return null;
    Object value = attr.get();
    if (value == null)
        return null;
    String valueString = null;
    if (value instanceof byte[])
        valueString = new String((byte[]) value);
    else
        valueString = value.toString();

    return valueString;
}
 
Example 4
Project: lazycat   File: ResourceAttributes.java   Source Code and License 6 votes vote down vote up
/**
 * Get name.
 * 
 * @return Name value
 */
public String getName() {
	if (name != null)
		return name;
	if (attributes != null) {
		Attribute attribute = attributes.get(NAME);
		if (attribute != null) {
			try {
				name = attribute.get().toString();
			} catch (NamingException e) {
				// No value for the attribute
			}
		}
	}
	return name;
}
 
Example 5
Project: jboss-eap7.1-playground   File: CheckDelegateTxROCClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws NamingException {
	checkArgs(args);
	
	Properties p = new Properties();
	
	p.put(Context.INITIAL_CONTEXT_FACTORY, WildFlyInitialContextFactory.class.getName());
	p.put(Context.PROVIDER_URL, "http-remoting://localhost:9080");
	
	p.put(Context.SECURITY_PRINCIPAL, "delegateUser");
	p.put(Context.SECURITY_CREDENTIALS, "delegateUser");
	InitialContext ic = new InitialContext(p);
	
	DelegateROC proxy = (DelegateROC) ic.lookup("ejb:EAP71-PLAYGROUND-MainServer-rocApp/ejb/DelegateROCBean!" + DelegateROC.class.getName());
	proxy.checkTransactionStickyness();
	
	// ic.close();  // not longer necessary
}
 
Example 6
Project: jdk8u-jdk   File: RMIConnector.java   Source Code and License 6 votes vote down vote up
private RMIServer findRMIServer(JMXServiceURL directoryURL,
        Map<String, Object> environment)
        throws NamingException, IOException {
    final boolean isIiop = RMIConnectorServer.isIiopURL(directoryURL,true);
    if (isIiop) {
        // Make sure java.naming.corba.orb is in the Map.
        environment.put(EnvHelp.DEFAULT_ORB,resolveOrb(environment));
    }

    String path = directoryURL.getURLPath();
    int end = path.indexOf(';');
    if (end < 0) end = path.length();
    if (path.startsWith("/jndi/"))
        return findRMIServerJNDI(path.substring(6,end), environment, isIiop);
    else if (path.startsWith("/stub/"))
        return findRMIServerJRMP(path.substring(6,end), environment, isIiop);
    else if (path.startsWith("/ior/")) {
        if (!IIOPHelper.isAvailable())
            throw new IOException("iiop protocol not available");
        return findRMIServerIIOP(path.substring(5,end), environment, isIiop);
    } else {
        final String msg = "URL path must begin with /jndi/ or /stub/ " +
                "or /ior/: " + path;
        throw new MalformedURLException(msg);
    }
}
 
Example 7
Project: jerrydog   File: ResourceAttributes.java   Source Code and License 6 votes vote down vote up
/**
 * Get ETag.
 * 
 * @param strong If true, the strong ETag will be returned
 * @return ETag
 */
public String getETag(boolean strong) {
    String result = null;
    if (attributes != null) {
        Attribute attribute = attributes.get(ETAG);
        if (attribute != null) {
            try {
                result = attribute.get().toString();
            } catch (NamingException e) {
                ; // No value for the attribute
            }
        }
    }
    if (strong) {
        // The strong ETag must always be calculated by the resources
        result = strongETag;
    } else {
        // The weakETag is contentLenght + lastModified
        if (weakETag == null) {
            weakETag = "W/\"" + getContentLength() + "-" 
                + getLastModified() + "\"";
        }
        result = weakETag;
    }
    return result;
}
 
Example 8
Project: nifi-registry   File: LdapUserGroupProvider.java   Source Code and License 6 votes vote down vote up
private String getUserIdentity(final DirContextOperations ctx) {
    final String identity;

    if (useDnForUserIdentity) {
        identity = ctx.getDn().toString();
    } else {
        final Attribute attributeName = ctx.getAttributes().get(userIdentityAttribute);
        if (attributeName == null) {
            throw new AuthorizationAccessException("User identity attribute [" + userIdentityAttribute + "] does not exist.");
        }

        try {
            identity = (String) attributeName.get();
        } catch (NamingException e) {
            throw new AuthorizationAccessException("Error while retrieving user name attribute [" + userIdentityAttribute + "].");
        }
    }

    return IdentityMappingUtil.mapIdentity(identity, identityMappings);
}
 
Example 9
Project: lazycat   File: JNDIRealm.java   Source Code and License 6 votes vote down vote up
private void restoreEnvironmentParameter(DirContext context, String parameterName,
		Hashtable<?, ?> preservedEnvironment) {
	try {
		context.removeFromEnvironment(parameterName);
		if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) {
			context.addToEnvironment(parameterName, preservedEnvironment.get(parameterName));
		}
	} catch (NamingException e) {
		// Ignore
	}
}
 
Example 10
Project: directory-ldap-api   File: TriggerUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Defines the Administration point and administrative role for the TriggerExecution specific point
 * @param apCtx The administrative point context
 * @throws NamingException If the operation failed
 */
public static void defineTriggerExecutionSpecificPoint( LdapContext apCtx ) throws NamingException
{
    Attributes ap = apCtx.getAttributes( "", new String[] { SchemaConstants.ADMINISTRATIVE_ROLE_AT } );
    Attribute administrativeRole = ap.get( SchemaConstants.ADMINISTRATIVE_ROLE_AT );
    
    if ( administrativeRole == null
        || !AttributeUtils.containsValueCaseIgnore( administrativeRole, SchemaConstants.TRIGGER_EXECUTION_SPECIFIC_AREA ) )
    {
        Attributes changes = new BasicAttributes( SchemaConstants.ADMINISTRATIVE_ROLE_AT,
            SchemaConstants.TRIGGER_EXECUTION_SPECIFIC_AREA, true );
        apCtx.modifyAttributes( "", DirContext.ADD_ATTRIBUTE, changes );
    }
}
 
Example 11
Project: lams   File: SelectorContext.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the named object.
 * 
 * @param name the name of the object to look up
 * @return the object bound to name
 * @exception NamingException if a naming exception is encountered
 */
public Object lookup(String name)
    throws NamingException {
    // Strip the URL header
    // Find the appropriate NamingContext according to the current bindings
    // Execute the lookup on that context
    return getBoundContext().lookup(parseName(name));
}
 
Example 12
Project: oscm   File: LdapAccessServiceBean.java   Source Code and License 5 votes vote down vote up
private <T> List<T> searchByLimit(Properties properties, String baseDN,
        String filter, ILdapResultMapper<T> mapper, boolean checkAttribute,
        int searchLimit) throws NamingException {
    List<T> list = new ArrayList<T>();
    NamingEnumeration<SearchResult> namingEnum = null;

    DirContext ctx = getDirContext(properties);

    SearchControls ctls = new SearchControls();
    String[] attrIds = mapper.getAttributes();
    ctls.setReturningAttributes(attrIds);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(searchLimit);

    try {
        namingEnum = ctx.search(baseDN, escapeLDAPSearchFilter(filter),
                ctls);
        int count = 0;
        while (count++ < searchLimit && hasMoreEnum(namingEnum)) {
            SearchResult res = namingEnum.next();
            Attributes ldapAttributes = res.getAttributes();
            String[] values = new String[attrIds.length];
            for (int i = 0; i < values.length; i++) {
                Attribute ldapAttr = ldapAttributes
                        .get(escapeLDAPSearchFilter(attrIds[i]));
                if (checkAttribute && ldapAttr == null) {
                    NamingException e = new NamingException(
                            "Unknown LDAP attribute " + attrIds[i]);
                    throw e;
                }
                if (ldapAttr != null && ldapAttr.get() != null) {
                    values[i] = ldapAttr.get().toString();
                }
            }
            T t = mapper.map(values);
            if (t != null) {
                list.add(t);
            }
        }
    } finally {
        if (namingEnum != null) {
            try {
                namingEnum.close();
            } finally {
                closeContext(ctx);
            }
        }
        closeContext(ctx);
    }
    return list;
}
 
Example 13
Project: testing_security_development_enterprise_systems   File: TopUsersTest.java   Source Code and License 5 votes vote down vote up
protected <T> T getEJB(Class<T> klass){
    try {
        return (T) ctx.lookup("java:global/classes/"+klass.getSimpleName()+"!"+klass.getName());
    } catch (NamingException e) {
        return null;
    }
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: NamingContextListener.java   Source Code and License 5 votes vote down vote up
/**
 * Set the specified resources in the naming context.
 */
public void removeResource(String name) {

    try {
        envCtx.unbind(name);
    } catch (NamingException e) {
        logger.error(sm.getString("naming.unbindFailed", e));
    }

    ObjectName on = objectNames.get(name);
    if (on != null) {
        Registry.getRegistry(null, null).unregisterComponent(on);
    }

}
 
Example 15
Project: OpenDiabetes   File: JDBCPool.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the Reference of this object.
 *
 * @return The non-null Reference of this object.
 * @exception NamingException If a naming exception was encountered
 *          while retrieving the reference.
 */
public Reference getReference() throws NamingException {
    String    cname = "org.hsqldb.jdbc.JDBCDataSourceFactory";
    Reference ref   = new Reference(getClass().getName(), cname, null);

    ref.add(new StringRefAddr("database", source.getDatabase()));
    ref.add(new StringRefAddr("user", source.getUser()));
    ref.add(new StringRefAddr("password", source.password));
    ref.add(new StringRefAddr("loginTimeout",
                              Integer.toString(source.loginTimeout)));
    ref.add(new StringRefAddr("poolSize", Integer.toString(connections.length)));

    return ref;
}
 
Example 16
Project: lazycat   File: NamingContext.java   Source Code and License 5 votes vote down vote up
/**
 * Throws a naming exception is Context is not writable.
 */
protected boolean checkWritable() throws NamingException {
	if (isWritable()) {
		return true;
	} else {
		if (exceptionOnFailedWrite) {
			throw new javax.naming.OperationNotSupportedException(sm.getString("namingContext.readOnly"));
		}
	}
	return false;
}
 
Example 17
Project: oscm   File: LdapAccessStub.java   Source Code and License 5 votes vote down vote up
/**
 * Execute an LDAP search and return the result.
 * 
 * @return the search result.
 */
public <T> List<T> search(Properties properties, String baseDN,
        String filter, ILdapResultMapper<T> mapper, boolean checkAttribute)
        throws NamingException {

    if ("invalid".equals(properties.getProperty(Context.PROVIDER_URL))) {
        throw new NamingException("Invalid URL.");
    }

    List<T> list = new ArrayList<T>();
    T t;

    String[] attrIds = mapper.getAttributes();

    if (filter.endsWith("*")) {
        t = mapper.map(getValues(attrIds, 0));
        list.add(t);
        t = mapper.map(getValues(attrIds, 1));
        list.add(t);
        t = mapper.map(getValues(attrIds, 2));
        list.add(t);
    } else if (filter.endsWith(allValues[0][0])) {
        t = mapper.map(getValues(attrIds, 0));
        list.add(t);
    } else if (filter.endsWith(allValues[1][0])) {
        t = mapper.map(getValues(attrIds, 1));
        list.add(t);
    } else if (filter.endsWith(allValues[2][0])) {
        t = mapper.map(getValues(attrIds, 2));
        list.add(t);
    }

    return list;
}
 
Example 18
Project: oscm   File: LoginHandler.java   Source Code and License 5 votes vote down vote up
protected String getUserKeyFromContext(SOAPMessageContext context)
        throws UserIdNotFoundException, NamingException, SQLException, NotExistentTenantException {
    
    String userId = getUserIdFromContext(context);
    String tenantId = getTenantIdFromContext(context);
    String orgId = getOrganizationIdFromContext(context);
    
    return getUserKey(userId, orgId, tenantId);
}
 
Example 19
Project: monarch   File: ContextImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Creates subcontext with name, relative to this Context.
 * 
 * @param name subcontext name.
 * @return new subcontext named name relative to this context.
 * @throws NoPermissionException if this context has been destroyed.
 * @throws InvalidNameException if name is empty or is CompositeName that spans more than one
 *         naming system.
 * @throws NameAlreadyBoundException if name is already bound in this Context
 * @throws NotContextException if any intermediate name from name is not bound to instance of
 *         javax.naming.Context.
 * 
 */
public Context createSubcontext(Name name) throws NamingException {
  checkIsDestroyed();
  Name parsedName = getParsedName(name);
  if (parsedName.size() == 0 || parsedName.get(0).length() == 0) {
    throw new InvalidNameException(
        LocalizedStrings.ContextImpl_NAME_CAN_NOT_BE_EMPTY.toLocalizedString());
  }
  String subContextName = parsedName.get(0);
  Object boundObject = ctxMaps.get(parsedName.get(0));
  if (parsedName.size() == 1) {
    // Check if name is already in use
    if (boundObject == null) {
      Context subContext = new ContextImpl(this, subContextName);
      ctxMaps.put(subContextName, subContext);
      return subContext;
    } else {
      throw new NameAlreadyBoundException(
          LocalizedStrings.ContextImpl_NAME_0_IS_ALREADY_BOUND.toLocalizedString(subContextName));
    }
  } else {
    if (boundObject instanceof Context) {
      // Let the subcontext create new subcontext
      // lets consider a scenerio a/b/c
      // case a/b exists : c will be created
      // case a exists : b/c will not be created
      // an exception will be thrown in that case.
      return ((Context) boundObject).createSubcontext(parsedName.getSuffix(1));
    } else {
      throw new NotContextException(LocalizedStrings.ContextImpl_EXPECTED_CONTEXT_BUT_FOUND_0
          .toLocalizedString(boundObject));
    }
  }
}
 
Example 20
Project: lazycat   File: NamingContextBindingsEnumeration.java   Source Code and License 5 votes vote down vote up
@Override
public Binding nextElement() {
	try {
		return nextElementInternal();
	} catch (NamingException e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 21
Project: hadoop-oss   File: TestLdapGroupsMapping.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetGroups() throws IOException, NamingException {
  // The search functionality of the mock context is reused, so we will
  // return the user NamingEnumeration first, and then the group
  when(mockContext.search(anyString(), anyString(), any(Object[].class),
      any(SearchControls.class)))
      .thenReturn(mockUserNamingEnum, mockGroupNamingEnum);
  
  doTestGetGroups(Arrays.asList(testGroups), 2);
}
 
Example 22
Project: lams   File: ResourceLinkFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Create a new DataSource instance.
 * 
 * @param obj The reference object describing the DataSource
 */
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
                                Hashtable environment)
    throws NamingException {
    
    if (!(obj instanceof ResourceLinkRef))
        return null;

    // Can we process this request?
    Reference ref = (Reference) obj;

    String type = ref.getClassName();

    // Read the global ref addr
    String globalName = null;
    RefAddr refAddr = ref.get(ResourceLinkRef.GLOBALNAME);
    if (refAddr != null) {
        globalName = refAddr.getContent().toString();
        Object result = null;
        result = globalContext.lookup(globalName);
        // FIXME: Check type
        return result;
    }

    return (null);

    
}
 
Example 23
Project: parabuild-ci   File: jdbcDataSource.java   Source Code and License 5 votes vote down vote up
public Reference getReference() throws NamingException {

        String    cname = "org.hsqldb.jdbc.jdbcDataSourceFactory";
        Reference ref   = new Reference(getClass().getName(), cname, null);

        ref.add(new StringRefAddr("database", getDatabase()));
        ref.add(new StringRefAddr("user", getUser()));
        ref.add(new StringRefAddr("password", password));

        return ref;
    }
 
Example 24
Project: apache-tomcat-7.0.73-with-comment   File: NamingContextListener.java   Source Code and License 5 votes vote down vote up
/**
 * Set the specified web services in the naming context.
 */
public void removeService(String name) {

    try {
        envCtx.unbind(name);
    } catch (NamingException e) {
        logger.error(sm.getString("naming.unbindFailed", e));
    }

}
 
Example 25
Project: apache-tomcat-7.0.73-with-comment   File: NamingContextBindingsEnumeration.java   Source Code and License 5 votes vote down vote up
@Override
public Binding nextElement() {
    try {
        return nextElementInternal();
    } catch (NamingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 26
Project: lazycat   File: javaURLContextFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Crete a new Context's instance.
 */
@SuppressWarnings("unchecked")
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment)
		throws NamingException {
	if ((ContextBindings.isThreadBound()) || (ContextBindings.isClassLoaderBound())) {
		return new SelectorContext((Hashtable<String, Object>) environment);
	}
	return null;
}
 
Example 27
Project: asw   File: JndiUtil.java   Source Code and License 5 votes vote down vote up
/** Effettua il lookup di una risorsa JMS. */
  public Object jndiLookup(String resourceName) {
  	Object resource = null; 
try {
	logger.info("Lookup della risorsa JNDI: " + resourceName);
  	    /* effettua il lookup della risorsa cercata */
  	    resource = getContext().lookup(resourceName);
      	logger.fine("Lookup di " + resourceName + " riuscito");
  	} catch (NamingException e) {
      	logger.info("Lookup di " + resourceName + " fallito");
      	e.printStackTrace();
      	// System.exit(1);
  	}
return resource; 
  }
 
Example 28
Project: asw   File: JndiUtil.java   Source Code and License 5 votes vote down vote up
/** Effettua il lookup di una risorsa JMS. */
  public Object jndiLookup(String resourceName) {
  	Object resource = null; 
try {
	logger.info("Lookup della risorsa JNDI: " + resourceName);
  	    /* effettua il lookup della risorsa cercata */
  	    resource = getContext().lookup(resourceName);
      	logger.fine("Lookup di " + resourceName + " riuscito");
  	} catch (NamingException e) {
      	logger.info("Lookup di " + resourceName + " fallito");
      	e.printStackTrace();
      	// System.exit(1);
  	}
return resource; 
  }
 
Example 29
Project: tomcat7   File: ResourceAttributes.java   Source Code and License 5 votes vote down vote up
/**
 * Put attribute.
 */
@Override
public Attribute put(Attribute attribute) {
    if (attributes == null) {
        try {
            return put(attribute.getID(), attribute.get());
        } catch (NamingException e) {
            return null;
        }
    } else {
        return attributes.put(attribute);
    }
}
 
Example 30
Project: lams   File: AbstractRemoteSlsbInvokerInterceptor.java   Source Code and License 5 votes vote down vote up
/**
 * Return a new instance of the stateless session bean.
 * To be invoked by concrete remote SLSB invoker subclasses.
 * <p>Can be overridden to change the algorithm.
 * @throws NamingException if thrown by JNDI
 * @throws InvocationTargetException if thrown by the create method
 * @see #create
 */
protected Object newSessionBeanInstance() throws NamingException, InvocationTargetException {
	if (logger.isDebugEnabled()) {
		logger.debug("Trying to create reference to remote EJB");
	}
	Object ejbInstance = create();
	if (logger.isDebugEnabled()) {
		logger.debug("Obtained reference to remote EJB: " + ejbInstance);
	}
	return ejbInstance;
}
 
Example 31
Project: marshalsec   File: JDKUtil.java   Source Code and License 5 votes vote down vote up
public static Enumeration<?> makeBindingEnumeration ( String codebase, String clazz ) throws ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException, Exception, NamingException, RemoteException {
    Class<?> cl = Class.forName("com.sun.jndi.rmi.registry.BindingEnumeration");
    Object enu = Reflections.createWithoutConstructor(cl);
    Reflections.setFieldValue(enu, "ctx", makeRegistryContext(makeRegistryImpl(codebase, clazz)));
    Reflections.setFieldValue(enu, "names", new String[] {
        "exp"
    });
    Reflections.setFieldValue(enu, "nextName", 0);
    return (Enumeration<?>) enu;
}
 
Example 32
Project: jdk8u-jdk   File: ContinuationDirContext.java   Source Code and License 5 votes vote down vote up
protected DirContextStringPair getTargetContext(String name)
        throws NamingException {

    if (cpe.getResolvedObj() == null)
        throw (NamingException)cpe.fillInStackTrace();

    Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
                                           cpe.getAltName(),
                                           cpe.getAltNameCtx(),
                                           env);

    if (ctx instanceof DirContext)
        return new DirContextStringPair((DirContext)ctx, name);

    if (ctx instanceof Resolver) {
        Resolver res = (Resolver)ctx;
        ResolveResult rr = res.resolveToClass(name, DirContext.class);

        // Reached a DirContext; return result.
        DirContext dctx = (DirContext)rr.getResolvedObj();
        Name tmp = rr.getRemainingName();
        String remains = (tmp != null) ? tmp.toString() : "";
        return (new DirContextStringPair(dctx, remains));
    }

    // Resolve all the way using lookup().  This may allow the operation
    // to succeed if it doesn't require the penultimate context.
    Object ultimate = ctx.lookup(name);
    if (ultimate instanceof DirContext) {
        return (new DirContextStringPair((DirContext)ultimate, ""));
    }

    throw (NamingException)cpe.fillInStackTrace();
}
 
Example 33
Project: lams   File: DirContextURLConnection.java   Source Code and License 5 votes vote down vote up
/**
 * List children of this collection. The names given are relative to this
 * URI's path. The full uri of the children is then : path + "/" + name.
 */
public Enumeration list()
    throws IOException {
    
    if (!connected) {
        connect();
    }
    
    if ((resource == null) && (collection == null)) {
        throw new FileNotFoundException();
    }
    
    Vector result = new Vector();
    
    if (collection != null) {
        try {
            NamingEnumeration enumeration = context.list(getURL().getFile());
            while (enumeration.hasMoreElements()) {
                NameClassPair ncp = (NameClassPair) enumeration.nextElement();
                result.addElement(ncp.getName());
            }
        } catch (NamingException e) {
            // Unexpected exception
            throw new FileNotFoundException();
        }
    }
    
    return result.elements();
    
}
 
Example 34
Project: monarch   File: CacheUtils.java   Source Code and License 5 votes vote down vote up
public static void destroyTable(String tableName) throws NamingException, SQLException {
  Context ctx = cache.getJNDIContext();
  DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
  Connection conn = ds.getConnection();
  // System.out.println (" trying to drop table: " + tableName);
  String sql = "drop table " + tableName;
  Statement sm = conn.createStatement();
  sm.execute(sql);
  conn.close();
}
 
Example 35
Project: monarch   File: ContextImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Looks up the object in this context. If the object is not found and the remote context was
 * provided, calls the remote context to lookup the object.
 * 
 * @param name object to search
 * @return object reference bound to name name.
 * @throws NamingException if naming error occurs.
 * 
 */
public Object lookup(String name) throws NamingException {
  checkIsDestroyed();
  try {
    return lookup(nameParser.parse(name));
  } catch (NameNotFoundException e) {
    LogWriterI18n writer = TransactionUtils.getLogWriterI18n();
    if (writer.infoEnabled())
      writer.info(LocalizedStrings.ContextImpl_CONTEXTIMPL_LOOKUP_ERROR_WHILE_LOOKING_UP_0, name,
          e);
    throw new NameNotFoundException(
        LocalizedStrings.ContextImpl_NAME_0_NOT_FOUND.toLocalizedString(new Object[] {name}));
  }
}
 
Example 36
Project: monarch   File: GemFireSecurityExceptionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void serializesWithSerializableNamingException() throws Exception {
  GemFireSecurityException instance =
      new GemFireSecurityException(this.message, this.serializableNamingException);

  GemFireSecurityException cloned = (GemFireSecurityException) SerializationUtils.clone(instance);

  assertThat(cloned).hasMessage(this.message).hasCause(this.serializableNamingException);
  NamingException cause = (NamingException) cloned.getCause();
  assertThat(cause).hasMessage(this.causeMessage);
  assertThat(cause.getResolvedObj()).isNotNull().isEqualTo(this.serializableResolvedObj);
}
 
Example 37
Project: lams   File: JndiTemplate.java   Source Code and License 5 votes vote down vote up
/**
 * Release a JNDI context as obtained from {@link #getContext()}.
 * @param ctx the JNDI context to release (may be {@code null})
 * @see #getContext
 */
public void releaseContext(Context ctx) {
	if (ctx != null) {
		try {
			ctx.close();
		}
		catch (NamingException ex) {
			logger.debug("Could not close JNDI InitialContext", ex);
		}
	}
}
 
Example 38
Project: oscm   File: LdapAccessStub.java   Source Code and License 5 votes vote down vote up
public <T> boolean searchOverLimit(Properties properties, String baseDN,
        String filter, ILdapResultMapper<T> mapper, boolean checkAttribute)
        throws NamingException {
    if (throwNamingException) {
        throw new NamingException();
    }

    return false;
}
 
Example 39
Project: lazycat   File: JNDIRealm.java   Source Code and License 5 votes vote down vote up
/**
 * Use the distinguished name to locate the directory entry for the user
 * with the specified username and return a User object; otherwise return
 * <code>null</code>.
 *
 * @param context
 *            The directory context
 * @param username
 *            The username
 * @param attrIds
 *            String[]containing names of attributes to
 * @param dn
 *            Distinguished name of the user retrieve.
 *
 * @exception NamingException
 *                if a directory server error occurs
 */
protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn)
		throws NamingException {

	// If no attributes are requested, no need to look for them
	if (attrIds == null || attrIds.length == 0) {
		return new User(username, dn, null, null, null);
	}

	// Get required attributes from user entry
	Attributes attrs = null;
	try {
		attrs = context.getAttributes(dn, attrIds);
	} catch (NameNotFoundException e) {
		return null;
	}
	if (attrs == null)
		return null;

	// Retrieve value of userPassword
	String password = null;
	if (userPassword != null)
		password = getAttributeValue(userPassword, attrs);

	String userRoleAttrValue = null;
	if (userRoleAttribute != null) {
		userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
	}

	// Retrieve values of userRoleName attribute
	ArrayList<String> roles = null;
	if (userRoleName != null)
		roles = addAttributeValues(userRoleName, attrs, roles);

	return new User(username, dn, password, roles, userRoleAttrValue);
}
 
Example 40
Project: lams   File: WorkManagerTaskExecutor.java   Source Code and License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws NamingException {
	if (this.workManager == null) {
		if (this.workManagerName != null) {
			this.workManager = lookup(this.workManagerName, WorkManager.class);
		}
		else {
			this.workManager = getDefaultWorkManager();
		}
	}
}
 
Example 41
Project: tomcat7   File: SelectorContext.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the named object.
 *
 * @param name the name of the object to look up
 * @return the object bound to name
 * @exception NamingException if a naming exception is encountered
 */
@Override
public Object lookup(String name)
    throws NamingException {

    if (log.isDebugEnabled()) {
        log.debug(sm.getString("selectorContext.methodUsingString", "lookup",
                name));
    }

    // Strip the URL header
    // Find the appropriate NamingContext according to the current bindings
    // Execute the lookup on that context
    return getBoundContext().lookup(parseName(name));
}
 
Example 42
Project: directory-ldap-api   File: ObjectClassDescriptionSchemaParserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNovellDcObject() throws ParseException, NamingException
{
    String value = "( 1.3.6.1.4.1.1466.344 NAME 'dcObject' AUXILIARY MUST dc X-NDS_NAMING 'dc' X-NDS_NOT_CONTAINER '1' X-NDS_NONREMOVABLE '1' )";
    ObjectClass objectClass = parser.parseObjectClassDescription( value );

    assertEquals( "1.3.6.1.4.1.1466.344", objectClass.getOid() );
    assertEquals( 1, objectClass.getNames().size() );
    assertEquals( "dcObject", objectClass.getNames().get( 0 ) );
    assertNull( objectClass.getDescription() );
    assertEquals( 0, objectClass.getSuperiorOids().size() );
    assertEquals( ObjectClassTypeEnum.AUXILIARY, objectClass.getType() );
    assertEquals( 1, objectClass.getMustAttributeTypeOids().size() );
    assertEquals( "dc", objectClass.getMustAttributeTypeOids().get( 0 ) );
    assertEquals( 0, objectClass.getMayAttributeTypeOids().size() );

    assertEquals( 3, objectClass.getExtensions().size() );
    assertNotNull( objectClass.getExtension( "X-NDS_NAMING" ) );
    assertEquals( 1, objectClass.getExtension( "X-NDS_NAMING" ).size() );
    assertEquals( "dc", objectClass.getExtension( "X-NDS_NAMING" ).get( 0 ) );
    assertNotNull( objectClass.getExtension( "X-NDS_NOT_CONTAINER" ) );
    assertEquals( 1, objectClass.getExtension( "X-NDS_NOT_CONTAINER" ).size() );
    assertEquals( "1", objectClass.getExtension( "X-NDS_NOT_CONTAINER" ).get( 0 ) );
    assertNotNull( objectClass.getExtension( "X-NDS_NONREMOVABLE" ) );
    assertEquals( 1, objectClass.getExtension( "X-NDS_NONREMOVABLE" ).size() );
    assertEquals( "1", objectClass.getExtension( "X-NDS_NONREMOVABLE" ).get( 0 ) );
}
 
Example 43
Project: lams   File: DefaultInstanceManager.java   Source Code and License 5 votes vote down vote up
/**
 * Inject resources in specified method.
 *
 * @param context  jndi context to extract value from
 * @param instance object to inject into
 * @param method   field target for injection
 * @param name     jndi name value is bound under
 * @param clazz    class annotation is defined in
 * @throws IllegalAccessException       if method is inaccessible
 * @throws javax.naming.NamingException if value is not accessible in naming context
 * @throws java.lang.reflect.InvocationTargetException
 *                                      if setter call fails
 */
protected static void lookupMethodResource(Context context,
        Object instance, Method method, String name, Class<?> clazz)
        throws NamingException, IllegalAccessException, InvocationTargetException {

    if (!method.getName().startsWith("set")
            || method.getParameterTypes().length != 1
            || !method.getReturnType().getName().equals("void")) {
        throw new IllegalArgumentException("Invalid method resource injection annotation");
    }

    Object lookedupResource;
    boolean accessibility;

    if ((name != null) &&
            (name.length() > 0)) {
        lookedupResource = context.lookup(name);
    } else {
        lookedupResource = context.lookup(
                clazz.getName() + "/" + method.getName().substring(3));
    }

    accessibility = method.isAccessible();
    method.setAccessible(true);
    method.invoke(instance, lookedupResource);
    method.setAccessible(accessibility);
}
 
Example 44
Project: openjdk-jdk10   File: RMIConnectorServer.java   Source Code and License 5 votes vote down vote up
/**
 * Bind a stub to a registry.
 * @param jndiUrl URL of the stub in the registry, extracted
 *        from the <code>JMXServiceURL</code>.
 * @param attributes A Hashtable containing environment parameters,
 *        built from the Map specified at this object creation.
 * @param rmiServer The object to bind in the registry
 * @param rebind true if the object must be rebound.
 **/
void bind(String jndiUrl, Hashtable<?, ?> attributes,
          RMIServer rmiServer, boolean rebind)
    throws NamingException, MalformedURLException {
    // if jndiURL is not null, we nust bind the stub to a
    // directory.
    InitialContext ctx =
        new InitialContext(attributes);

    if (rebind)
        ctx.rebind(jndiUrl, rmiServer);
    else
        ctx.bind(jndiUrl, rmiServer);
    ctx.close();
}
 
Example 45
Project: lazycat   File: SelectorContext.java   Source Code and License 5 votes vote down vote up
/**
 * Strips the URL header.
 *
 * @return the parsed name
 * @exception NamingException
 *                if there is no "java:" header or if no naming context has
 *                been bound to this thread
 */
protected String parseName(String name) throws NamingException {

	if ((!initialContext) && (name.startsWith(prefix))) {
		return (name.substring(prefixLength));
	} else {
		if (initialContext) {
			return (name);
		} else {
			throw new NamingException(sm.getString("selectorContext.noJavaUrl"));
		}
	}

}
 
Example 46
Project: apache-tomcat-7.0.73-with-comment   File: ResourceAttributes.java   Source Code and License 5 votes vote down vote up
/**
 * Get ETag.
 * 
 * @return strong ETag if available, else weak ETag. 
 */
public String getETag() {
    String result = null;
    if (attributes != null) {
        Attribute attribute = attributes.get(ETAG);
        if (attribute != null) {
            try {
                result = attribute.get().toString();
            } catch (NamingException e) {
                // No value for the attribute
            }
        }
    }
    if (result == null) {
        if (strongETag != null) {
            // The strong ETag must always be calculated by the resources
            result = strongETag;
        } else {
            // The weakETag is contentLength + lastModified
            if (weakETag == null) {
                long contentLength = getContentLength();
                long lastModified = getLastModified();
                if ((contentLength >= 0) || (lastModified >= 0)) {
                    weakETag = "W/\"" + contentLength + "-" +
                               lastModified + "\"";
                }
            }
            result = weakETag;
        }
    } 
    return result;
}
 
Example 47
Project: Equella   File: LDAP.java   Source Code and License 5 votes vote down vote up
public Attributes getAttributes(DirContext ctx, Name name, String[] attributes)
{
	try
	{
		return ctx.getAttributes(name, attributes);
	}
	catch( NamingException ne )
	{
		throw new RuntimeException(ne);
	}
}
 
Example 48
Project: crnk-framework   File: DummyInitialContextFactory.java   Source Code and License 4 votes vote down vote up
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
	return null;
}
 
Example 49
Project: crnk-framework   File: DummyInitialContextFactory.java   Source Code and License 4 votes vote down vote up
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
	return null;
}
 
Example 50
Project: flume-release-1.7.0   File: InitialContextFactory.java   Source Code and License 4 votes vote down vote up
public InitialContext create(Properties properties) throws NamingException {
  return new InitialContext(properties);
}
 
Example 51
Project: jdk8u-jdk   File: ContinuationDirContext.java   Source Code and License 4 votes vote down vote up
public DirContext getSchemaClassDefinition(String name)
        throws NamingException  {
    DirContextStringPair res = getTargetContext(name);
    return res.getDirContext().getSchemaClassDefinition(res.getString());
}
 
Example 52
Project: oscm   File: LdapAccessStub.java   Source Code and License 4 votes vote down vote up
public <T> boolean searchOverLimit(Properties properties, String baseDN,
        String filter, ILdapResultMapper<T> mapper, boolean checkAttribute)
        throws NamingException {
    return false;
}
 
Example 53
Project: apache-tomcat-7.0.73-with-comment   File: EmptyDirContext.java   Source Code and License 4 votes vote down vote up
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
    return emptyName;
}
 
Example 54
Project: lazycat   File: EmptyDirContext.java   Source Code and License 4 votes vote down vote up
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException {
	return emptyEnv;
}
 
Example 55
Project: lams   File: JndiObjectLocator.java   Source Code and License 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws IllegalArgumentException, NamingException {
	if (!StringUtils.hasLength(getJndiName())) {
		throw new IllegalArgumentException("Property 'jndiName' is required");
	}
}
 
Example 56
Project: apache-tomcat-7.0.73-with-comment   File: DefaultInstanceManager.java   Source Code and License 4 votes vote down vote up
@Override
public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException {
    Class<?> clazz = loadClassMaybePrivileged(className, classLoader);
    return newInstance(clazz.newInstance(), clazz);
}
 
Example 57
Project: lams   File: CoreMessageLogger.java   Source Code and License 4 votes vote down vote up
@LogMessage(level = WARN)
@Message(value = "Naming exception occurred accessing factory: %s", id = 178)
void namingExceptionAccessingFactory(NamingException exception);
 
Example 58
Project: jdk8u-jdk   File: ContinuationDirContext.java   Source Code and License 4 votes vote down vote up
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException {
    DirContextNamePair res = getTargetContext(name);
    return res.getDirContext().getAttributes(res.getName(), attrIds);
}
 
Example 59
Project: apache-tomcat-7.0.73-with-comment   File: ResourceLinkFactory.java   Source Code and License 4 votes vote down vote up
/**
 * Create a new DataSource instance.
 *
 * @param obj The reference object describing the DataSource
 */
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
        Hashtable<?,?> environment) throws NamingException {

    if (!(obj instanceof ResourceLinkRef)) {
        return null;
    }

    // Can we process this request?
    Reference ref = (Reference) obj;

    // Read the global ref addr
    String globalName = null;
    RefAddr refAddr = ref.get(ResourceLinkRef.GLOBALNAME);
    if (refAddr != null) {
        globalName = refAddr.getContent().toString();
        // Confirm that the current web application is currently configured
        // to access the specified global resource
        if (!validateGlobalResourceAccess(globalName)) {
            return null;
        }
        Object result = null;
        result = globalContext.lookup(globalName);
        // Check the expected type
        String expectedClassName = ref.getClassName();
        if (expectedClassName == null) {
            throw new IllegalArgumentException(
                    sm.getString("resourceLinkFactory.nullType", name, globalName));
        }
        try {
            Class<?> expectedClazz = Class.forName(
                    expectedClassName, true, Thread.currentThread().getContextClassLoader());
            if (!expectedClazz.isAssignableFrom(result.getClass())) {
                throw new IllegalArgumentException(sm.getString("resourceLinkFactory.wrongType",
                        name, globalName, expectedClassName, result.getClass().getName()));
            }
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException(sm.getString("resourceLinkFactory.unknownType",
                    name, globalName, expectedClassName), e);
        }
        return result;
    }

    return null;
}
 
Example 60
Project: lazycat   File: EmptyDirContext.java   Source Code and License 4 votes vote down vote up
@Override
public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException {
	// no op
}