Search in sources :

Example 66 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class PreviewHttpHandler method start.

@POST
@Path("/previews")
public void start(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId) throws Exception {
    NamespaceId namespace = new NamespaceId(namespaceId);
    AppRequest appRequest;
    try (Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8)) {
        appRequest = GSON.fromJson(reader, AppRequest.class);
    } catch (JsonSyntaxException e) {
        throw new BadRequestException("Request body is invalid json: " + e.getMessage());
    }
    responder.sendString(HttpResponseStatus.OK, GSON.toJson(previewManager.start(namespace, appRequest)));
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStreamReader(java.io.InputStreamReader) LogReader(co.cask.cdap.logging.read.LogReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BadRequestException(co.cask.cdap.common.BadRequestException) NamespaceId(co.cask.cdap.proto.id.NamespaceId) ChannelBufferInputStream(org.jboss.netty.buffer.ChannelBufferInputStream) AppRequest(co.cask.cdap.proto.artifact.AppRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 67 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class WorkflowStatsSLAHttpHandler method workflowRunDetail.

/**
   * The endpoint returns a list of workflow metrics based on the workflow run and a surrounding number of runs
   * of the workflow that are spaced apart by a time interval from each other.
   *
   * @param request The request
   * @param responder The responder
   * @param namespaceId The namespace the application is in
   * @param appId The application the workflow is in
   * @param workflowId The workflow that needs to have it stats shown
   * @param runId The run id of the Workflow that the user wants to see
   * @param limit The number of the records that the user wants to compare against on either side of the run
   * @param interval The timeInterval with which the user wants to space out the runs
   */
@GET
@Path("apps/{app-id}/workflows/{workflow-id}/runs/{run-id}/statistics")
public void workflowRunDetail(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("app-id") String appId, @PathParam("workflow-id") String workflowId, @PathParam("run-id") String runId, @QueryParam("limit") @DefaultValue("10") int limit, @QueryParam("interval") @DefaultValue("10s") String interval) throws Exception {
    if (limit <= 0) {
        throw new BadRequestException("Limit has to be greater than 0. Entered value was : " + limit);
    }
    long timeInterval;
    try {
        timeInterval = TimeMathParser.resolutionInSeconds(interval);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Interval is specified with invalid time unit. It should be specified with one" + " of the 'ms', 's', 'm', 'h', 'd' units. Entered value was : " + interval);
    }
    if (timeInterval <= 0) {
        throw new BadRequestException("Interval should be greater than 0 and should be specified with one of the 'ms'," + " 's', 'm', 'h', 'd' units. Entered value was : " + interval);
    }
    WorkflowId workflow = new WorkflowId(namespaceId, appId, workflowId);
    Collection<WorkflowDataset.WorkflowRunRecord> workflowRunRecords = store.retrieveSpacedRecords(workflow, runId, limit, timeInterval);
    List<WorkflowRunMetrics> workflowRunMetricsList = new ArrayList<>();
    Map<String, Long> startTimes = new HashMap<>();
    for (WorkflowDataset.WorkflowRunRecord workflowRunRecord : workflowRunRecords) {
        workflowRunMetricsList.add(getDetailedRecord(workflow, workflowRunRecord.getWorkflowRunId()));
        startTimes.put(workflowRunRecord.getWorkflowRunId(), RunIds.getTime(RunIds.fromString(workflowRunRecord.getWorkflowRunId()), TimeUnit.SECONDS));
    }
    Collection<WorkflowStatsComparison.ProgramNodes> formattedStatisticsMap = format(workflowRunMetricsList);
    responder.sendJson(HttpResponseStatus.OK, new WorkflowStatsComparison(startTimes, formattedStatisticsMap));
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) WorkflowId(co.cask.cdap.proto.id.WorkflowId) WorkflowStatsComparison(co.cask.cdap.proto.WorkflowStatsComparison) BadRequestException(co.cask.cdap.common.BadRequestException) WorkflowDataset(co.cask.cdap.internal.app.store.WorkflowDataset) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 68 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class AbstractRemoteSystemOpsHandler method deserializeNext.

@Nullable
<T> T deserializeNext(Iterator<MethodArgument> arguments, @Nullable Type typeOfT) throws ClassNotFoundException, BadRequestException {
    if (!arguments.hasNext()) {
        throw new BadRequestException("Expected additional elements.");
    }
    MethodArgument argument = arguments.next();
    if (argument == null) {
        return null;
    }
    JsonElement value = argument.getValue();
    if (value == null) {
        return null;
    }
    if (typeOfT != null) {
        return GSON.fromJson(value, typeOfT);
    }
    return GSON.<T>fromJson(value, Class.forName(argument.getType()));
}
Also used : MethodArgument(co.cask.cdap.common.internal.remote.MethodArgument) JsonElement(com.google.gson.JsonElement) BadRequestException(co.cask.cdap.common.BadRequestException) Nullable(javax.annotation.Nullable)

Example 69 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class ProgramLifecycleService method findRuntimeInfo.

private List<ProgramRuntimeService.RuntimeInfo> findRuntimeInfo(ProgramId programId, @Nullable String runId) throws BadRequestException {
    if (runId != null) {
        RunId run;
        try {
            run = RunIds.fromString(runId);
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("Error parsing run-id.", e);
        }
        ProgramRuntimeService.RuntimeInfo runtimeInfo = runtimeService.lookup(programId, run);
        return runtimeInfo == null ? Collections.<RuntimeInfo>emptyList() : Collections.singletonList(runtimeInfo);
    }
    return new ArrayList<>(runtimeService.list(programId).values());
}
Also used : ArrayList(java.util.ArrayList) BadRequestException(co.cask.cdap.common.BadRequestException) RuntimeInfo(co.cask.cdap.app.runtime.ProgramRuntimeService.RuntimeInfo) RunId(org.apache.twill.api.RunId) ProgramRunId(co.cask.cdap.proto.id.ProgramRunId) ProgramRuntimeService(co.cask.cdap.app.runtime.ProgramRuntimeService)

Example 70 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class DatasetAdminService method createOrUpdate.

/**
   * Configures and creates a Dataset
   *
   * @param datasetInstanceId dataset instance to be created
   * @param typeMeta type meta for the dataset
   * @param props dataset instance properties
   * @param existing if dataset already exists (in case of update), the existing properties
   * @return dataset specification
   */
public DatasetSpecification createOrUpdate(final DatasetId datasetInstanceId, final DatasetTypeMeta typeMeta, final DatasetProperties props, @Nullable final DatasetSpecification existing) throws Exception {
    if (existing == null) {
        LOG.info("Creating dataset instance {}, type meta: {}", datasetInstanceId, typeMeta);
    } else {
        LOG.info("Updating dataset instance {}, type meta: {}, existing: {}", datasetInstanceId, typeMeta, existing);
    }
    try (DatasetClassLoaderProvider classLoaderProvider = new DirectoryClassLoaderProvider(cConf, locationFactory)) {
        final DatasetContext context = DatasetContext.from(datasetInstanceId.getNamespace());
        UserGroupInformation ugi = getUgiForDataset(impersonator, datasetInstanceId);
        final DatasetType type = ImpersonationUtils.doAs(ugi, new Callable<DatasetType>() {

            @Override
            public DatasetType call() throws Exception {
                DatasetType type = dsFramework.getDatasetType(typeMeta, null, classLoaderProvider);
                if (type == null) {
                    throw new BadRequestException(String.format("Cannot instantiate dataset type using provided type meta: %s", typeMeta));
                }
                return type;
            }
        });
        DatasetSpecification spec = ImpersonationUtils.doAs(ugi, new Callable<DatasetSpecification>() {

            @Override
            public DatasetSpecification call() throws Exception {
                DatasetSpecification spec = existing == null ? type.configure(datasetInstanceId.getEntityName(), props) : type.reconfigure(datasetInstanceId.getEntityName(), props, existing);
                DatasetAdmin admin = type.getAdmin(context, spec);
                if (existing != null) {
                    if (admin instanceof Updatable) {
                        ((Updatable) admin).update(existing);
                    } else {
                        admin.upgrade();
                    }
                } else {
                    admin.create();
                }
                return spec;
            }
        });
        // Writing system metadata should be done without impersonation since user may not have access to system tables.
        writeSystemMetadata(datasetInstanceId, spec, props, typeMeta, type, context, existing != null, ugi);
        return spec;
    } catch (Exception e) {
        if (e instanceof IncompatibleUpdateException) {
            // this is expected to happen if user provides bad update properties, so we log this as debug
            LOG.debug("Incompatible update for dataset '{}'", datasetInstanceId, e);
        } else {
            LOG.error("Error {} dataset '{}': {}", existing == null ? "creating" : "updating", datasetInstanceId, e.getMessage(), e);
        }
        throw e;
    }
}
Also used : DatasetSpecification(co.cask.cdap.api.dataset.DatasetSpecification) DatasetAdmin(co.cask.cdap.api.dataset.DatasetAdmin) DatasetType(co.cask.cdap.data2.datafabric.dataset.DatasetType) IncompatibleUpdateException(co.cask.cdap.api.dataset.IncompatibleUpdateException) DatasetManagementException(co.cask.cdap.api.dataset.DatasetManagementException) IOException(java.io.IOException) NotFoundException(co.cask.cdap.common.NotFoundException) BadRequestException(co.cask.cdap.common.BadRequestException) DirectoryClassLoaderProvider(co.cask.cdap.data2.datafabric.dataset.type.DirectoryClassLoaderProvider) Updatable(co.cask.cdap.api.dataset.Updatable) BadRequestException(co.cask.cdap.common.BadRequestException) DatasetClassLoaderProvider(co.cask.cdap.data2.datafabric.dataset.type.DatasetClassLoaderProvider) DatasetContext(co.cask.cdap.api.dataset.DatasetContext) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) IncompatibleUpdateException(co.cask.cdap.api.dataset.IncompatibleUpdateException)

Aggregations

BadRequestException (co.cask.cdap.common.BadRequestException)82 Path (javax.ws.rs.Path)29 NotFoundException (co.cask.cdap.common.NotFoundException)25 HttpResponse (co.cask.common.http.HttpResponse)17 JsonSyntaxException (com.google.gson.JsonSyntaxException)17 URL (java.net.URL)17 POST (javax.ws.rs.POST)17 NamespaceId (co.cask.cdap.proto.id.NamespaceId)16 IOException (java.io.IOException)15 ChannelBufferInputStream (org.jboss.netty.buffer.ChannelBufferInputStream)13 AuditPolicy (co.cask.cdap.common.security.AuditPolicy)12 HttpRequest (co.cask.common.http.HttpRequest)12 InputStreamReader (java.io.InputStreamReader)11 Reader (java.io.Reader)11 NamespaceNotFoundException (co.cask.cdap.common.NamespaceNotFoundException)9 ApplicationId (co.cask.cdap.proto.id.ApplicationId)8 ArtifactNotFoundException (co.cask.cdap.common.ArtifactNotFoundException)7 ProgramType (co.cask.cdap.proto.ProgramType)7 ProgramId (co.cask.cdap.proto.id.ProgramId)6 Test (org.junit.Test)6