<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.usergrid.services.users;


import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.usergrid.persistence.cache.CacheScope;
import org.apache.usergrid.persistence.cache.ScopedCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.management.UserInfo;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.EntityRef;
import org.apache.usergrid.persistence.index.query.Identifier;
import org.apache.usergrid.persistence.Query;
import org.apache.usergrid.persistence.Results;
import org.apache.usergrid.persistence.Schema;
import org.apache.usergrid.persistence.entities.Role;
import org.apache.usergrid.security.shiro.utils.SubjectUtils;
import org.apache.usergrid.services.AbstractCollectionService;
import org.apache.usergrid.services.ServiceContext;
import org.apache.usergrid.services.ServicePayload;
import org.apache.usergrid.services.ServiceRequest;
import org.apache.usergrid.services.ServiceResults;
import org.apache.usergrid.services.exceptions.ServiceResourceNotFoundException;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.usergrid.persistence.Schema.PROPERTY_EMAIL;
import static org.apache.usergrid.persistence.Schema.PROPERTY_PICTURE;
import static org.apache.usergrid.services.ServiceResults.genericServiceResults;
import static org.apache.usergrid.utils.ConversionUtils.string;


public class UsersService extends AbstractCollectionService {

    private static final Logger logger = LoggerFactory.getLogger( UsersService.class );


    public UsersService() {
        super();
        if (logger.isTraceEnabled()) {
            logger.trace("/users");
        }

        makeConnectionPrivate( "following" );

        declareVirtualCollections( Arrays.asList( "following", "followers" ) );

        addReplaceParameters( Arrays.asList( "$id", "followers" ), Arrays.asList( "\\0", "connecting", "following" ) );

        // rolenames is the one case of Entity Dictionary name not equal to path segment
        declareEntityDictionary( new EntityDictionaryEntry( "rolenames", "roles" ) );

        declareEntityDictionaries( Arrays.asList( "permissions" ) );
    }


    @Override
    public ServiceResults getItemByName( ServiceContext context, String name ) throws Exception {
        String nameProperty = Schema.getDefaultSchema().aliasProperty( getEntityType() );

        if ( nameProperty == null ) {
            nameProperty = "name";
        }

        EntityRef entity = null;
        Identifier id = Identifier.from( name );

        if ( id != null ) {
            entity = em.getUserByIdentifier( id );
        }

        if ( entity == null ) {
            throw new ServiceResourceNotFoundException( context );
        }

        if ( !context.moreParameters() ) {
            entity = em.get( entity );
            entity = importEntity( context, ( Entity ) entity );
        }

        checkPermissionsForEntity( context, entity );

        List<ServiceRequest> nextRequests = context.getNextServiceRequests( entity );

        return new ServiceResults( this, context, ServiceResults.Type.COLLECTION, Results.fromRef( entity ), null,
                nextRequests );
    }


    @Override
    public ServiceResults invokeItemWithName( ServiceContext context, String name ) throws Exception {
        if ( "me".equals( name ) ) {
            UserInfo user = SubjectUtils.getUser();
            if ( ( user != null ) && ( user.getUuid() != null ) ) {
                return super.invokeItemWithId( context, user.getUuid() );
            }
        }
        return super.invokeItemWithName( context, name );
    }<commit_msg>Fix NPE when user doesn't exist after lookup from the unique value index.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.usergrid.services.users;


import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.usergrid.persistence.cache.CacheScope;
import org.apache.usergrid.persistence.cache.ScopedCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.management.UserInfo;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.EntityRef;
import org.apache.usergrid.persistence.index.query.Identifier;
import org.apache.usergrid.persistence.Query;
import org.apache.usergrid.persistence.Results;
import org.apache.usergrid.persistence.Schema;
import org.apache.usergrid.persistence.entities.Role;
import org.apache.usergrid.security.shiro.utils.SubjectUtils;
import org.apache.usergrid.services.AbstractCollectionService;
import org.apache.usergrid.services.ServiceContext;
import org.apache.usergrid.services.ServicePayload;
import org.apache.usergrid.services.ServiceRequest;
import org.apache.usergrid.services.ServiceResults;
import org.apache.usergrid.services.exceptions.ServiceResourceNotFoundException;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.usergrid.persistence.Schema.PROPERTY_EMAIL;
import static org.apache.usergrid.persistence.Schema.PROPERTY_PICTURE;
import static org.apache.usergrid.services.ServiceResults.genericServiceResults;
import static org.apache.usergrid.utils.ConversionUtils.string;


public class UsersService extends AbstractCollectionService {

    private static final Logger logger = LoggerFactory.getLogger( UsersService.class );


    public UsersService() {
        super();
        if (logger.isTraceEnabled()) {
            logger.trace("/users");
        }

        makeConnectionPrivate( "following" );

        declareVirtualCollections( Arrays.asList( "following", "followers" ) );

        addReplaceParameters( Arrays.asList( "$id", "followers" ), Arrays.asList( "\\0", "connecting", "following" ) );

        // rolenames is the one case of Entity Dictionary name not equal to path segment
        declareEntityDictionary( new EntityDictionaryEntry( "rolenames", "roles" ) );

        declareEntityDictionaries( Arrays.asList( "permissions" ) );
    }


    @Override
    public ServiceResults getItemByName( ServiceContext context, String name ) throws Exception {
        
        EntityRef entity = null;
        Identifier id = Identifier.from( name );

        if ( id != null ) {
            // get the entityRef from the unique value index
            entity = em.getUserByIdentifier( id );
        }

        if ( entity == null ) {
            throw new ServiceResourceNotFoundException( context );
        }

        if ( !context.moreParameters() ) {

            // full load the entity from the database based on the UUID from the unique value index
            entity = em.get( entity );

            if ( entity == null ) {
                throw new ServiceResourceNotFoundException( context );
            }

            entity = importEntity( context, ( Entity ) entity );
        }

        checkPermissionsForEntity( context, entity );

        List<ServiceRequest> nextRequests = context.getNextServiceRequests( entity );

        return new ServiceResults( this, context, ServiceResults.Type.COLLECTION, Results.fromRef( entity ), null,
                nextRequests );
    }


    @Override
    public ServiceResults invokeItemWithName( ServiceContext context, String name ) throws Exception {
        if ( "me".equals( name ) ) {
            UserInfo user = SubjectUtils.getUser();
            if ( ( user != null ) && ( user.getUuid() != null ) ) {
                return super.invokeItemWithId( context, user.getUuid() );
            }
        }
        return super.invokeItemWithName( context, name );
    }
{'fraction_non_alphanumeric': 0.09307875894988067, 'fraction_numerical': 0.0016602677181695549, 'mean_word_length': 3.4703153988868274, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1796766', 'n_tokens_mistral': 2517, 'n_tokens_neox': 2489, 'n_words': 704}