Example usage for com.google.common.collect ImmutableMap get

List of usage examples for com.google.common.collect ImmutableMap get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.baasbox.controllers.User.java

/***
 * Login the user./*from  w  w  w .  ja  va 2 s .  co m*/
 * parameters: 
 * username
 * password
 * appcode: the App Code (API KEY)
 * login_data: json serialized string containing info related to the device used by the user. In particular, for push notification, must by supplied:
 *    deviceId
 *    os: (android|ios)
 * @return
 * @throws SqlInjectionException 
 * @throws IOException 
 * @throws JsonProcessingException 
 */
@With({ NoUserCredentialWrapFilter.class })
public static Result login() throws SqlInjectionException, JsonProcessingException, IOException {
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;

    RequestBody body = request().body();
    //BaasBoxLogger.debug ("Login called. The body is: {}", body);
    if (body == null)
        return badRequest("missing data: is the body x-www-form-urlencoded or application/json? Detected: "
                + request().getHeader(CONTENT_TYPE));
    Map<String, String[]> bodyUrlEncoded = body.asFormUrlEncoded();
    if (bodyUrlEncoded != null) {
        if (bodyUrlEncoded.get("username") == null)
            return badRequest("The 'username' field is missing");
        else
            username = bodyUrlEncoded.get("username")[0];
        if (bodyUrlEncoded.get("password") == null)
            return badRequest("The 'password' field is missing");
        else
            password = bodyUrlEncoded.get("password")[0];
        if (bodyUrlEncoded.get("appcode") == null)
            return badRequest("The 'appcode' field is missing");
        else
            appcode = bodyUrlEncoded.get("appcode")[0];
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Username " + username);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Password " + password);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Appcode " + appcode);
        if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
                || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
            return forbidden(username + " cannot login");

        if (bodyUrlEncoded.get("login_data") != null)
            loginData = bodyUrlEncoded.get("login_data")[0];
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("LoginData" + loginData);
    } else {
        JsonNode bodyJson = body.asJson();
        if (bodyJson == null)
            return badRequest("missing data : is the body x-www-form-urlencoded or application/json? Detected: "
                    + request().getHeader(CONTENT_TYPE));
        if (bodyJson.get("username") == null)
            return badRequest("The 'username' field is missing");
        else
            username = bodyJson.get("username").asText();
        if (bodyJson.get("password") == null)
            return badRequest("The 'password' field is missing");
        else
            password = bodyJson.get("password").asText();
        if (bodyJson.get("appcode") == null)
            return badRequest("The 'appcode' field is missing");
        else
            appcode = bodyJson.get("appcode").asText();
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Username " + username);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Password " + password);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Appcode " + appcode);
        if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
                || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
            return forbidden(username + " cannot login");

        if (bodyJson.get("login_data") != null)
            loginData = bodyJson.get("login_data").asText();
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("LoginData" + loginData);
    }
    /* other useful parameter to receive and to store...*/
    //validate user credentials
    ODatabaseRecordTx db = null;
    String user = null;
    try {
        db = DbHelper.open(appcode, username, password);
        user = prepareResponseToJson(UserService.getCurrentUser());

        if (loginData != null) {
            JsonNode loginInfo = null;
            try {
                loginInfo = Json.parse(loginData);
            } catch (Exception e) {
                if (BaasBoxLogger.isDebugEnabled())
                    BaasBoxLogger.debug("Error parsong login_data field");
                if (BaasBoxLogger.isDebugEnabled())
                    BaasBoxLogger.debug(ExceptionUtils.getFullStackTrace(e));
                return badRequest("login_data field is not a valid json string");
            }
            Iterator<Entry<String, JsonNode>> it = loginInfo.fields();
            HashMap<String, Object> data = new HashMap<String, Object>();
            while (it.hasNext()) {
                Entry<String, JsonNode> element = it.next();
                String key = element.getKey();
                Object value = element.getValue().asText();
                data.put(key, value);
            }
            UserService.registerDevice(data);
        }
    } catch (OSecurityAccessException e) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("UserLogin: " + ExceptionUtils.getMessage(e));
        return unauthorized("user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("UserLogin: " + ExceptionUtils.getMessage(e));
        return badRequest("user " + username + " unauthorized");
    } finally {
        if (db != null && !db.isClosed())
            db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider.getSessionTokenProvider()
            .setSession(appcode, username, password);
    response().setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

    ObjectMapper mapper = new ObjectMapper();
    user = user.substring(0, user.lastIndexOf("}")) + ",\"" + SessionKeys.TOKEN.toString() + "\":\""
            + (String) sessionObject.get(SessionKeys.TOKEN) + "\"}";
    JsonNode jn = mapper.readTree(user);

    return ok(jn);
}

From source file:com.facebook.buck.cxx.CxxBinaryImplicitFlavors.java

public ImmutableSortedSet<Flavor> addImplicitFlavorsForRuleTypes(ImmutableSortedSet<Flavor> argDefaultFlavors,
        RuleType... types) {/*from   ww w.j ava  2 s  . c o  m*/
    Optional<Flavor> platformFlavor = getCxxPlatformsProvider().getUnresolvedCxxPlatforms()
            .getFlavor(argDefaultFlavors);

    for (RuleType type : types) {
        ImmutableMap<String, Flavor> libraryDefaults = cxxBuckConfig.getDefaultFlavorsForRuleType(type);

        if (!platformFlavor.isPresent()) {
            platformFlavor = Optional.ofNullable(libraryDefaults.get(CxxBuckConfig.DEFAULT_FLAVOR_PLATFORM));
        }
    }

    if (platformFlavor.isPresent()) {
        return ImmutableSortedSet.of(platformFlavor.get());
    } else {
        // To avoid changing the output path of binaries built without a flavor,
        // we'll default to no flavor, which implicitly builds the default platform.
        return ImmutableSortedSet.of();
    }
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLHealthMonitor.java

public synchronized void recordSample(String shardName, boolean success) {
    ImmutableMap<String, ShardState> shardHealthMap = shardHealthMapRef.get();

    ShardState shardState = shardHealthMap.get(shardName);
    if (shardState.healthSamples.remainingCapacity() == 0) {
        shardState.numSuccessesInWindow -= shardState.healthSamples.removeLast();
    }//from  ww w. jav a  2 s.  c  o  m

    int successVal = success ? 1 : 0;
    shardState.numSuccessesInWindow += successVal;
    shardState.healthSamples.addFirst(successVal);
}

From source file:io.awacs.server.DefaultRepositories.java

@Override
public void init(Configuration configuration) throws InitializationException {
    String[] repoNames = configuration.getString(Configurations.REPOSITORY_PREFIX).trim().split(",");
    for (String repoName : repoNames) {
        logger.debug("Repository {} configuration found.", repoName);
        ImmutableMap<String, String> resourceConfig = configuration
                .getSubProperties(Configurations.REPOSITORY_PREFIX + "." + repoName + ".");
        String className = resourceConfig.get(Configurations.REPOSITORY_CLASS);
        if (Strings.isNullOrEmpty(className))
            throw new InitializationException();
        try {//  w w w  . j  a  v a 2 s. c o  m
            Class<?> clazz = Class.forName(className);
            Object repository = clazz.newInstance();
            if (repository instanceof Configurable) {
                ((Configurable) repository).init(new Configuration(resourceConfig));
            }
            repositories.put(repoName, repository);
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
            throw new InitializationException();
        }
    }
}

From source file:com.facebook.buck.io.ExecutableFinder.java

private ImmutableSet<String> getExecutableSuffixes(ImmutableMap<String, String> env) {
    if (platform == Platform.WINDOWS) {
        String pathext = env.get("PATHEXT");
        if (pathext == null) {
            return DEFAULT_WINDOWS_EXTENSIONS;
        }/*from  ww w  . j av  a  2 s.c o m*/
        return ImmutableSet.<String>builder().addAll(Splitter.on(";").omitEmptyStrings().split(pathext))
                .build();
    }
    return ImmutableSet.of("");
}

From source file:com.github.rinde.jaamas17.GendreauResultWriter.java

public GendreauResultWriter(File target, Gendreau06ObjectiveFunction objFunc) {
    super(target, objFunc);

    try {/*from w w w  .  j a v  a  2 s .  c  o  m*/
        final ImmutableMap.Builder<String, ImmutableMap<Property, String>> mapBuilder = ImmutableMap.builder();
        for (final ImmutableMap<Property, String> map : MeasureGendreau
                .read(new File(MeasureGendreau.PROPS_FILE))) {

            final String id = map.get(Property.PROBLEM_CLASS) + SEPARATOR + map.get(Property.INSTANCE_ID);
            mapBuilder.put(id, map);
        }
        properties = mapBuilder.build();
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.wealdtech.hawk.jersey.HawkAuthenticator.java

/**
 * Authenticate a request from a bewit./*from ww  w .  ja  v  a2  s .  c o m*/
 * @param request the HTTP request
 * @return the authenticated principal, or <code>Optional.absent()</code> if the request was not authenticated
 * @throws DataError if there is a problem with the data that prevents the authentication attempt
 */
private Optional<T> authenticateFromBewit(final ContainerRequest request) {
    checkState((request.getMethod().equals("GET")), "HTTP method %s not supported with bewit",
            request.getMethod());
    final String bewit = server.extractBewit(request.getRequestUri());
    final ImmutableMap<String, String> bewitFields = server.splitBewit(bewit);
    final Optional<T> principal = provider.getFromKey(bewitFields.get("id"));
    if (!principal.isPresent()) {
        // Could not find the principal, reject this authentication request
        return Optional.absent();
    }
    final HawkCredentials credentials = principal.get().getHawkCredentials(bewitFields.get("id"));
    this.server.authenticate(credentials, request.getRequestUri());
    return principal;
}

From source file:com.facebook.buck.cxx.CxxLibraryImplicitFlavors.java

public ImmutableSortedSet<Flavor> addImplicitFlavorsForRuleTypes(ImmutableSortedSet<Flavor> argDefaultFlavors,
        RuleType... types) {//from  w  w w .  java  2s  .c o  m
    Optional<Flavor> typeFlavor = CxxLibraryDescription.LIBRARY_TYPE.getFlavor(argDefaultFlavors);
    CxxPlatformsProvider cxxPlatformsProvider = getCxxPlatformsProvider();
    Optional<Flavor> platformFlavor = cxxPlatformsProvider.getUnresolvedCxxPlatforms()
            .getFlavor(argDefaultFlavors);

    LOG.debug("Got arg default type %s platform %s", typeFlavor, platformFlavor);

    for (RuleType type : types) {
        ImmutableMap<String, Flavor> libraryDefaults = cxxBuckConfig.getDefaultFlavorsForRuleType(type);

        if (!typeFlavor.isPresent()) {
            typeFlavor = Optional.ofNullable(libraryDefaults.get(CxxBuckConfig.DEFAULT_FLAVOR_LIBRARY_TYPE));
        }

        if (!platformFlavor.isPresent()) {
            platformFlavor = Optional.ofNullable(libraryDefaults.get(CxxBuckConfig.DEFAULT_FLAVOR_PLATFORM));
        }
    }

    ImmutableSortedSet<Flavor> result = ImmutableSortedSet.of(
            // Default to static if not otherwise specified.
            typeFlavor.orElse(CxxDescriptionEnhancer.STATIC_FLAVOR),
            platformFlavor.orElse(cxxPlatformsProvider.getDefaultUnresolvedCxxPlatform().getFlavor()));

    LOG.debug("Got default flavors %s for rule types %s", result, Arrays.toString(types));
    return result;
}

From source file:org.grycap.gpf4med.TemplateManager.java

public @Nullable Template getTemplate(final ConceptNameTemplate conceptName) {
    checkArgument(conceptName != null, "Uninitialized or invalid concept name");
    final ImmutableMap<String, Template> templates = templates(null);
    return templates != null ? templates.get(Id.getId(conceptName)) : null;
}

From source file:io.druid.indexing.overlord.setup.JavaScriptWorkerSelectStrategy.java

@Override
public Optional<ImmutableZkWorker> findWorkerForTask(RemoteTaskRunnerConfig config,
        ImmutableMap<String, ImmutableZkWorker> zkWorkers, Task task) {
    String worker = fnSelector.apply(config, zkWorkers, task);
    return Optional.fromNullable(worker == null ? null : zkWorkers.get(worker));
}