Java Code Examples for io.vertx.ext.web.RoutingContext

The following are top voted examples for showing how to use io.vertx.ext.web.RoutingContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: RequestHeaderElementTest.java   View source code 8 votes vote down vote up
@Test
public void getFormattedElement() {
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  AccessLogParam param = new AccessLogParam().setRoutingContext(mockContext);
  HttpServerRequest mockRequest = Mockito.mock(HttpServerRequest.class);
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String testValue = "testValue";
  headers.add(HEADER_IDENTIFIER, testValue);

  Mockito.when(mockContext.request()).thenReturn(mockRequest);
  Mockito.when(mockRequest.headers()).thenReturn(headers);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals(testValue, result);
  assertEquals(ELEMENT.getIdentifier(), HEADER_IDENTIFIER);
}
 
Example 2
Project: vertx-chtijug-2017   File: MyShoppingListVerticle.java   View source code 7 votes vote down vote up
private void addItem(RoutingContext rc) {
    String body = rc.getBodyAsString();
    if (body != null) {
        Item item = Json.decodeValue(body, Item.class);

        if (item.getQuantity() == 0) {
            redis.hdel("my-shopping-list", item.getName(), res -> {
                if (res.failed()) {
                    rc.fail(res.cause());
                } else {
                    getShoppingList(rc);
                }
            });
        } else {
            redis.hset("my-shopping-list", item.getName(), Integer.toString(item.getQuantity()), res -> {
                if (res.failed()) {
                    rc.fail(res.cause());
                } else {
                    getShoppingList(rc);
                }
            });
        }
    } else {
        rc.response().setStatusCode(400).end();
    }
}
 
Example 3
Project: vertx-zero   File: BlockAim.java   View source code 6 votes vote down vote up
@Override
public Handler<RoutingContext> attack(final Event event) {
    return Fn.get(() -> (context) -> Responser.exec(() -> {
        // 1. Build Arguments
        final Object[] arguments = buildArgs(context, event);

        // 2. Method call
        invoke(event, arguments);

        // 3. Resource model building
        final Envelop data = Envelop.ok();

        // 4. Process modal
        Answer.reply(context, data, event);
    }, context, event), event);
}
 
Example 4
Project: DMS   File: APIKeyManageRouter.java   View source code 6 votes vote down vote up
public void handle(RoutingContext ctx) {
    HttpServerResponse response = ctx.response();
    if (userManager.isLogined(ctx)) {
        try {
            String uid = userManager.getUid(userManager.getIdFromSession(ctx));
            JobResult result = requestManager.getApiKeys(uid);
            if (result.isSuccess()) {
                SafeResultSet rs = (SafeResultSet) result.getArgs()[0];
                while (rs.next()) {
                    //
                    //
                    //
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatusCode(500);
        }
    } else {
        response.setStatusCode(400);
    }
    response.end();
    response.close();
}
 
Example 5
Project: vertx-chtijug-2017   File: MyShoppingVerticle.java   View source code 6 votes vote down vote up
private void addToList(RoutingContext rc) {
    JsonObject json = rc.getBodyAsJson();
    int quantity = json.getInteger("quantity", 1);
    if (quantity <= 0) {
        rc.response().setStatusCode(400);
        return;
    }

    redis.hset(KEY, json.getString("name"), Integer.toString(quantity), r -> {
        if (r.succeeded()) {
            getList(rc);
        } else {
            rc.fail(r.cause());
        }
    });

}
 
Example 6
Project: vertx-zero   File: IpcAim.java   View source code 6 votes vote down vote up
@Override
public Handler<RoutingContext> attack(final Event event) {
    return Fn.get(() -> (context) -> Responser.exec(() -> {
        // 1. Build Arguments
        final Object[] arguments = buildArgs(context, event);

        // 2. Method call
        final Object result = invoke(event, arguments);

        // 3. Resource model building
        final Envelop data = Flower.continuous(context, result);

        // 4. Rpc Client Call to send the data.
        final Future<Envelop> handler = TunnelClient.create(getClass())
                .connect(context.vertx())
                .connect(event)
                .send(data);
        // 5. Reply
        handler.setHandler(res -> Answer.reply(context, res.result()));
    }, context, event), event);
}
 
Example 7
Project: wayf-cloud   File: ResponseWriter.java   View source code 6 votes vote down vote up
public <B> void buildSuccess(RoutingContext routingContext, B body) {
    LOG.debug("Building success message");

    Completable.fromAction(
            () ->
                    routingContext.response()
                            .setStatusCode(200)
                            .putHeader(CONTENT_TYPE_KEY, CONTENT_TYPE_VALUE)
                            .putHeader("Link", buildLinkHeaderValue())
                            .end(body != null ? Json.encodePrettily(body) : StringUtils.EMPTY))
            .subscribeOn(Schedulers.io())
            .subscribe(
                    () -> {}, // Do nothing on success
                    (ex) -> routingContext.fail(ex)
            );
}
 
Example 8
Project: vertx-sfdc-platformevents   File: ApplicationStarter.java   View source code 6 votes vote down vote up
/**
 * Handler for the /api endpoint, listing out routes and loaded verticles
 * 
 * @param ctx
 */
private void rootHandler(final RoutingContext ctx) {
	ctx.response().putHeader(Constants.CONTENT_HEADER, Constants.CONTENT_TYPE_JSON);
	final JsonObject result = new JsonObject().put("RunningSince", Utils.getDateString(this.startDate));
	final JsonObject routeObject = new JsonObject();
	for (final Route r : this.router.getRoutes()) {
		final String p = r.getPath();
		if (p != null) {
			routeObject.put(p, String.valueOf(r));
		}
	}
	result.put("Routes", routeObject);
	final JsonArray verticleArray = new JsonArray(this.loadedVerticles);
	result.put("Verticles", verticleArray);
	ctx.response().end(result.encodePrettily());
}
 
Example 9
Project: DMS   File: AddSurveyQuestion.java   View source code 6 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
	if(!AdminManager.isAdmin(ctx)) {
		ctx.response().setStatusCode(204).end();
		ctx.response().close();
		return;
	}
	
	int surveyNo = Integer.parseInt(ctx.request().getFormAttribute("survey_no"));
	String title = ctx.request().getFormAttribute("title");
	boolean isObjective = Boolean.parseBoolean(ctx.request().getFormAttribute("is_objective"));
	
	if(isObjective) {
		// true면 객관식, false면 주관식
		String objects = ctx.request().getFormAttribute("objects");
		
		DB.executeUpdate("INSERT INTO survey_question(survey_no, title, is_objective, objects) VALUES(?, ?, ?, ?)", surveyNo, title, isObjective, objects);
	} else {
		DB.executeUpdate("INSERT INTO survey_question(survey_no, title, is_objective) VALUES(?, ?, ?)", surveyNo, title, isObjective);
	}
	
	ctx.response().setStatusCode(201).end();
	ctx.response().close();
}
 
Example 10
Project: vertx-zero   File: MediaAnalyzer.java   View source code 6 votes vote down vote up
@Override
public Object[] in(final RoutingContext context,
                   final Event event)
        throws WebException {
    /** Consume mime type matching **/
    final MediaType requestMedia = getMedia(context);
    MediaAtom.accept(event, requestMedia);

    /** Extract definition from method **/
    final List<Epsilon<Object>> epsilons =
            this.income.in(context, event);

    /** Extract value list **/
    return epsilons.stream()
            .map(Epsilon::getValue).toArray();
}
 
Example 11
Project: Daejeon-People   File: Signin.java   View source code 6 votes vote down vote up
private void registerSessionId(RoutingContext ctx, String id) {
	/*
	 * keepLogin 설정에 따라 세션 혹은 쿠키 설정
	 */
	
	String sessionId = getSessionFromId(id);
	// 이미 할당된 session id가 있는지 확인
	
	if(sessionId == null) {
		// 할당된 session id가 없는 경우 create
		sessionId = createSessionId();
	}
	
	// keep_login 설정에 따라 쿠키 또는 세션 put
	SessionUtil.createCookie(ctx, "UserSession", sessionId);
	MySQL.executeUpdate("UPDATE account SET session_id=? WHERE id=?", sessionId, AES256.encrypt(id));
}
 
Example 12
Project: incubator-servicecomb-java-chassis   File: ResponseHeaderElementTest.java   View source code 6 votes vote down vote up
@Test
public void getFormattedElementOnNotFound() {
  AccessLogParam param = new AccessLogParam();
  RoutingContext mockContext = Mockito.mock(RoutingContext.class);
  HttpServerResponse mockResponse = Mockito.mock(HttpServerResponse.class);
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String headerValue = "headerValue";

  param.setRoutingContext(mockContext);
  headers.add("anotherHeader", headerValue);

  Mockito.when(mockContext.response()).thenReturn(mockResponse);
  Mockito.when(mockResponse.headers()).thenReturn(headers);

  String result = ELEMENT.getFormattedElement(param);

  assertEquals("-", result);
}
 
Example 13
Project: dragoman   File: DatasetResource.java   View source code 6 votes vote down vote up
private void writeDatasetContents(
    RoutingContext routingContext, Observable<DataEnvelope> datasetContents) {
  HttpServerResponse httpServerResponse =
      jsonContentType(routingContext.response()).setChunked(true);

  final AtomicBoolean isFirst = new AtomicBoolean(true);
  datasetContents.subscribe(
      (DataEnvelope dataEnvelope) -> {
        if (!isFirst.get()) {
          httpServerResponse.write(",");
        } else {
          isFirst.set(false);
          httpServerResponse.write("[");
        }
        httpServerResponse.write(new JsonObject(dataEnvelope.getPayload()).encodePrettily());
      },
      throwable -> GlobalExceptionHandler.error(routingContext, throwable),
      () -> httpServerResponse.end("]"));
}
 
Example 14
Project: incubator-servicecomb-java-chassis   File: TestVertxRestDispatcher.java   View source code 6 votes vote down vote up
@Test
public void failureHandlerErrorDataWithInvocation(@Mocked RoutingContext context, @Mocked InvocationException e) {
  RestProducerInvocation restProducerInvocation = new RestProducerInvocation();

  ErrorDataDecoderException edde = new ErrorDataDecoderException(e);
  new Expectations() {
    {
      context.get(RestConst.REST_PRODUCER_INVOCATION);
      result = restProducerInvocation;
      context.failure();
      returns(edde, edde);
    }
  };

  Deencapsulation.invoke(dispatcher, "failureHandler", context);

  Assert.assertSame(e, this.throwable);
}
 
Example 15
Project: vertx-guide-for-java-devs   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void pageRenderingHandler(RoutingContext context) {
  String requestedPage = context.request().getParam("page");
  dbService.fetchPage(requestedPage, reply -> {
    if (reply.succeeded()) {

      JsonObject payLoad = reply.result();
      boolean found = payLoad.getBoolean("found");
      String rawContent = payLoad.getString("rawContent", EMPTY_PAGE_MARKDOWN);
      context.put("title", requestedPage);
      context.put("id", payLoad.getInteger("id", -1));
      context.put("newPage", found ? "no" : "yes");
      context.put("rawContent", rawContent);
      context.put("content", Processor.process(rawContent));
      context.put("timestamp", new Date().toString());

      templateEngine.render(context, "templates", "/page.ftl", ar -> {
        if (ar.succeeded()) {
          context.response().putHeader("Content-Type", "text/html");
          context.response().end(ar.result());
        } else {
          context.fail(ar.cause());
        }
      });

    } else {
      context.fail(reply.cause());
    }
  });
}
 
Example 16
Project: vertx-guide-for-java-devs   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void apiGetPage(RoutingContext context) {
  int id = Integer.valueOf(context.request().getParam("id"));
  dbService.fetchPageById(id, reply -> {
    JsonObject response = new JsonObject();
    if (reply.succeeded()) {
      JsonObject dbObject = reply.result();
      if (dbObject.getBoolean("found")) {
        JsonObject payload = new JsonObject()
          .put("name", dbObject.getString("name"))
          .put("id", dbObject.getInteger("id"))
          .put("markdown", dbObject.getString("content"))
          .put("html", Processor.process(dbObject.getString("content")));
        response
          .put("success", true)
          .put("page", payload);
        context.response().setStatusCode(200);
      } else {
        context.response().setStatusCode(404);
        response
          .put("success", false)
          .put("error", "There is no page with ID " + id);
      }
    } else {
      response
        .put("success", false)
        .put("error", reply.cause().getMessage());
      context.response().setStatusCode(500);
    }
    context.response().putHeader("Content-Type", "application/json");
    context.response().end(response.encode());
  });
}
 
Example 17
Project: vertx-guide-for-java-devs   File: MainVerticle.java   View source code 5 votes vote down vote up
private void pageUpdateHandler(RoutingContext context) {
  String id = context.request().getParam("id");   // <1>
  String title = context.request().getParam("title");
  String markdown = context.request().getParam("markdown");
  boolean newPage = "yes".equals(context.request().getParam("newPage"));  // <2>

  dbClient.getConnection(car -> {
    if (car.succeeded()) {
      SQLConnection connection = car.result();
      String sql = newPage ? SQL_CREATE_PAGE : SQL_SAVE_PAGE;
      JsonArray params = new JsonArray();   // <3>
      if (newPage) {
        params.add(title).add(markdown);
      } else {
        params.add(markdown).add(id);
      }
      connection.updateWithParams(sql, params, res -> {   // <4>
        connection.close();
        if (res.succeeded()) {
          context.response().setStatusCode(303);    // <5>
          context.response().putHeader("Location", "/wiki/" + title);
          context.response().end();
        } else {
          context.fail(res.cause());
        }
      });
    } else {
      context.fail(car.cause());
    }
  });
}
 
Example 18
Project: vertx-guide-for-java-devs   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void pageCreateHandler(RoutingContext context) {
  String pageName = context.request().getParam("name");
  String location = "/wiki/" + pageName;
  if (pageName == null || pageName.isEmpty()) {
    location = "/";
  }
  context.response().setStatusCode(303);
  context.response().putHeader("Location", location);
  context.response().end();
}
 
Example 19
Project: wayf-cloud   File: RequestReader.java   View source code 5 votes vote down vote up
private static <B> B _readRequestBody(RoutingContext routingContext, Class<B> bodyClass) {
    LOG.debug("Reading request body of type [{}] from request", bodyClass);

    try {
        return Json.prettyMapper.readValue(routingContext.getBodyAsString(), bodyClass);
    } catch (IOException e) {
        throw new ServiceException(HttpStatus.SC_BAD_REQUEST, "Could not read request body", e);
    }
}
 
Example 20
Project: simulacron   File: EndpointManager.java   View source code 5 votes vote down vote up
/**
 * This is an async callback that will be invoked in order to accept connections to a particular
 * scope or all the clusters if the scope is not set. The scope will be specified in a similar way
 * to other requests, adding /clusterIdOrName/datacenterIdOrName/nodeIdOrName to the path. It will
 * usually be called after {@link #rejectConnections(RoutingContext)}.
 *
 * <p>Example Supported HTTP Requests
 *
 * <p>PUT http://iphere:porthere/connections/listener/clusterIdOrName/datacenterIdOrName/ this
 * will accept again the connections to the datacenter represented by datacenterIdOrName inside
 * the cluster represented by clusterIdOrName if {@link #rejectConnections(RoutingContext)} had
 * been called on this nodes before, otherwise, nothing will be done
 *
 * @param context RoutingContext provided by vertx
 */
private void acceptConnections(RoutingContext context) {
  context
      .request()
      .bodyHandler(
          totalBuffer -> {
            try {
              Scope scope = HttpUtils.getScope(context, server);
              if (scope == null) {
                return;
              }
              CompletionStage<Void> future =
                  HttpUtils.find(server, scope).acceptConnectionsAsync();
              future.whenComplete(
                  (completedCluster, ex) -> {
                    if (ex == null) {
                      context
                          .request()
                          .response()
                          .putHeader("content-type", "application/json")
                          .setStatusCode(200)
                          .end();
                    } else {
                      handleError(new ErrorMessage(ex.getMessage(), 400), context);
                    }
                  });
            } catch (Exception e) {
              e.printStackTrace();
              logger.error("Error ocurred while processing closeConnections request");
              handleError(new ErrorMessage(e.getMessage(), 400), context);
            }
          });
}
 
Example 21
Project: Daejeon-People   File: SessionUtil.java   View source code 5 votes vote down vote up
public static void removeSession(RoutingContext ctx, String key) {
	if(ctx.session().get(key) != null) {
		ctx.session().remove(key);
	}
	
	if(ctx.getCookie(key) != null) {
		ctx.getCookie(key).setMaxAge(0);
	}
}
 
Example 22
Project: DMS   File: UploadNotice.java   View source code 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {

	if (!Guardian.isAdmin(ctx)) {
		ctx.response().setStatusCode(400).end();
		ctx.response().close();
		return;
	}

	DataBase database = DataBase.getInstance();
	
	String title = ctx.request().getParam("title");
	String content = ctx.request().getParam("content");
	
	if(!Guardian.checkParameters(title, content)) {
           ctx.response().setStatusCode(400).end();
           ctx.response().close();
       	return;
       }
	
	try {
		database.executeUpdate("INSERT INTO notice(title, content) VALUES('", title, "', '", content, "')");
		
		ctx.response().setStatusCode(201).end();
		ctx.response().close();
	} catch(SQLException e) {
		ctx.response().setStatusCode(500).end();
		ctx.response().close();
	}
}
 
Example 23
Project: irked   File: Controller.java   View source code 5 votes vote down vote up
/**
 * Helper method for {@link Router} to create the appropriate request
 * handler for Vert.X
 * @param field routing endpoint handler exposed by this controller
 * @return a handler that takes a Vert.x original routing context and
 *  wraps it in a local request context before delegating to the routing endpoint
 */
@SuppressWarnings("unchecked")
Handler<RoutingContext> getHandler(Field field) {
	try {
		field.setAccessible(true);
		if (Handler.class.isAssignableFrom(field.getType()))
			return (Handler<RoutingContext>)field.get(this);
		return null;
	} catch (IllegalArgumentException | IllegalAccessException e) {
		// shouldn't happen
		throw new RuntimeException("Error accessing field " + field + ": " + e, e);
	}
}
 
Example 24
Project: vertx-chtijug-2017   File: MyShoppingListVerticle.java   View source code 5 votes vote down vote up
private void getShoppingList(RoutingContext rc) {
    redis.hgetall("my-shopping-list", res -> {
        if (res.failed()) {
            rc.fail(res.cause());
        } else {
            rc.response().end(res.result().put("served-by", System.getenv("HOSTNAME")).encode());
        }
    });
}
 
Example 25
Project: vertx-guide-for-java-devs_chinese   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void handleSimpleDbReply(RoutingContext context, AsyncResult<Void> reply) {
  if (reply.succeeded()) {
    context.response().setStatusCode(200);
    context.response().putHeader("Content-Type", "application/json");
    context.response().end(new JsonObject().put("success", true).encode());
  } else {
    context.response().setStatusCode(500);
    context.response().putHeader("Content-Type", "application/json");
    context.response().end(new JsonObject()
      .put("success", false)
      .put("error", reply.cause().getMessage()).encode());
  }
}
 
Example 26
Project: Daejeon-People   File: AttractionsListInquiry.java   View source code 5 votes vote down vote up
public static JSONArray inquireBasedKeyword(RoutingContext ctx, String keyword) {
	// 검색 + 정렬
	int sortType = Integer.parseInt(ctx.request().getParam("sort_type"));
	int page = Integer.parseInt(ctx.request().getParam("page"));
	
	String query = "SELECT * FROM attractions_basic WHERE title LIKE '%" + keyword + "%' ORDER BY ? LIMIT " + (page - 1) * numOfRows + ", " + page * numOfRows;

	ResultSet rs = null;
	switch (sortType) {
	case 1:
		// 조회순
		rs = MySQL.executeQuery(query.replaceFirst("\\?", "views_count DESC"));
		break;
	case 2:
		// 위시리스트 많은 순
		rs = MySQL.executeQuery(query.replaceFirst("\\?", "wish_count DESC"));
		break;
	case 3:
		// 거리순
		double x = Double.parseDouble(ctx.request().getParam("x"));
		double y = Double.parseDouble(ctx.request().getParam("y"));
		// 클라이언트 좌표값

		rs = MySQL.executeQuery(query.split(" ORDER BY")[0]);
		// contentTypeId에 해당하는 데이터 전체

		rs = distanceBasedInquiry(rs, page, x, y);
		// 거리기반 조회

		break;
	}
	
	return extractDatas(ctx, rs);
}
 
Example 27
Project: DMS   File: UploadBug.java   View source code 5 votes vote down vote up
public void handle(RoutingContext context) {
	String title = context.request().getParam("title");
	String content = context.request().getParam("content");

	if (!Guardian.checkParameters(title, content)) {
		context.response().setStatusCode(400).end();
		context.response().close();
		return;
	}

	DB.executeUpdate("INSERT INTO bug_report(title, content) VALUES(?, ?)", title, content);

	context.response().setStatusCode(201).end();
	context.response().close();
}
 
Example 28
Project: vertx-guide-for-java-devs_chinese   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void loginHandler(RoutingContext context) {
  context.put("title", "Login");
  templateEngine.render(context, "templates", "/login.ftl", ar -> {
    if (ar.succeeded()) {
      context.response().putHeader("Content-Type", "text/html");
      context.response().end(ar.result());
    } else {
      context.fail(ar.cause());
    }
  });
}
 
Example 29
Project: vertx-guide-for-java-devs   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void handleSimpleDbReply(RoutingContext context, AsyncResult<Void> reply) {
  if (reply.succeeded()) {
    context.response().setStatusCode(200);
    context.response().putHeader("Content-Type", "application/json");
    context.response().end(new JsonObject().put("success", true).encode());
  } else {
    context.response().setStatusCode(500);
    context.response().putHeader("Content-Type", "application/json");
    context.response().end(new JsonObject()
      .put("success", false)
      .put("error", reply.cause().getMessage()).encode());
  }
}
 
Example 30
Project: incubator-servicecomb-java-chassis   File: EdgeDispatcher.java   View source code 5 votes vote down vote up
protected void onRequest(RoutingContext context) {
  Map<String, String> pathParams = context.pathParams();
  String microserviceName = pathParams.get("param0");
  String pathVersion = pathParams.get("param1");
  String path = context.request().path().substring(4);

  EdgeInvocation edgeInvocation = new EdgeInvocation();
  edgeInvocation.setVersionRule(versionMapper.getOrCreate(pathVersion).getVersionRule());

  edgeInvocation.init(microserviceName, context, path, httpServerFilters);
  edgeInvocation.edgeInvoke();
}
 
Example 31
Project: vertx-zero   File: JsonResolver.java   View source code 5 votes vote down vote up
@Override
public Epsilon<T> resolve(final RoutingContext context,
                          final Epsilon<T> income)
        throws WebException {
    // Json Resolver
    final String content = context.getBodyAsString();
    final Object result = ZeroSerializer.getValue(income.getArgType(), content);
    if (null != result) {
        income.setValue((T) result);
    }
    return income;
}
 
Example 32
Project: rest.vertx   File: RestRouter.java   View source code 5 votes vote down vote up
private static HttpResponseWriter getWriter(InjectionProvider injectionProvider,
                                            Method method,
                                            RouteDefinition definition,
                                            MediaType acceptHeader,
                                            RoutingContext context) throws ContextException {

	HttpResponseWriter writer = writers.getResponseWriter(injectionProvider, method.getReturnType(), definition, acceptHeader);
	if (writer == null) {
		return null;
	}

	Type writerType = ClassFactory.getGenericType(writer.getClass());
	ClassFactory.checkIfCompatibleTypes(method.getReturnType(),
	                                    writerType,
	                                    definition.toString().trim() + " - Response type: '" +
	                                    method.getReturnType() + "' not matching writer type: '" +
	                                    writerType + "' in: '" + writer.getClass() + "'");

	ContextProviderFactory.injectContext(writer, definition, context); // injects @Context if needed
	return writer;
}
 
Example 33
Project: Daejeon-People   File: Logout.java   View source code 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
	if(UserManager.isLogined(ctx)) {
		logout(ctx);
		ctx.response().setStatusCode(201).end();
		ctx.response().close();
	} else {
		ctx.response().setStatusCode(204).end();
		ctx.response().close();
	}
}
 
Example 34
Project: vertx-guide-for-java-devs   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void apiUpdatePage(RoutingContext context) {
  int id = Integer.valueOf(context.request().getParam("id"));
  JsonObject page = context.getBodyAsJson();
  if (!validateJsonPageDocument(context, page, "markdown")) {
    return;
  }
  dbService.savePage(id, page.getString("markdown"), reply -> {
    handleSimpleDbReply(context, reply);
  });
}
 
Example 35
Project: vertx-zero   File: Flower.java   View source code 5 votes vote down vote up
static <T> Envelop continuous(final RoutingContext context,
                              final T entity) {
    final Envelop envelop = Envelop.success(entity);
    envelop.setHeaders(context.request().headers());
    envelop.setUser(context.user());
    envelop.setSession(context.session());
    return envelop;
}
 
Example 36
Project: DMS   File: SessionUtil.java   View source code 5 votes vote down vote up
public static void registerCookie(RoutingContext context, String key, String sessionKey) {
    Cookie cookie = Cookie.cookie(key, sessionKey);
    String path = "/";
    cookie.setPath(path);
    cookie.setMaxAge(356 * 24 * 60 * 60);
    context.addCookie(cookie);
}
 
Example 37
Project: AlipayWechatPlatform   File: AlipayOauthSubRouter.java   View source code 5 votes vote down vote up
/**
 * 支付宝静默授权的回调方法
 * 由支付宝服务器调用
 *
 * @param rc Vertx的RoutingContext对象
 * @author Leibniz.Hu
 */
private void oauthBaseCallback(RoutingContext rc) {
    HttpServerRequest req = rc.request();
    HttpServerResponse resp = rc.response();
    Integer eid = Integer.parseInt(req.getParam("eid"));
    getAccountAndExecute(resp, eid, aliAcc -> {
        AlipaySystemOauthTokenResponse oauthRes = AliPayApi.getUserId(aliAcc, req);
        oauthSuccessProcess(req, resp, oauthRes, url -> log.info("授权成功,OpenID={},{},准备跳转到{}", oauthRes.getUserId(), oauthRes.getAlipayUserId(), url));
    });
}
 
Example 38
Project: vertx-zero   File: BaseAim.java   View source code 5 votes vote down vote up
/**
 * Template method
 *
 * @param context
 * @param event
 * @return
 */
protected Object[] buildArgs(final RoutingContext context,
                             final Event event) {
    Object[] cached = context.get(ID.PARAMS);
    if (null == cached) {
        cached = this.analyzer.in(context, event);
        context.put(ID.PARAMS, cached);
    }
    // Validation handler has been get the parameters.
    return cached;
}
 
Example 39
Project: DMS   File: LoadGoingoutApplyStatus.java   View source code 5 votes vote down vote up
@Override
public void handle(RoutingContext ctx) {
	EasyJsonObject responseObject = new EasyJsonObject();

       if(UserManager.isLogined(ctx)) {
		try {
			UserManager.getUserInfo(UserManager.getIdFromSession(ctx));
			boolean[] status = UserManager.getOutStatus(UserManager.getIdFromSession(ctx));
			responseObject.put("sat", status[0]);
			responseObject.put("sun", status[1]);
			ctx.response().setStatusCode(200).end(responseObject.toString());
			ctx.response().close();
		} catch (SQLException e) {
			ctx.response().setStatusCode(500).end();
			ctx.response().close();

			Log.l("SQLException");
		}
	}else{
		ctx.response().setStatusCode(400).end();
		ctx.response().close();
		return;
	}
}
 
Example 40
Project: vertx-guide-for-java-devs_chinese   File: HttpServerVerticle.java   View source code 5 votes vote down vote up
private void pageRenderingHandler(RoutingContext context) {
  String requestedPage = context.request().getParam("page");
  dbService.fetchPage(requestedPage, reply -> {
    if (reply.succeeded()) {

      JsonObject payLoad = reply.result();
      boolean found = payLoad.getBoolean("found");
      String rawContent = payLoad.getString("rawContent", EMPTY_PAGE_MARKDOWN);
      context.put("title", requestedPage);
      context.put("id", payLoad.getInteger("id", -1));
      context.put("newPage", found ? "no" : "yes");
      context.put("rawContent", rawContent);
      context.put("content", Processor.process(rawContent));
      context.put("timestamp", new Date().toString());

      templateEngine.render(context, "templates", "/page.ftl", ar -> {
        if (ar.succeeded()) {
          context.response().putHeader("Content-Type", "text/html");
          context.response().end(ar.result());
        } else {
          context.fail(ar.cause());
        }
      });

    } else {
      context.fail(reply.cause());
    }
  });
}