Example usage for io.netty.handler.codec.http HttpResponseStatus CONFLICT

List of usage examples for io.netty.handler.codec.http HttpResponseStatus CONFLICT

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus CONFLICT.

Prototype

HttpResponseStatus CONFLICT

To view the source code for io.netty.handler.codec.http HttpResponseStatus CONFLICT.

Click Source Link

Document

409 Conflict

Usage

From source file:com.mastfrog.acteur.errors.Err.java

License:Open Source License

public static Err conflict(String msg) {
    return new Err(HttpResponseStatus.CONFLICT, msg);
}

From source file:com.mesosphere.mesos.rx.java.test.simulation.MesosServerSimulation.java

License:Apache License

/**
 * Create a {@code MesosServerSimulation} that will use {@code events} as the event stream to return to a
 * a client when {@code isSubscribePredicate} evaluates to {@code true}
 * <p>/*from   ww w .jav a 2  s  .  com*/
 * The simulation server must be started using {@link #start()} before requests can be serviced by the server.
 *
 * @param events               The event stream to be returned by the server upon {@code isSubscribePredicate}
 *                             evaluating to {@code true} For each {@link Event} sent to {@code events}, the event
 *                             will be sent by the server.
 * @param sendCodec            The {@link MessageCodec} to use to encode {@link Event}s sent by the server
 * @param receiveCodec         The {@link MessageCodec} to use to decode {@link Call}s received by the server
 * @param isSubscribePredicate The predicate used to determine if a {@link Call} is a "Subscribe" call
 */
public MesosServerSimulation(@NotNull final Observable<Event> events,
        @NotNull final MessageCodec<Event> sendCodec, @NotNull final MessageCodec<Call> receiveCodec,
        @NotNull final Predicate<Call> isSubscribePredicate) {
    this.callsReceived = Collections.synchronizedList(new ArrayList<>());
    this.started = new AtomicBoolean(false);
    this.eventsCompletedLatch = new CountDownLatch(1);
    this.subscribedLatch = new CountDownLatch(1);
    this.sem = new Semaphore(0);
    this.server = RxNetty.createHttpServer(0, (request, response) -> {
        response.getHeaders().setHeader("Accept", receiveCodec.mediaType());

        if (!"/api/v1/scheduler".equals(request.getUri())) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            response.getHeaders().setHeader("Content-Length", "0");
            return response.close();
        }
        if (!HttpMethod.POST.equals(request.getHttpMethod())
                || !receiveCodec.mediaType().equals(request.getHeaders().getHeader("Content-Type"))
                || request.getHeaders().getContentLength() <= 0) {
            response.setStatus(HttpResponseStatus.BAD_REQUEST);
            response.getHeaders().setHeader("Content-Length", "0");
            return response.close();
        }

        return request.getContent().flatMap(buf -> {
            final ByteBufInputStream in = new ByteBufInputStream(buf);
            final Call call = receiveCodec.decode(in);
            if (callsReceived.add(call)) {
                sem.release();
            }
            LOGGER.debug(RECEIVE_MARKER, "Call: {}", receiveCodec.show(call));
            if (isSubscribePredicate.test(call)) {
                if (subscribedLatch.getCount() == 0) {
                    final String message = "Only one event stream can be open per server";
                    response.setStatus(HttpResponseStatus.CONFLICT);
                    response.getHeaders().set("Content-Type", "test/plain;charset=utf-8");
                    response.writeString(message);
                    return response.close();
                }
                LOGGER.debug("Responding with event stream from source: {}", events);
                response.getHeaders().setTransferEncodingChunked();
                response.getHeaders().set("Content-Type", sendCodec.mediaType());
                response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
                response.getHeaders().add("Pragma", "no-cache");

                final Subject<Void, Void> subject = PublishSubject.create();
                final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
                final Subscription actionSubscription = events
                        .doOnSubscribe(() -> LOGGER.debug("Event stream subscription active"))
                        .doOnNext(e -> LOGGER.debug(SEND_MARKER, "Event: {}", sendCodec.show(e)))
                        .doOnError((t) -> LOGGER.error("Error while creating response", t))
                        .doOnCompleted(() -> {
                            eventsCompletedLatch.countDown();
                            LOGGER.debug("Sending events complete");
                            if (!response.isCloseIssued()) {
                                response.close(true);
                            }
                        }).map(sendCodec::encode).map(RecordIOUtils::createChunk).subscribe(bytes -> {
                            if (!response.getChannel().isOpen()) {
                                subscription.unsubscribe();
                                return;
                            }
                            try {
                                LOGGER.trace(SEND_MARKER, "bytes: {}", Arrays.toString(bytes));
                                response.writeBytesAndFlush(bytes);
                            } catch (Exception e) {
                                subject.onError(e);
                            }
                        });
                subscription.set(actionSubscription);
                subscribedLatch.countDown();
                return subject;
            } else {
                response.setStatus(HttpResponseStatus.ACCEPTED);
                return response.close();
            }
        });
    });
}

From source file:com.mesosphere.mesos.rx.java.test.simulation.MesosServerSimulationScenariosTest.java

License:Apache License

@Test
public void onlyOneSubscriptionPerServer() throws Exception {
    final MesosServerSimulation<String, String> sim = new MesosServerSimulation<>(Observable.just(SUBSCRIBED),
            StringMessageCodec.UTF8_STRING, StringMessageCodec.UTF8_STRING, SUBSCRIBE::equals);
    final int serverPort = sim.start();
    final URI uri = URI.create(String.format("http://localhost:%d/api/v1/scheduler", serverPort));
    final HttpClient<ByteBuf, ByteBuf> httpClient = createClient(uri);
    final HttpClientRequest<ByteBuf> subscribe = createRequest(uri, SUBSCRIBE);

    final Observable<byte[]> observable = httpClient.submit(subscribe).flatMap(response -> {
        assertThat(response.getStatus()).isEqualTo(HttpResponseStatus.OK);
        return response.getContent();
    }).map(MesosServerSimulationScenariosTest::bufToBytes);

    final TestSubscriber<byte[]> testSubscriber = new TestSubscriber<>();
    final AwaitableEventSubscriberDecorator<byte[]> sub = new AwaitableEventSubscriberDecorator<>(
            testSubscriber);/*from   w ww .j  a  va 2s  . c  om*/

    assertThat(sim.getCallsReceived()).hasSize(0);
    assertThat(testSubscriber.getOnNextEvents()).hasSize(0);

    final Subscription subscription = observable.subscribe(sub);

    sim.awaitSubscribeCall();
    final HttpClientResponse<ByteBuf> secondSubscribe = httpClient.submit(subscribe).toBlocking().first();

    assertThat(secondSubscribe.getStatus()).isEqualTo(HttpResponseStatus.CONFLICT);

    sim.awaitSendingEvents();
    sub.awaitEvent();
    final List<byte[]> expected = newArrayList(
            RecordIOUtils.createChunk(StringMessageCodec.UTF8_STRING.encode(SUBSCRIBED)));
    final List<byte[]> actual = testSubscriber.getOnNextEvents();
    assertThat(deepEquals(actual, expected)).isTrue();
    subscription.unsubscribe();
    sim.shutdown();
}

From source file:com.thesoftwarefactory.vertx.web.mvc.ActionResult.java

License:Apache License

public static HttpStatusCodeResult conflict() {
    return new HttpStatusCodeResultImpl(HttpResponseStatus.CONFLICT);
}

From source file:io.apiman.gateway.vertx.api.ApiListener.java

License:Apache License

public void listen(final IEngine engine) {
    // Subscribe to the api
    eb.send(VertxEngineConfig.APIMAN_API_SUBSCRIBE, uuid);

    // register application
    eb.registerHandler(uuid + VertxEngineConfig.APIMAN_API_APPLICATIONS_REGISTER,
            new ApiCatchHandler<String>() {

                @Override//w w w. j  a v a 2 s. c  o m
                protected void handleApi(final Message<String> message) {
                    Application application = Json.decodeValue(message.body(), Application.class);
                    engine.getRegistry().registerApplication(application, new IAsyncResultHandler<Void>() {
                        @Override
                        public void handle(IAsyncResult<Void> result) {
                            if (result.isSuccess()) {
                                // Signal that everything seems OK
                                replyOk(message);
                            } else {
                                Throwable e = result.getError();
                                replyError(message, new GenericError(HttpResponseStatus.NOT_FOUND.code(),
                                        e.getLocalizedMessage(), e));
                            }
                        }
                    });
                    //logger.debug(("registered app " + application.getApplicationId());
                    //logger.debug(("with contract(s): ");

                    // for(Contract c : application.getContracts()) {
                    //     logger.debug(("API KEY = "  + c.getApiKey());
                    // }
                };
            });

    // delete application
    eb.registerHandler(uuid + VertxEngineConfig.APIMAN_API_APPLICATIONS_DELETE,
            new ApiCatchHandler<JsonObject>() {

                @Override
                protected void handleApi(final Message<JsonObject> message) {
                    JsonObject json = message.body();
                    String orgId = json.getString("organizationId"); //$NON-NLS-1$
                    String appId = json.getString("applicationId"); //$NON-NLS-1$
                    String version = json.getString("version"); //$NON-NLS-1$
                    Application app = new Application();
                    app.setOrganizationId(orgId);
                    app.setApplicationId(appId);
                    app.setVersion(version);
                    engine.getRegistry().unregisterApplication(app, new IAsyncResultHandler<Void>() {
                        @Override
                        public void handle(IAsyncResult<Void> result) {
                            if (result.isSuccess()) {
                                replyOk(message);
                            } else {
                                Throwable e = result.getError();
                                replyError(message, new GenericError(HttpResponseStatus.NOT_FOUND.code(),
                                        e.getLocalizedMessage(), e));
                            }
                        }
                    });
                    //logger.debug(("Deleted app");
                };
            });

    // register service
    eb.registerHandler(uuid + VertxEngineConfig.APIMAN_API_SERVICES_REGISTER, new ApiCatchHandler<String>() {

        @Override
        public void handleApi(final Message<String> message) {
            Service service = Json.decodeValue(message.body(), Service.class);
            engine.getRegistry().publishService(service, new IAsyncResultHandler<Void>() {
                @Override
                public void handle(IAsyncResult<Void> result) {
                    if (result.isSuccess()) {
                        replyOk(message);
                    } else {
                        Throwable e = result.getError();
                        replyError(message, new GenericError(HttpResponseStatus.CONFLICT.code(),
                                e.getLocalizedMessage(), e));
                    }
                }
            });
            //logger.debug(("registered service " + service.getEndpointType());
        };
    });

    // retire service
    eb.registerHandler(uuid + VertxEngineConfig.APIMAN_API_SERVICES_DELETE, new ApiCatchHandler<JsonObject>() {

        @Override
        public void handleApi(final Message<JsonObject> message) {
            JsonObject json = message.body();
            String orgId = json.getString("organizationId"); //$NON-NLS-1$
            String svcId = json.getString("serviceId"); //$NON-NLS-1$
            String version = json.getString("version"); //$NON-NLS-1$
            Service service = new Service();
            service.setOrganizationId(orgId);
            service.setServiceId(svcId);
            service.setVersion(version);
            engine.getRegistry().retireService(service, new IAsyncResultHandler<Void>() {
                @Override
                public void handle(IAsyncResult<Void> result) {
                    if (result.isSuccess()) {
                        replyOk(message);
                    } else {
                        Throwable e = result.getError();
                        replyError(message, new GenericError(HttpResponseStatus.NOT_FOUND.code(),
                                e.getLocalizedMessage(), e));
                    }
                }
            });
        };
    });
}

From source file:io.crate.protocols.http.HttpBlobHandler.java

License:Apache License

private void writeToFile(ByteBuf input, boolean last, final boolean continueExpected) throws IOException {
    if (digestBlob == null) {
        throw new IllegalStateException("digestBlob is null in writeToFile");
    }/*  w w w.ja  v a 2  s .c om*/

    RemoteDigestBlob.Status status = digestBlob.addContent(input, last);
    HttpResponseStatus exitStatus = null;
    switch (status) {
    case FULL:
        exitStatus = HttpResponseStatus.CREATED;
        break;
    case PARTIAL:
        // tell the client to continue
        if (continueExpected) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.CONTINUE));
        }
        return;
    case MISMATCH:
        exitStatus = HttpResponseStatus.BAD_REQUEST;
        break;
    case EXISTS:
        exitStatus = HttpResponseStatus.CONFLICT;
        break;
    case FAILED:
        exitStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    default:
        throw new IllegalArgumentException("Unknown status: " + status);
    }

    assert exitStatus != null : "exitStatus should not be null";
    LOGGER.trace("writeToFile exit status http:{} blob: {}", exitStatus, status);
    simpleResponse(exitStatus);
}

From source file:org.jspare.forvertx.web.handling.Handling.java

License:Apache License

/**
 * Conflict.
 */
public void conflict() {

    status(HttpResponseStatus.CONFLICT);
    end();
}

From source file:org.jspare.forvertx.web.handling.Handling.java

License:Apache License

/**
 * Conflict.//from www.j ava 2  s  .  c o m
 *
 * @param object the object
 */
public void conflict(Object object) {

    String content = my(Json.class).toJSON(object);
    status(HttpResponseStatus.CONFLICT);
    contentType("application/json");
    res.setChunked(true);
    res.write(content, StandardCharsets.UTF_8.name());
    end();
}

From source file:org.nosceon.titanite.Response.java

License:Apache License

public static Response conflict() {
    return new Response(HttpResponseStatus.CONFLICT);
}

From source file:org.restexpress.util.HttpSpecificationTest.java

License:Apache License

@Test
public void shouldPassOn409() {
    response.setResponseStatus(HttpResponseStatus.CONFLICT);
    response.setBody("Should be allowed.");
    response.setContentType(ContentType.JSON);
    response.addHeader(HttpHeaders.Names.CONTENT_LENGTH, "15");
    HttpSpecification.enforce(response);
}