Search in sources :

Example 46 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project presto by prestodb.

the class ThrowableMapper method toResponse.

@Override
public Response toResponse(Throwable throwable) {
    if (throwable instanceof WebApplicationException) {
        return ((WebApplicationException) throwable).getResponse();
    }
    log.warn(throwable, "Request failed for %s", request.getRequestURI());
    ResponseBuilder responseBuilder = Response.serverError().header(CONTENT_TYPE, TEXT_PLAIN);
    if (includeExceptionInResponse) {
        responseBuilder.entity(Throwables.getStackTraceAsString(throwable));
    } else {
        responseBuilder.entity("Exception processing request");
    }
    return responseBuilder.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder)

Example 47 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project platformlayer by platformlayer.

the class ServiceAuthorizationResource method createService.

// We deliberately don't support this at the moment... it's quite restrictive on our data store
// @GET
// @Produces({ APPLICATION_XML, APPLICATION_JSON })
// public <T> ServiceAuthorizationCollection getAll() {
// List<ServiceAuthorization> items = authorizationRepository.getByAccountId(getAccountId());
// ServiceAuthorizationCollection collection = new ServiceAuthorizationCollection();
// collection.items = items;
// return collection;
// }
@POST
@Consumes({ XML, JSON })
@Produces({ XML, JSON })
public <T> ServiceAuthorization createService(final ServiceAuthorization authorization) throws OpsException, RepositoryException {
    ServiceType serviceType = getServiceType();
    authorization.serviceType = serviceType.getKey();
    final ServiceProvider serviceProvider = opsSystem.getServiceProvider(serviceType);
    if (serviceProvider == null) {
        log.warn("Unknown serviceProvider: " + serviceType);
        throw new WebApplicationException(404);
    }
    String data = authorization.data;
    if (Strings.isNullOrEmpty(data)) {
        throw new IllegalArgumentException("Data is required");
    }
    data = data.trim();
    if (data.startsWith("{")) {
        // Convert to XML
        SettingCollection settings = new SettingCollection();
        settings.items = Lists.newArrayList();
        // We presume it's a simple map of keys and values
        try {
            JSONObject json = new JSONObject(data);
            @SuppressWarnings("unchecked") Iterator<String> keys = json.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = json.getString(key);
                Setting setting = new Setting();
                setting.key = key;
                setting.value = value;
                settings.items.add(setting);
            }
        } catch (JSONException e) {
            throw new IllegalArgumentException("Error parsing data", e);
        }
        JaxbHelper jaxbHelper = JaxbHelper.get(SettingCollection.class);
        String xml;
        try {
            xml = jaxbHelper.marshal(settings, false);
        } catch (JAXBException e) {
            throw new IllegalArgumentException("Error converting JSON to XML", e);
        }
        authorization.data = xml;
    }
    // Authentication authentication = getAuthentication();
    //
    // OpsContextBuilder opsContextBuilder = opsSystem.getInjector().getInstance(OpsContextBuilder.class);
    // final OpsContext opsContext = opsContextBuilder.buildOpsContext(serviceType, authentication, false);
    //
    // OpsContext.runInContext(opsContext, new CheckedCallable<Object, Exception>() {
    // @Override
    // public Object call() throws Exception {
    // serviceProvider.validateAuthorization(authorization);
    // return null;
    // }
    // });
    // serviceProvider.validateAuthorization(authorization);
    ServiceAuthorization created = authorizationRepository.createAuthorization(getProject(), authorization);
    // For security, never return the data
    created.data = null;
    return created;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SettingCollection(org.platformlayer.xaas.model.SettingCollection) Setting(org.platformlayer.xaas.model.Setting) JAXBException(javax.xml.bind.JAXBException) JSONException(org.json.JSONException) ServiceAuthorization(org.platformlayer.xaas.model.ServiceAuthorization) JSONObject(org.json.JSONObject) ServiceType(org.platformlayer.ids.ServiceType) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) JaxbHelper(org.platformlayer.xml.JaxbHelper) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 48 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project platformlayer by platformlayer.

the class ServiceResource method getSshPublicKey.

@GET
@Path("sshkey")
@Produces({ TEXT_PLAIN })
public String getSshPublicKey() throws RepositoryException, OpsException, IOException {
    final ServiceProvider serviceProvider = getServiceProvider();
    if (serviceProvider == null) {
        raiseNotFound();
    }
    OpsContextBuilder opsContextBuilder = opsContextBuilderFactory.get();
    final OpsContext opsContext = opsContextBuilder.buildTemporaryOpsContext(serviceProvider.getServiceType(), getProjectAuthorization());
    PublicKey publicKey = OpsContext.runInContext(opsContext, new CheckedCallable<PublicKey, Exception>() {

        @Override
        public PublicKey call() throws Exception {
            PublicKey publicKey = serviceProvider.getSshPublicKey();
            return publicKey;
        }
    });
    if (publicKey == null) {
        throw new WebApplicationException(404);
    }
    String description = "platformlayer://" + getProject().getKey() + "/" + serviceProvider.getServiceType().getKey();
    return OpenSshUtils.serialize(publicKey, description);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) PublicKey(java.security.PublicKey) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) OpsContext(org.platformlayer.ops.OpsContext) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) WebApplicationException(javax.ws.rs.WebApplicationException) OpsContextBuilder(org.platformlayer.ops.tasks.OpsContextBuilder) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 49 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project platformlayer by platformlayer.

the class BlobsResource method downloadBlob.

@GET
@Path("blob/{blobId}")
public Response downloadBlob(@PathParam("blobId") String blobId) {
    Download download = oneTimeDownloads.get(blobId);
    if (download == null) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    String responseData = download.getContent();
    String contentType = download.getContentType();
    ResponseBuilder rBuild = Response.ok(responseData, contentType);
    return rBuild.build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Download(org.platformlayer.ops.OneTimeDownloads.Download) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 50 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project helios by spotify.

the class HostsResource method list.

/**
   * Returns the list of hostnames of known hosts/agents.
   * @return The list of hostnames.
   */
@GET
@Produces(APPLICATION_JSON)
@Timed
@ExceptionMetered
public List<String> list(@QueryParam("namePattern") final String namePattern, @QueryParam("selector") final List<String> hostSelectors) {
    List<String> hosts = model.listHosts();
    if (namePattern != null) {
        final Predicate<String> matchesPattern = Pattern.compile(namePattern).asPredicate();
        hosts = hosts.stream().filter(matchesPattern).collect(Collectors.toList());
    }
    if (!hostSelectors.isEmpty()) {
        // check that all supplied selectors are parseable/valid
        final List<HostSelector> selectors = hostSelectors.stream().map(selectorStr -> {
            final HostSelector parsed = HostSelector.parse(selectorStr);
            if (parsed == null) {
                throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("Invalid host selector: " + selectorStr).build());
            }
            return parsed;
        }).collect(Collectors.toList());
        final Map<String, Map<String, String>> hostsAndLabels = getLabels(hosts);
        final HostMatcher matcher = new HostMatcher(hostsAndLabels);
        hosts = matcher.getMatchingHosts(selectors);
    }
    return hosts;
}
Also used : Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) SetGoalResponse(com.spotify.helios.common.protocol.SetGoalResponse) HostRegisterResponse(com.spotify.helios.common.protocol.HostRegisterResponse) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Optional(com.google.common.base.Optional) JobUndeployResponse(com.spotify.helios.common.protocol.JobUndeployResponse) Map(java.util.Map) INVALID_ID(com.spotify.helios.common.protocol.JobUndeployResponse.Status.INVALID_ID) Deployment(com.spotify.helios.common.descriptors.Deployment) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) HostStillInUseException(com.spotify.helios.master.HostStillInUseException) JobDeployResponse(com.spotify.helios.common.protocol.JobDeployResponse) DELETE(javax.ws.rs.DELETE) HostMatcher(com.spotify.helios.master.HostMatcher) Responses.notFound(com.spotify.helios.master.http.Responses.notFound) JobDoesNotExistException(com.spotify.helios.master.JobDoesNotExistException) FORBIDDEN(com.spotify.helios.common.protocol.JobUndeployResponse.Status.FORBIDDEN) Predicate(java.util.function.Predicate) JOB_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.JOB_NOT_FOUND) Collectors(java.util.stream.Collectors) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) JobPortAllocationConflictException(com.spotify.helios.master.JobPortAllocationConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) Responses.badRequest(com.spotify.helios.master.http.Responses.badRequest) Pattern(java.util.regex.Pattern) JobId(com.spotify.helios.common.descriptors.JobId) PathParam(javax.ws.rs.PathParam) HOST_NOT_FOUND(com.spotify.helios.common.protocol.JobUndeployResponse.Status.HOST_NOT_FOUND) GET(javax.ws.rs.GET) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) OK(com.spotify.helios.common.protocol.JobUndeployResponse.Status.OK) PATCH(com.spotify.helios.master.http.PATCH) Function(java.util.function.Function) Responses.forbidden(com.spotify.helios.master.http.Responses.forbidden) HostSelector(com.spotify.helios.common.descriptors.HostSelector) EMPTY_TOKEN(com.spotify.helios.common.descriptors.Job.EMPTY_TOKEN) HostStatus(com.spotify.helios.common.descriptors.HostStatus) HostNotFoundException(com.spotify.helios.master.HostNotFoundException) JobAlreadyDeployedException(com.spotify.helios.master.JobAlreadyDeployedException) MasterModel(com.spotify.helios.master.MasterModel) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) HostDeregisterResponse(com.spotify.helios.common.protocol.HostDeregisterResponse) Maps(com.google.common.collect.Maps) TokenVerificationException(com.spotify.helios.master.TokenVerificationException) PUT(javax.ws.rs.PUT) JobNotDeployedException(com.spotify.helios.master.JobNotDeployedException) WebApplicationException(javax.ws.rs.WebApplicationException) HostSelector(com.spotify.helios.common.descriptors.HostSelector) Map(java.util.Map) HostMatcher(com.spotify.helios.master.HostMatcher) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)276 Produces (javax.ws.rs.Produces)77 GET (javax.ws.rs.GET)71 Path (javax.ws.rs.Path)69 IOException (java.io.IOException)47 POST (javax.ws.rs.POST)47 Consumes (javax.ws.rs.Consumes)44 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)43 Response (javax.ws.rs.core.Response)30 MediaType (javax.ws.rs.core.MediaType)26 URI (java.net.URI)25 HashMap (java.util.HashMap)20 JSONObject (org.codehaus.jettison.json.JSONObject)20 Test (org.junit.Test)19 JSONException (org.codehaus.jettison.json.JSONException)18 ApiOperation (io.swagger.annotations.ApiOperation)17 ArrayList (java.util.ArrayList)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)15 List (java.util.List)14