Search in sources :

Example 11 with HttpResponder

use of io.cdap.http.HttpResponder in project cdap by caskdata.

the class JsonListResponderTest method testSendForWholeListResponder.

@Test
public void testSendForWholeListResponder() throws IOException {
    HttpResponder responder = Mockito.mock(HttpResponder.class);
    ChunkResponder chunkResponder = Mockito.mock(ChunkResponder.class);
    Mockito.when(responder.sendChunkStart(HttpResponseStatus.OK)).thenReturn(chunkResponder);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Mockito.doAnswer(invocation -> {
        ByteBuffers.writeToStream(invocation.getArgumentAt(0, ByteBuffer.class), byteArrayOutputStream);
        return null;
    }).when(chunkResponder).sendChunk(Mockito.any(ByteBuffer.class));
    JsonWholeListResponder.respond(new Gson(), responder, (jsonListResponder) -> {
        jsonListResponder.send("application");
    });
    JsonParser parser = new JsonParser();
    JsonArray array = (JsonArray) parser.parse(byteArrayOutputStream.toString());
    Assert.assertEquals(array.get(0).getAsString(), "application");
}
Also used : JsonArray(com.google.gson.JsonArray) HttpResponder(io.cdap.http.HttpResponder) Gson(com.google.gson.Gson) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer) ChunkResponder(io.cdap.http.ChunkResponder) JsonParser(com.google.gson.JsonParser) Test(org.junit.Test)

Example 12 with HttpResponder

use of io.cdap.http.HttpResponder in project cdap by caskdata.

the class JsonListResponderTest method testMultipleSendForPaginatedListResponder.

@Test
public void testMultipleSendForPaginatedListResponder() throws IOException {
    HttpResponder responder = Mockito.mock(HttpResponder.class);
    ChunkResponder chunkResponder = Mockito.mock(ChunkResponder.class);
    Mockito.when(responder.sendChunkStart(HttpResponseStatus.OK)).thenReturn(chunkResponder);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Mockito.doAnswer(invocation -> {
        ByteBuffers.writeToStream(invocation.getArgumentAt(0, ByteBuffer.class), byteArrayOutputStream);
        return null;
    }).when(chunkResponder).sendChunk(Mockito.any(ByteBuffer.class));
    JsonPaginatedListResponder.respond(new Gson(), responder, "applications", (jsonListResponder) -> {
        jsonListResponder.send("application0");
        jsonListResponder.send("application1");
        return "nextToken";
    });
    JsonParser parser = new JsonParser();
    JsonObject json = (JsonObject) parser.parse(byteArrayOutputStream.toString());
    Assert.assertEquals(json.get("applications").getAsJsonArray().get(0).getAsString(), "application0");
    Assert.assertEquals(json.get("applications").getAsJsonArray().get(1).getAsString(), "application1");
    Assert.assertEquals(json.get("nextPageToken").getAsString(), "nextToken");
}
Also used : HttpResponder(io.cdap.http.HttpResponder) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer) ChunkResponder(io.cdap.http.ChunkResponder) JsonParser(com.google.gson.JsonParser) Test(org.junit.Test)

Example 13 with HttpResponder

use of io.cdap.http.HttpResponder in project cdap by caskdata.

the class RuntimeServiceRoutingHandler method routeServiceWithBody.

/**
 * Handles PUT and POST calls from program runtime to access CDAP services.
 * It simply verify the request and forward the call to internal CDAP services.
 */
@Path("/services/{service}/**")
@PUT
@POST
public BodyConsumer routeServiceWithBody(HttpRequest request, HttpResponder responder, @PathParam("namespace") String namespace, @PathParam("app") String app, @PathParam("version") String version, @PathParam("program-type") String programType, @PathParam("program") String program, @PathParam("run") String run, @PathParam("service") String service) throws Exception {
    HttpURLConnection urlConn = openConnection(request, namespace, app, version, programType, program, run, service);
    urlConn.setDoOutput(true);
    OutputStream output;
    try {
        output = urlConn.getOutputStream();
    } catch (UnknownServiceException e) {
        throw new BadRequestException(e.getMessage(), e);
    } catch (IOException e) {
        // If fails to get output stream, treat it as service unavailable so that the client can retry
        throw new ServiceUnavailableException(service, e);
    }
    return new BodyConsumer() {

        @Override
        public void chunk(ByteBuf byteBuf, HttpResponder httpResponder) {
            try {
                byteBuf.readBytes(output, byteBuf.readableBytes());
            } catch (IOException e) {
                throw new ServiceUnavailableException(service, e);
            }
        }

        @Override
        public void finished(HttpResponder httpResponder) {
            try {
                output.close();
            } catch (IOException e) {
                throw new ServiceUnavailableException(service, e);
            }
            try {
                ResponseInfo responseInfo = new ResponseInfo(service, urlConn);
                responder.sendContent(HttpResponseStatus.valueOf(responseInfo.getResponseCode()), new RelayBodyProducer(urlConn.getURL(), responseInfo), responseInfo.getHeaders());
            } catch (BadRequestException e) {
                throw new ServiceException(e, HttpResponseStatus.BAD_REQUEST);
            }
        }

        @Override
        public void handleError(Throwable throwable) {
            LOG.warn("Exception raised for call to {}", urlConn.getURL(), throwable);
        }
    };
}
Also used : HttpResponder(io.cdap.http.HttpResponder) UnknownServiceException(java.net.UnknownServiceException) OutputStream(java.io.OutputStream) IOException(java.io.IOException) ServiceUnavailableException(io.cdap.cdap.common.ServiceUnavailableException) ByteBuf(io.netty.buffer.ByteBuf) HttpURLConnection(java.net.HttpURLConnection) UnknownServiceException(java.net.UnknownServiceException) ServiceException(io.cdap.cdap.common.ServiceException) BadRequestException(io.cdap.cdap.common.BadRequestException) BodyConsumer(io.cdap.http.BodyConsumer) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) PUT(javax.ws.rs.PUT)

Example 14 with HttpResponder

use of io.cdap.http.HttpResponder in project cdap by caskdata.

the class RuntimeHandler method writeSparkEventLogs.

/**
 * Handles call for Spark event logs upload.
 */
@Path("/spark-event-logs/{id}")
@POST
public BodyConsumer writeSparkEventLogs(HttpRequest request, HttpResponder responder, @PathParam("namespace") String namespace, @PathParam("app") String app, @PathParam("version") String version, @PathParam("program-type") String programType, @PathParam("program") String program, @PathParam("run") String run, @PathParam("id") String id) throws Exception {
    if (!eventLogsEnabled) {
        throw new UnsupportedOperationException("Spark event logs collection is not enabled");
    }
    if (!MediaType.APPLICATION_OCTET_STREAM.equals(request.headers().get(HttpHeaderNames.CONTENT_TYPE))) {
        throw new BadRequestException("Only application/octet-stream content type is supported.");
    }
    ApplicationId appId = new NamespaceId(namespace).app(app, version);
    ProgramRunId programRunId = new ProgramRunId(appId, ProgramType.valueOfCategoryName(programType, BadRequestException::new), program, run);
    requestValidator.getProgramRunStatus(programRunId, request);
    Location location = eventLogsBaseLocation.append(String.format("%s-%s-%s-%s-%s", namespace, app, program, run, id));
    if (location.exists()) {
        LOG.debug("Deleting event logs location {} for program run {}", location, programRunId);
        location.delete(true);
    }
    OutputStream os = location.getOutputStream();
    return new BodyConsumer() {

        @Override
        public void chunk(ByteBuf request, HttpResponder responder) {
            try {
                request.readBytes(os, request.readableBytes());
            } catch (IOException e) {
                throw new RuntimeException("Failed to write spark event logs to " + location, e);
            }
        }

        @Override
        public void finished(HttpResponder responder) {
            try {
                os.close();
                responder.sendStatus(HttpResponseStatus.OK);
            } catch (IOException e) {
                throw new RuntimeException("Failed to close spark event logs output stream for " + location, e);
            }
        }

        @Override
        public void handleError(Throwable cause) {
            LOG.error("Failed to write spark event logs for {}", programRunId, cause);
            Closeables.closeQuietly(os);
            try {
                location.delete();
            } catch (IOException e) {
                LOG.error("Failed to delete obsolete event logs location {}", location, e);
            }
        }
    };
}
Also used : HttpResponder(io.cdap.http.HttpResponder) OutputStream(java.io.OutputStream) IOException(java.io.IOException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) BadRequestException(io.cdap.cdap.common.BadRequestException) BodyConsumer(io.cdap.http.BodyConsumer) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) Location(org.apache.twill.filesystem.Location) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 15 with HttpResponder

use of io.cdap.http.HttpResponder in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method doGetSchedules.

private void doGetSchedules(HttpResponder responder, ApplicationId applicationId, @Nullable ProgramId programId, @Nullable String triggerTypeStr, @Nullable String statusStr) throws Exception {
    ApplicationSpecification appSpec = store.getApplication(applicationId);
    if (appSpec == null) {
        throw new NotFoundException(applicationId);
    }
    ProgramScheduleStatus status;
    try {
        status = statusStr == null ? null : ProgramScheduleStatus.valueOf(statusStr);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(String.format("Invalid schedule status '%s'. Must be one of %s.", statusStr, Joiner.on(',').join(ProgramScheduleStatus.values())), e);
    }
    ProtoTrigger.Type triggerType;
    try {
        triggerType = triggerTypeStr == null ? null : ProtoTrigger.Type.valueOfCategoryName(triggerTypeStr);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
    Predicate<ProgramScheduleRecord> predicate = record -> true;
    if (status != null) {
        predicate = predicate.and(record -> record.getMeta().getStatus().equals(status));
    }
    if (triggerType != null) {
        predicate = predicate.and(record -> record.getSchedule().getTrigger().getType().equals(triggerType));
    }
    Collection<ProgramScheduleRecord> schedules;
    if (programId != null) {
        if (!appSpec.getProgramsByType(programId.getType().getApiProgramType()).contains(programId.getProgram())) {
            throw new NotFoundException(programId);
        }
        schedules = programScheduleService.list(programId, predicate);
    } else {
        schedules = programScheduleService.list(applicationId, predicate);
    }
    List<ScheduleDetail> details = schedules.stream().map(ProgramScheduleRecord::toScheduleDetail).collect(Collectors.toList());
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(details, Schedulers.SCHEDULE_DETAILS_TYPE));
}
Also used : BatchProgramSchedule(io.cdap.cdap.proto.BatchProgramSchedule) AuditDetail(io.cdap.cdap.common.security.AuditDetail) RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) BatchProgramResult(io.cdap.cdap.proto.BatchProgramResult) TypeToken(com.google.gson.reflect.TypeToken) MRJobInfoFetcher(io.cdap.cdap.app.mapreduce.MRJobInfoFetcher) MRJobInfo(io.cdap.cdap.proto.MRJobInfo) GsonBuilder(com.google.gson.GsonBuilder) ScheduledRuntime(io.cdap.cdap.proto.ScheduledRuntime) ProgramScheduleStatus(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) ScheduleId(io.cdap.cdap.proto.id.ScheduleId) Map(java.util.Map) ProgramStatus(io.cdap.cdap.proto.ProgramStatus) ScheduleDetail(io.cdap.cdap.proto.ScheduleDetail) EnumSet(java.util.EnumSet) HttpRequest(io.netty.handler.codec.http.HttpRequest) Set(java.util.Set) Reader(java.io.Reader) Constraint(io.cdap.cdap.internal.schedule.constraint.Constraint) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) ProgramScheduleRecord(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleRecord) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StandardCharsets(java.nio.charset.StandardCharsets) Id(io.cdap.cdap.common.id.Id) ApplicationSpecificationAdapter(io.cdap.cdap.internal.app.ApplicationSpecificationAdapter) TriggerCodec(io.cdap.cdap.internal.app.runtime.schedule.trigger.TriggerCodec) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) RunRecord(io.cdap.cdap.proto.RunRecord) GET(javax.ws.rs.GET) SatisfiableTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.SatisfiableTrigger) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) ArrayList(java.util.ArrayList) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) Nullable(javax.annotation.Nullable) Charsets(com.google.common.base.Charsets) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) BatchRunnableInstances(io.cdap.cdap.proto.BatchRunnableInstances) ProgramLiveInfo(io.cdap.cdap.proto.ProgramLiveInfo) ProgramLifecycleService(io.cdap.cdap.internal.app.services.ProgramLifecycleService) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) NotImplementedException(io.cdap.cdap.common.NotImplementedException) ServiceInstances(io.cdap.cdap.proto.ServiceInstances) InputStreamReader(java.io.InputStreamReader) ProgramRuntimeService(io.cdap.cdap.app.runtime.ProgramRuntimeService) Futures(com.google.common.util.concurrent.Futures) ProgramSpecification(io.cdap.cdap.api.ProgramSpecification) Schedulers(io.cdap.cdap.internal.app.runtime.schedule.store.Schedulers) RunCountResult(io.cdap.cdap.proto.RunCountResult) BatchProgramStatus(io.cdap.cdap.proto.BatchProgramStatus) JsonObject(com.google.gson.JsonObject) NamespaceQueryAdmin(io.cdap.cdap.common.namespace.NamespaceQueryAdmin) RandomEndpointStrategy(io.cdap.cdap.common.discovery.RandomEndpointStrategy) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Inject(com.google.inject.Inject) ProgramScheduleService(io.cdap.cdap.scheduler.ProgramScheduleService) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ServiceUnavailableException(io.cdap.cdap.common.ServiceUnavailableException) EndpointStrategy(io.cdap.cdap.common.discovery.EndpointStrategy) QueryParam(javax.ws.rs.QueryParam) Gson(com.google.gson.Gson) DefaultValue(javax.ws.rs.DefaultValue) Objects(com.google.common.base.Objects) ProgramHistory(io.cdap.cdap.proto.ProgramHistory) ConstraintCodec(io.cdap.cdap.internal.app.runtime.schedule.constraint.ConstraintCodec) DELETE(javax.ws.rs.DELETE) Containers(io.cdap.cdap.proto.Containers) Function(com.google.common.base.Function) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) BatchProgramStart(io.cdap.cdap.proto.BatchProgramStart) BatchRunnable(io.cdap.cdap.proto.BatchRunnable) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Collectors(java.util.stream.Collectors) ProgramStatusTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.ProgramStatusTrigger) List(java.util.List) Type(java.lang.reflect.Type) CaseInsensitiveEnumTypeAdapterFactory(io.cdap.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory) Constants(io.cdap.cdap.common.conf.Constants) NotFoundException(io.cdap.cdap.common.NotFoundException) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BatchProgramHistory(io.cdap.cdap.proto.BatchProgramHistory) BatchProgramCount(io.cdap.cdap.proto.BatchProgramCount) HashMap(java.util.HashMap) ProgramType(io.cdap.cdap.proto.ProgramType) JsonElement(com.google.gson.JsonElement) NotRunningProgramLiveInfo(io.cdap.cdap.proto.NotRunningProgramLiveInfo) HashSet(java.util.HashSet) Trigger(io.cdap.cdap.api.schedule.Trigger) BatchProgram(io.cdap.cdap.proto.BatchProgram) Instances(io.cdap.cdap.proto.Instances) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) AbstractAppFabricHttpHandler(io.cdap.cdap.gateway.handlers.util.AbstractAppFabricHttpHandler) ProtoTrigger(io.cdap.cdap.proto.ProtoTrigger) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) HttpResponder(io.cdap.http.HttpResponder) JsonSyntaxException(com.google.gson.JsonSyntaxException) SchedulerException(io.cdap.cdap.internal.app.runtime.schedule.SchedulerException) ProgramId(io.cdap.cdap.proto.id.ProgramId) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramSchedule(io.cdap.cdap.internal.app.runtime.schedule.ProgramSchedule) Store(io.cdap.cdap.app.store.Store) TimeUnit(java.util.concurrent.TimeUnit) ServiceDiscoverable(io.cdap.cdap.common.service.ServiceDiscoverable) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) NotFoundException(io.cdap.cdap.common.NotFoundException) ProgramScheduleStatus(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) ProtoTrigger(io.cdap.cdap.proto.ProtoTrigger) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramScheduleRecord(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleRecord) ScheduleDetail(io.cdap.cdap.proto.ScheduleDetail)

Aggregations

HttpResponder (io.cdap.http.HttpResponder)28 UnauthorizedException (io.cdap.cdap.security.spi.authorization.UnauthorizedException)19 BadRequestException (io.cdap.cdap.common.BadRequestException)14 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)14 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)13 IOException (java.io.IOException)13 Path (javax.ws.rs.Path)13 NamespaceNotFoundException (io.cdap.cdap.common.NamespaceNotFoundException)12 HttpRequest (io.netty.handler.codec.http.HttpRequest)12 POST (javax.ws.rs.POST)12 Test (org.junit.Test)12 Gson (com.google.gson.Gson)11 JsonObject (com.google.gson.JsonObject)10 JsonSyntaxException (com.google.gson.JsonSyntaxException)10 ConflictException (io.cdap.cdap.common.ConflictException)10 NotFoundException (io.cdap.cdap.common.NotFoundException)10 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)10 NotImplementedException (io.cdap.cdap.common.NotImplementedException)9 MonitorHandler (io.cdap.cdap.gateway.handlers.MonitorHandler)9 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)9