All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.marvelution.jira.plugins.jenkins.rest.SiteResource Maven / Gradle / Ivy

There is a newer version: 2.3.1
Show newest version
/*
 * Copyright (c) 2012-present Marvelution B.V.
 *
 * 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 org.marvelution.jira.plugins.jenkins.rest;

import java.util.List;
import java.util.Optional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.marvelution.jira.plugins.jenkins.model.ErrorMessages;
import org.marvelution.jira.plugins.jenkins.model.RestData;
import org.marvelution.jira.plugins.jenkins.model.Site;
import org.marvelution.jira.plugins.jenkins.model.SiteStatus;
import org.marvelution.jira.plugins.jenkins.model.SiteSyncStatus;
import org.marvelution.jira.plugins.jenkins.rest.exception.BadRequestException;
import org.marvelution.jira.plugins.jenkins.rest.exception.NotFoundException;
import org.marvelution.jira.plugins.jenkins.rest.security.AdminRequired;
import org.marvelution.jira.plugins.jenkins.services.Communicator;
import org.marvelution.jira.plugins.jenkins.services.CommunicatorFactory;
import org.marvelution.jira.plugins.jenkins.services.JobService;
import org.marvelution.jira.plugins.jenkins.services.SiteService;

import com.atlassian.plugin.spring.scanner.annotation.component.Scanned;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.atlassian.sal.api.message.I18nResolver;
import org.apache.commons.lang3.StringUtils;

import static java.util.stream.Collectors.toCollection;

/**
 * REST resource for {@link Site}s
 *
 * @author Mark Rekveld
 * @since 1.0.0
 */
@Scanned
@AdminRequired
@Path("site")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class SiteResource {

	private final SiteService siteService;
	private final JobService jobService;
	private final CommunicatorFactory communicatorFactory;
	private final I18nResolver i18nResolver;

	public SiteResource(SiteService siteService, JobService jobService, CommunicatorFactory communicatorFactory,
	                    @ComponentImport I18nResolver i18nResolver) {
		this.siteService = siteService;
		this.jobService = jobService;
		this.communicatorFactory = communicatorFactory;
		this.i18nResolver = i18nResolver;
	}

	/**
	 * Get all the sites available
	 *
	 * @return collection of all the sites
	 */
	@GET
	public List getAll(@QueryParam("includeJobs") @DefaultValue("false") boolean includeJobs) {
		return siteService.getAll(includeJobs);
	}

	/**
	 * Adds a new site
	 *
	 * @param site the new site to add
	 */
	@POST
	public Site addSite(Site site) {
		if (site.getId() != 0) {
			throw new BadRequestException();
		} else {
			site.setToken(site.getNewtoken());
			return validateAndStoreSite(site);
		}
	}

	private Site validateAndStoreSite(Site site) {
		ErrorMessages errorMessages = new ErrorMessages();
		if (site.getType() == null) {
			errorMessages.addError("type", i18nResolver.getText("site.type.required"));
		}
		if (StringUtils.isBlank(site.getName())) {
			errorMessages.addError("name", i18nResolver.getText("site.name.required"));
		}
		if (site.getRpcUrl() == null) {
			errorMessages.addError("rpcUrl", i18nResolver.getText("site.rpc.url.required"));
		} else if (site.getRpcUrl().getHost() == null) {
			errorMessages.addError("rpcUrl", i18nResolver.getText("url.invalid", "host"));
		}
		if (site.hasDisplayUrl() && site.getDisplayUrl().getHost() == null) {
			errorMessages.addError("displayUrl", i18nResolver.getText("url.invalid", "host"));
		}
		if (StringUtils.isNotBlank(site.getUser()) && StringUtils.isBlank(site.getToken())) {
			errorMessages.addError("token", i18nResolver.getText("site.token.required"));
		} else if (StringUtils.isNotBlank(site.getToken()) && StringUtils.isBlank(site.getUser())) {
			errorMessages.addError("user", i18nResolver.getText("site.user.required"));
		}
		if (!errorMessages.hasErrors()) {
			if (site.getId() == 0) {
				site.setSupportsBackLink(false);
				site.setUseCrumbs(true);
			}
			Site saved = siteService.save(site);
			siteService.sync(saved);
			return saved;
		} else {
			throw new BadRequestException(errorMessages);
		}
	}

	/**
	 * Get a {@link Site} by its Id
	 *
	 * @param siteId the site id
	 * @return Ok Response in case there is a site with the given Id and a Not Found otherwise
	 */
	@GET
	@Path("{siteId}")
	public Site get(@PathParam("siteId") int siteId, @QueryParam("includeJobs") @DefaultValue("false") boolean includeJobs) {
		Site site = siteService.get(siteId);
		if (site == null) {
			throw new NotFoundException();
		} else {
			if (includeJobs) {
				site.setJobs(jobService.getAllBySite(site));
			}
			return site;
		}
	}

	/**
	 * Updates a site
	 *
	 * @param siteId the id of the site to update, must match the id with the site parameter
	 * @param site   the site details
	 */
	@POST
	@Path("{siteId}")
	public Site updateSite(@PathParam("siteId") int siteId, Site site) {
		if (siteId < 1 || siteId != site.getId()) {
			throw new BadRequestException();
		} else {
			Site existing = siteService.get(site.getId());
			if (existing == null) {
				throw new NotFoundException();
			} else {
				existing.setType(site.getType());
				existing.setName(site.getName());
				existing.setRpcUrl(site.getRpcUrl());
				existing.setDisplayUrl(site.getDisplayUrl());
				existing.setAutoLink(site.isAutoLink());
				existing.setUser(site.getUser());
				if (site.isChangeToken() && StringUtils.isNotBlank(site.getNewtoken())) {
					existing.setToken(site.getNewtoken());
				}
				return validateAndStoreSite(existing);
			}
		}
	}

	/**
	 * Delete a site
	 *
	 * @param siteId the id of the site to delete
	 */
	@DELETE
	@Path("{siteId}")
	public void deleteSite(@PathParam("siteId") int siteId) {
		Site site = siteService.get(siteId);
		if (site == null) {
			throw new NotFoundException();
		} else {
			siteService.delete(site);
		}
	}

	/**
	 * Sync the {@link Site} by its given Id
	 *
	 * @param siteId the id of the Site to sync
	 */
	@POST
	@Path("{siteId}/sync")
	public void syncJobList(@PathParam("siteId") int siteId) {
		Site site = siteService.get(siteId);
		if (site != null) {
			siteService.sync(site);
		} else {
			throw new NotFoundException();
		}
	}

	/**
	 * Enable or Disable the auto linking of the site
	 *
	 * @param siteId   the id of the {@link Site}
	 * @param restData the {@link RestData} payload send
	 */
	@POST
	@Path("{siteId}/autolink")
	public void enableAutoLink(@PathParam("siteId") int siteId, RestData restData) {
		Site site = siteService.get(siteId);
		if (site != null) {
			siteService.enable(siteId, Boolean.parseBoolean(restData.getPayload()));
		} else {
			throw new NotFoundException();
		}
	}

	/**
	 * Get the current synchronization status of a site
	 *
	 * @param siteId the site id
	 * @return 200 OK with {@link SiteSyncStatus} status, 204 NO CONTENT or 404 NOT FOUND if the site is not found
	 */
	@GET
	@Path("{siteId}/sync/status")
	public SiteSyncStatus getSyncStatus(@PathParam("siteId") int siteId, @QueryParam("includeJobs") boolean includeJobs) {
		SiteSyncStatus status = Optional.ofNullable(siteService.get(siteId))
		                                .map(siteService::getSyncStatus)
		                                .orElseThrow(NotFoundException::new);
		if (includeJobs) {
			jobService.getAllBySite(status.getSite()).stream()
			          .map(jobService::getSyncStatus)
			          .collect(toCollection(status::getJobs));
		}
		return status;
	}

	/**
	 * Check is the {@link Site} is online and accessible
	 *
	 * @param siteId the id of the {@link Site}
	 * @return {@link SiteStatus}
	 */
	@GET
	@Path("{siteId}/status")
	public SiteStatus siteStatus(@PathParam("siteId") int siteId) {
		SiteStatus status;
		Site site = siteService.get(siteId);
		if (site != null) {
			Communicator communicator = communicatorFactory.get(site);
			status = SiteStatus.forStatus(communicator.getRemoteStatus(), site);
			if (status.getStatus().isAccessible()) {
				status.setPluginInstalled(communicator.isJenkinsPluginInstalled());
			}
			return status;
		} else {
			throw new NotFoundException();
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy