com.tcloud.bee.key.server.restful.DummyController.java Source code

Java tutorial

Introduction

Here is the source code for com.tcloud.bee.key.server.restful.DummyController.java

Source

/**
 * Copyright 2013 Trend Micro Incorporated
 *
 * Licensed 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 com.tcloud.bee.key.server.restful;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import javax.crypto.KeyGenerator;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.io.crypto.bee.BeeConstants;
import org.apache.hadoop.io.crypto.bee.RestObjectResult;
import org.apache.hadoop.io.crypto.bee.RestResult;
import org.apache.hadoop.io.crypto.bee.key.sasl.common.KeyToken;
import org.apache.hadoop.io.crypto.bee.key.sasl.common.SaslUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.tcloud.bee.key.server.restful.verifier.BaseVerifier;
import com.tcloud.bee.key.server.restful.verifier.KeyNameVerifier;
import com.tcloud.bee.key.server.restful.verifier.ParametersVerifier;
import com.tcloud.bee.key.server.restful.verifier.UsersVerifier;
import com.tcloud.bee.key.server.service.KeyManageService;
import com.tcloud.bee.key.server.service.SaslService;
import com.tcloud.bee.key.server.service.KeyTokenStore;

/**
 * @author howie_yu
 * 
 */
@Path("/api")
@Controller
public class DummyController {

    final Logger logger = LoggerFactory.getLogger(getClass());

    private Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    @Inject
    private KeyTokenStore keyTokenStore;

    @Inject
    private KeyManageService keyManageService;

    @Inject
    private SaslService saslService;

    private final KeyGenerator keyGen;
    {
        try {
            keyGen = KeyGenerator.getInstance(SaslUtil.DEFAULT_HMAC_ALGORITHM);
            keyGen.init(SaslUtil.KEY_LENGTH);
        } catch (NoSuchAlgorithmException nsa) {
            throw new IllegalArgumentException("Can't find " + SaslUtil.DEFAULT_HMAC_ALGORITHM + " algorithm.");
        }
    }

    @GET
    @Path("/ping")
    public Response ping() {

        String currentPrincipalName = authentication.getName();

        logger.info("ping by {}", currentPrincipalName);
        return Response.ok("ping by " + currentPrincipalName).build();
    }

    @GET
    @Path("/echo/{msg}")
    public Response echo(@PathParam("msg") String msg) {
        String currentPrincipalName = authentication.getName();
        logger.info("[{}]msg:{}", currentPrincipalName, msg);

        return Response.ok(msg).build();
    }

    @GET
    @Path("/uuid_test/{msg}")
    public Response uuid_test(@PathParam("msg") String msg) {
        //String currentPrincipalName = authentication.getName();
        //logger.info("[{}]msg:{}", currentPrincipalName, msg);
        logger.info("Get uuid:{}", msg);
        KeyToken keyToken = keyTokenStore.getToken(UUID.fromString(msg));

        return Response.ok("password:" + new String(keyToken.getPassword())).build();
    }

    @GET
    @Path("/createToken")
    public Response createToken() {
        String currentPrincipalName = authentication.getName();
        logger.info("currentPrincipalName: {}: createToken", currentPrincipalName);

        //TODO Add checking: Only our user can create token
        String username = authentication.getName().split("@")[0];
        byte[] password;
        synchronized (keyGen) {
            password = keyGen.generateKey().getEncoded();
        }

        KeyToken token = new KeyToken(UUID.randomUUID(), username, password);
        keyTokenStore.addToken(token);

        RestObjectResult restObjectResult = new RestObjectResult(BeeConstants.ResponseStatus.SUCCESS.toString(),
                token);
        return Response.ok(new Gson().toJson(restObjectResult, RestObjectResult.class))
                .type(MediaType.APPLICATION_JSON).build();
    }

    @GET
    @Path("/removeToken/{msg}")
    public Response removeToken(@PathParam("msg") String msg) {
        String currentPrincipalName = authentication.getName();
        logger.info("currentPrincipalName: {}: removeToken", currentPrincipalName);

        String strMsg = new String(Base64.decodeBase64(msg));
        logger.debug("Token string:" + msg + ", decoded:" + strMsg);
        KeyToken token = new Gson().fromJson(strMsg, KeyToken.class);

        RestResult restResult = keyTokenStore.removeToken(token.getId(), authentication.getName().split("@")[0]);

        return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                .build();
    }

    @GET
    @Path("/createKey/{keyNameAndUsers}")
    public Response createKey(@PathParam("keyNameAndUsers") String keyNameAndUsers)
            throws NoSuchAlgorithmException, FileNotFoundException, IOException {
        logger.trace("keyNameAndUsers: {}", keyNameAndUsers);

        BaseVerifier paramVerifier = new ParametersVerifier(new KeyNameVerifier(new UsersVerifier(null)));
        RestResult restResult = paramVerifier.verify(keyNameAndUsers);

        if (!restResult.getResult().toString().equals(BeeConstants.ResponseStatus.SUCCESS.toString())) {
            return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                    .build();
        }

        String currentPrincipalName = authentication.getName();
        String owner = currentPrincipalName.substring(0, currentPrincipalName.indexOf("@"));

        KeyManageService.QueryResult queryResult = keyManageService.createKey(new Param(keyNameAndUsers), owner);
        restResult = new RestResult(queryResult.status.toString(), queryResult.msg);
        return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                .build();
    }

    @GET
    @Path("/updateKeyUsers/{keyNameAndUsers}")
    public Response updateKeyUsers(@PathParam("keyNameAndUsers") String keyNameAndUsers)
            throws NoSuchAlgorithmException, FileNotFoundException, IOException {
        logger.trace("keyNameAndUsers: {}", keyNameAndUsers);

        BaseVerifier paramVerifier = new ParametersVerifier(new KeyNameVerifier(new UsersVerifier(null)));
        RestResult restResult = paramVerifier.verify(keyNameAndUsers);

        if (!restResult.getResult().toString().equals(BeeConstants.ResponseStatus.SUCCESS.toString())) {
            return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                    .build();
        }

        String currentPrincipalName = authentication.getName();
        String owner = currentPrincipalName.substring(0, currentPrincipalName.indexOf("@"));

        KeyManageService.QueryResult queryResult = keyManageService.updateKeyUsers(new Param(keyNameAndUsers),
                owner);
        restResult = new RestResult(queryResult.status.toString(), queryResult.msg);
        return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                .build();
    }

    @GET
    @Path("/queryKeyInfo/{keyName}")
    public Response queryKeyInfo(@PathParam("keyName") String keyName) throws FileNotFoundException, IOException {
        if (!keyName.matches(BeeConstants.KEY_NAME_PATTERN)) {
            RestResult restResult = new RestResult(BeeConstants.ResponseStatus.FAIL.toString(),
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_PARAM_KEYNAME_INVALID));
            return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                    .build();
        }
        String currentPrincipalName = authentication.getName();
        String userName = currentPrincipalName.substring(0, currentPrincipalName.indexOf("@"));

        KeyManageService.QueryResult queryResult = keyManageService.queryKeyInfo(keyName, userName);
        RestObjectResult restObjectResult = new RestObjectResult(queryResult.status.toString(), queryResult.rtnObj);
        return Response.ok(new Gson().toJson(restObjectResult, RestObjectResult.class))
                .type(MediaType.APPLICATION_JSON).build();
    }

    @GET
    @Path("/getHexkey/{keyName}")
    public Response getHexkey(@PathParam("keyName") String keyName) throws FileNotFoundException, IOException {
        if (!keyName.matches(BeeConstants.KEY_NAME_PATTERN)) {
            RestResult restResult = new RestResult(BeeConstants.ResponseStatus.FAIL.toString(),
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_PARAM_KEYNAME_INVALID));
            return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                    .build();
        }

        String currentPrincipalName = authentication.getName();
        String userName = currentPrincipalName.substring(0, currentPrincipalName.indexOf("@"));

        KeyManageService.QueryResult queryResult = keyManageService.getHexkey(keyName, userName);
        RestResult restResult = new RestResult(queryResult.status.toString(), queryResult.msg);
        return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                .build();
    }

    @GET
    @Path("/deleteKey/{keyName}")
    public Response deleteKey(@PathParam("keyName") String keyName) throws FileNotFoundException, IOException {
        if (!keyName.matches(BeeConstants.KEY_NAME_PATTERN)) {
            RestResult restResult = new RestResult(BeeConstants.ResponseStatus.FAIL.toString(),
                    BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_PARAM_KEYNAME_INVALID));
            return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                    .build();
        }
        String currentPrincipalName = authentication.getName();
        String userName = currentPrincipalName.substring(0, currentPrincipalName.indexOf("@"));

        KeyManageService.QueryResult queryResult = keyManageService.deleteKey(keyName, userName);
        RestResult restResult = new RestResult(queryResult.status.toString(), queryResult.msg);
        return Response.ok(new Gson().toJson(restResult, RestResult.class)).type(MediaType.APPLICATION_JSON)
                .build();
    }

    @GET
    @Path("/sasl/echo/{msg}")
    public Response saslEcho(@PathParam("msg") String msg) {
        logger.debug("into method: saslEcho");
        String currentPrincipalName = authentication.getName();
        logger.info("[{}]msg:{}", currentPrincipalName, msg);

        return Response.ok(msg).build();
    }

    @GET
    @Path("/sasl/getkey/{msg}")
    public Response saslGetkey(@PathParam("msg") String msg) {
        logger.debug("into method: saslGetkey");
        try {
            String decodeMsg = new String(Base64.decodeBase64(msg));
            //logger.debug("decodeMsg:{}", decodeMsg);
            String returnMsg = saslService.getKey(decodeMsg);
            return Response.ok(returnMsg).build();
        } catch (Exception e) {
            logger.info("Request getkey fail. Exception:", e);
            return Response.ok("").build();
        }
    }
}