de.otto.mongodb.profiler.web.DatabaseController.java Source code

Java tutorial

Introduction

Here is the source code for de.otto.mongodb.profiler.web.DatabaseController.java

Source

/*
 *  Copyright 2013 Robert Gacki <robert.gacki@cgi.com>
 *
 *  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 de.otto.mongodb.profiler.web;

import de.otto.mongodb.profiler.*;
import de.otto.mongodb.profiler.util.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.UriComponentsBuilder;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping(DatabaseController.CONTROLLER_RESOURCE)
public class DatabaseController extends AbstractController {

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

    public static final String CONTROLLER_RESOURCE = "/connections/{connectionId:.+}/databases";

    public DatabaseController(ProfilerService profilerService) {
        super(profilerService);
    }

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public View showDatabases(@PathVariable("connectionId") final String connectionId,
            final UriComponentsBuilder uriComponentsBuilder) throws ResourceNotFoundException {

        final String uri = uriComponentsBuilder.path("/connections/{connectionId}").buildAndExpand(connectionId)
                .toUriString();

        return new RedirectView(uri);
    }

    @Page(mainNavigation = MainNavigation.DATABASES)
    @RequestMapping(value = "/{name:.+}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView showDatabase(@PathVariable("connectionId") String connectionId,
            @PathVariable("name") String databaseName) throws ResourceNotFoundException {

        final ProfiledDatabase database = requireDatabase(connectionId, databaseName);

        final DatabasePageViewModel viewModel = new DatabasePageViewModel(database);

        return new ModelAndView("page.database").addObject("model", viewModel).addObject("collection",
                new AddCollectionProfileFormModel());
    }

    @Page(mainNavigation = MainNavigation.DATABASES)
    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ModelAndView addDatabase(@Valid @ModelAttribute("database") final AddDatabaseFormModel model,
            final BindingResult bindingResult, @PathVariable("connectionId") String connectionId,
            final UriComponentsBuilder uriComponentsBuilder) throws ResourceNotFoundException {

        final ProfiledConnection connection = requireConnection(connectionId);

        if (bindingResult.hasErrors()) {
            final List<? extends ProfiledDatabase> databases = getProfilerService().getDatabases(connection);
            final ConnectionPageViewModel viewModel = new ConnectionPageViewModel(connection, databases);
            return new ModelAndView("page.connection").addObject("model", viewModel).addObject("database", model);
        }

        final ProfiledDatabase database;
        try {
            if (model.isCredentialsAvailable()) {
                database = getProfilerService().addDatabase(connection, model.getName(), model.getUsername(),
                        model.getPassword().toCharArray());
            } else {
                database = getProfilerService().addDatabase(connection, model.getName());
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {

            if (e instanceof DatabaseDoesNotExistException) {
                logger.debug(e, "Failed to authenticate against database [%s]!", model.getName());
                bindingResult.rejectValue("name", "databaseDoesNotExist", "Database does not exist!");
            } else if (e instanceof DatabaseAlreadyConfiguredException) {
                logger.debug(e, "Failed to authenticate against database [%s]!", model.getName());
                bindingResult.rejectValue("name", "databaseAlreadyConfigured", "Database is already configured!");
            } else if (e instanceof AuthenticationException) {
                logger.info(e, "Failed to authenticate against database [%s]!", model.getName());
                bindingResult.reject("failedToAuthenticateDatabase",
                        "Failed to authenticate or authentication is required!");
            } else if (e instanceof ConnectivityException) {
                logger.warn(e, "There was a connectivity issue!", model.getName());
                bindingResult.reject("connectivityIssue", new Object[] { e.getMessage() },
                        "Failed to interact with the database: {0}!");
            } else {
                logger.warn(e, "Failed to authenticate against database [%s]!", model.getName());
                bindingResult.reject("unknownError");
            }

            final List<? extends ProfiledDatabase> databases = getProfilerService().getDatabases(connection);
            final ConnectionPageViewModel viewModel = new ConnectionPageViewModel(connection, databases);
            return new ModelAndView("page.connection").addObject("model", viewModel).addObject("database", model);
        }

        final String uri = uriComponentsBuilder.path("/connections/{id}/databases/{name}")
                .buildAndExpand(connection.getId(), database.getName()).toUriString();

        return new ModelAndView(new RedirectView(uri));
    }

    @RequestMapping(value = "/{name:.+}/control", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, params = "action=remove")
    public View removeDatabase(@PathVariable("connectionId") final String connectionId,
            @PathVariable("name") final String databaseName, final UriComponentsBuilder uriComponentsBuilder)
            throws ResourceNotFoundException {

        final ProfiledDatabase database = requireDatabase(connectionId, databaseName);
        getProfilerService().removeDatabase(database);

        final String uri = uriComponentsBuilder.path("/connections/{id}").buildAndExpand(connectionId)
                .toUriString();

        return new RedirectView(uri);
    }
}