public String objectAsJson(Object value) throws BankException {
   try {
     return mObjectMapper.writeValueAsString(value);
   } catch (JsonProcessingException e) {
     throw new BankException(e.getMessage(), e);
   }
 }
 public static String tagsToJson(ArrayList<Tag> tags) throws CloudFormationException {
   try {
     return mapper.writeValueAsString(tags == null ? Lists.<Tag>newArrayList() : tags);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
 public static String conditionMapToJson(Map<String, Boolean> conditionMap)
     throws CloudFormationException {
   try {
     return mapper.writeValueAsString(
         conditionMap == null ? Maps.<String, Boolean>newLinkedHashMap() : conditionMap);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
 public static String parametersToJson(ArrayList<StackEntity.Parameter> parameters)
     throws CloudFormationException {
   try {
     return mapper.writeValueAsString(
         parameters == null ? Lists.<StackEntity.Parameter>newArrayList() : parameters);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
 public static String notificationARNsToJson(ArrayList<String> notificationARNs)
     throws CloudFormationException {
   try {
     return mapper.writeValueAsString(
         notificationARNs == null ? Lists.<String>newArrayList() : notificationARNs);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
 public static String outputsToJson(ArrayList<StackEntity.Output> outputs)
     throws CloudFormationException {
   try {
     return mapper.writeValueAsString(
         outputs == null ? Lists.<StackEntity.Output>newArrayList() : outputs);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
 @Override
 public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
     throws SQLException {
   try {
     ps.setString(i, objectMapper.writeValueAsString(parameter));
   } catch (JsonProcessingException e) {
     logger.error(e.getMessage(), e);
   }
 }
Beispiel #8
0
 /**
  * Print JsonNode using default pretty printer.
  *
  * @param json JSON node to print
  */
 @java.lang.SuppressWarnings("squid:S1148")
 private void printJson(JsonNode json) {
   try {
     print("%s", mapper().writerWithDefaultPrettyPrinter().writeValueAsString(json));
   } catch (JsonProcessingException e) {
     StringWriter sw = new StringWriter();
     e.printStackTrace(new PrintWriter(sw));
     print("[ERROR] %s\n%s", e.getMessage(), sw.toString());
   }
 }
 public static String pseudoParameterMapToJson(Map<String, String> pseudoParameterMap)
     throws CloudFormationException {
   try {
     return mapper.writeValueAsString(
         pseudoParameterMap == null
             ? Maps.<String, String>newLinkedHashMap()
             : pseudoParameterMap);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
  private void getAutoGeneratedRules(
      Metadata metadata, Condition condition, Condition parentCondition, List<Rule> rules) {
    Set<String> tags = condition.getConditionType().getMetadata().getTags();
    if (tags.contains("eventCondition") && !tags.contains("profileCondition")) {
      try {
        Map<String, Object> m = new HashMap<>(3);
        m.put("scope", metadata.getScope());
        m.put("condition", condition);
        m.put("numberOfDays", parentCondition.getParameter("numberOfDays"));
        String key = CustomObjectMapper.getObjectMapper().writeValueAsString(m);
        key = "eventTriggered" + getMD5(key);
        parentCondition.setParameter("generatedPropertyKey", key);
        Rule rule = rulesService.getRule(key);
        if (rule == null) {
          rule =
              new Rule(
                  new Metadata(
                      metadata.getScope(),
                      key,
                      "Auto generated rule for " + metadata.getName(),
                      ""));
          rule.setCondition(condition);
          rule.getMetadata().setHidden(true);
          final Action action = new Action();
          action.setActionType(definitionsService.getActionType("setEventOccurenceCountAction"));
          action.setParameter("pastEventCondition", parentCondition);

          rule.setActions(Arrays.asList(action));
          rule.setLinkedItems(Arrays.asList(metadata.getId()));
          rules.add(rule);

          updateExistingProfilesForPastEventCondition(condition, parentCondition);
        } else {
          rule.getLinkedItems().add(metadata.getId());
          rules.add(rule);
        }
      } catch (JsonProcessingException e) {
        logger.error(e.getMessage(), e);
      }
    } else {
      Collection<Object> values = new ArrayList<>(condition.getParameterValues().values());
      for (Object parameterValue : values) {
        if (parameterValue instanceof Condition) {
          getAutoGeneratedRules(metadata, (Condition) parameterValue, condition, rules);
        } else if (parameterValue instanceof Collection) {
          for (Object subCondition : (Collection<?>) parameterValue) {
            if (subCondition instanceof Condition) {
              getAutoGeneratedRules(metadata, (Condition) subCondition, condition, rules);
            }
          }
        }
      }
    }
  }
 public static String mappingToJson(Map<String, Map<String, Map<String, String>>> mapping)
     throws CloudFormationException {
   try {
     return mapper.writeValueAsString(
         mapping == null
             ? Maps.<String, Map<String, Map<String, String>>>newLinkedHashMap()
             : mapping);
   } catch (JsonProcessingException e) {
     throw new ValidationErrorException(e.getMessage());
   }
 }
 public static String toJson(Object o) {
   if (o == null) {
     return null;
   }
   try {
     return MAPPER.writeValueAsString(o);
   } catch (JsonProcessingException e) {
     logger.error(e.getMessage(), e);
     return null;
   }
 }
 /**
  * Process a JSON string and handle appropriately.
  *
  * <p>Currently JSON strings in four different forms are handled by this method:
  *
  * <ul>
  *   <li>list requests in the form: <code>{"type":"list","list":"trains"}</code> or <code>
  *       {"list":"trains"}</code> that are passed to the JsonUtil for handling.
  *   <li>individual item state requests in the form: <code>
  *       {"type":"turnout","data":{"name":"LT14"}}</code> that are passed to type-specific
  *       handlers. In addition to the initial response, these requests will initiate "listeners",
  *       which will send updated responses every time the item's state changes.
  *       <ul>
  *         <li>an item's state can be set by adding a <strong>state</strong> node to the
  *             <em>data</em> node: <code>{"type":"turnout","data":{"name":"LT14","state":4}}
  *             </code>
  *         <li>individual types can be created if a <strong>method</strong> node with the value
  *             <em>put</em> is included in message: <code>
  *             {"type":"turnout","method":"put","data":{"name":"LT14"}}</code>. The
  *             <em>method</em> node may be included in the <em>data</em> node: <code>
  *             {"type":"turnout","data":{"name":"LT14","method":"put"}}</code> Note that not all
  *             types support this.
  *       </ul>
  *   <li>a heartbeat in the form <code>{"type":"ping"}</code>. The heartbeat gets a <code>
  *       {"type":"pong"}</code> response.
  *   <li>a sign off in the form: <code>{"type":"goodbye"}</code> to which an identical response is
  *       sent before the connection gets closed.
  * </ul>
  *
  * @param string
  * @throws IOException
  */
 public void onMessage(String string) throws IOException {
   log.debug("Received from client: {}", string);
   try {
     this.onMessage(this.connection.getObjectMapper().readTree(string));
   } catch (JsonProcessingException pe) {
     log.warn("Exception processing \"{}\"\n{}", string, pe.getMessage());
     this.sendErrorMessage(
         500,
         Bundle.getMessage(
             this.connection.getLocale(), "ErrorProcessingJSON", pe.getLocalizedMessage()));
   }
 }
Beispiel #14
0
 @JsonIgnore
 @Override
 public String toJSON() {
   ObjectMapper om = new ObjectMapper();
   String rawJson = null;
   try {
     rawJson = om.writer().writeValueAsString(this);
   } catch (JsonProcessingException e) {
     log.error(e.getMessage(), e);
   }
   return rawJson;
 }
  public void onAuthenticationSuccess(
      HttpServletRequest request, HttpServletResponse response, Authentication authentication)
      throws IOException, ServletException {

    ObjectMapper objectMapper = new ObjectMapper();
    response.setHeader("Content-Type", "application/json;charset=UTF-8");
    try {
      // 登陆成功后返回的信息
      objectMapper.writeValue(response.getOutputStream(), "true");
    } catch (JsonProcessingException ex) {
      throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
    }
  }
 /**
  * Retrieves representation of an instance of edu.gatech.sad.project4.GetStudentResource
  *
  * @return an instance of java.lang.String
  */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 @Path("{id}/{enteredPassword}")
 public Response getJson(
     @PathParam("id") int id, @PathParam("enteredPassword") String enteredPassword) {
   try {
     Administratortable at = iLayer.getAdmin(id);
     boolean loggedIn = at.getPassword().equals(enteredPassword);
     return Response.ok(mapper.writeValueAsString(loggedIn))
         .header("Access-Control-Allow-Origin", "*")
         .build();
   } catch (JsonProcessingException ex) {
     Logger.getLogger(GetProfessorResource.class.getName()).log(Level.SEVERE, null, ex);
     return Response.noContent().type(ex.getMessage()).build();
   }
 }
  /** Override this to place result in non-standard location on document */
  protected ObjectNode getRootDocument(StreamsDatum datum) {

    try {
      String json =
          datum.getDocument() instanceof String
              ? (String) datum.getDocument()
              : mapper.writeValueAsString(datum.getDocument());
      return mapper.readValue(json, ObjectNode.class);
    } catch (JsonProcessingException e) {
      LOGGER.warn(e.getMessage());
      return null;
    } catch (IOException e) {
      LOGGER.warn(e.getMessage());
      return null;
    }
  }
 protected static void logResponseBody(String payload) {
   if (!StringUtils.isEmpty(payload)) {
     ObjectMapper mapper = getObectMapperInstance();
     JsonNode tree;
     try {
       tree = mapper.readTree(payload);
       logger.info("responseBody: " + mapper.writeValueAsString(tree));
     } catch (JsonProcessingException e) {
       // Ignore any Exceptions
       logger.error(e.getMessage());
     } catch (IOException e) {
       // Ignore any Exceptions
       logger.error(e.getMessage());
     }
   }
 }
 /**
  * Returns the API documentation of all annotated resources for purposes of Swagger documentation.
  *
  * @return The resource's documentation
  */
 @GET
 @Path("/swagger.json")
 @Produces(MediaType.APPLICATION_JSON)
 public HttpResponse getSwaggerJSON() {
   Swagger swagger = new Reader(new Swagger()).read(this.getClass());
   if (swagger == null) {
     return new HttpResponse(
         "Swagger API declaration not available!", HttpURLConnection.HTTP_NOT_FOUND);
   }
   try {
     return new HttpResponse(Json.mapper().writeValueAsString(swagger), HttpURLConnection.HTTP_OK);
   } catch (JsonProcessingException e) {
     e.printStackTrace();
     return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
   }
 }
 /**
  * Retrieves representation of an instance of edu.gatech.sad.project4.getAllProfessorsResource
  *
  * @return an instance of java.lang.String
  */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getJson() {
   try {
     List<Professorstable> pList = iLayer.getAllProfessors();
     return Response.ok(mapper.writeValueAsString(pList))
         .header("Access-Control-Allow-Origin", "*")
         .build();
   } catch (JsonProcessingException ex) {
     Logger.getLogger(GetAllProfessorsResource.class.getName()).log(Level.SEVERE, null, ex);
     return Response.noContent()
         .type(ex.getMessage())
         .header("Access-Control-Allow-Origin", "*")
         .build();
   }
 }
 @RequestMapping(
     value = "/catalogo",
     method = RequestMethod.GET,
     headers = {"Accept=application/saho.costospresupuestos.app-1.0+json"})
 @ResponseBody
 public CatalogoResponse catalogo(
     // @RequestParam String formulas
     ) {
   CatalogoResponse catalogoResponse = new CatalogoResponse();
   List<Concepto> lstConcepto = catalogoService.selectConceptos();
   String jsonCatalogo = "";
   try {
     jsonCatalogo = objectMapper.writeValueAsString(lstConcepto);
     catalogoResponse.setCatalogo(jsonCatalogo);
   } catch (JsonProcessingException jsonProcessingException) {
     LOGGER.error(jsonProcessingException.getMessage(), jsonProcessingException);
   }
   return catalogoResponse;
 }
  @Override
  protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
      throws IOException, HttpMessageNotWritableException {

    JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
    JsonGenerator generator =
        this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
    try {
      writePrefix(generator, object);

      Class<?> serializationView = null;
      FilterProvider filters = null;
      Object value = object;
      JavaType javaType = null;
      if (object instanceof MappingJacksonValue) {
        MappingJacksonValue container = (MappingJacksonValue) object;
        value = container.getValue();
        serializationView = container.getSerializationView();
        filters = container.getFilters();
      }
      if (type != null && value != null && TypeUtils.isAssignable(type, value.getClass())) {
        javaType = getJavaType(type, null);
      }
      ObjectWriter objectWriter;
      if (serializationView != null) {
        objectWriter = this.objectMapper.writerWithView(serializationView);
      } else if (filters != null) {
        objectWriter = this.objectMapper.writer(filters);
      } else {
        objectWriter = this.objectMapper.writer();
      }
      if (javaType != null && javaType.isContainerType()) {
        objectWriter = objectWriter.forType(javaType);
      }
      objectWriter.writeValue(generator, value);

      writeSuffix(generator, object);
      generator.flush();

    } catch (JsonProcessingException ex) {
      throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
    }
  }
 protected static void logRequestBody(String payload, String URI, String xpaytoken, String crId) {
   ObjectMapper mapper = getObectMapperInstance();
   JsonNode tree;
   logger.info("URI: " + URI);
   logger.info("X-PAY-TOKEN: " + xpaytoken);
   logger.info("X-CORRELATION-ID: " + crId);
   if (!StringUtils.isEmpty(payload)) {
     try {
       tree = mapper.readTree(payload);
       logger.info("requestBody: " + mapper.writeValueAsString(tree));
     } catch (JsonProcessingException e) {
       // Ignore any Exceptions
       logger.error(e.getMessage());
     } catch (IOException e) {
       // Ignore any Exceptions
       logger.error(e.getMessage());
     }
   }
 }
 private CoverallsResponse parseResponse(final HttpResponse response)
     throws ProcessingException, IOException {
   HttpEntity entity = response.getEntity();
   ContentType contentType = ContentType.getOrDefault(entity);
   InputStreamReader reader = null;
   try {
     reader = new InputStreamReader(entity.getContent(), contentType.getCharset());
     CoverallsResponse cr = objectMapper.readValue(reader, CoverallsResponse.class);
     if (cr.isError()) {
       throw new ProcessingException(getResponseErrorMessage(response, cr.getMessage()));
     }
     return cr;
   } catch (JsonProcessingException ex) {
     throw new ProcessingException(getResponseErrorMessage(response, ex.getMessage()), ex);
   } catch (IOException ex) {
     throw new IOException(getResponseErrorMessage(response, ex.getMessage()), ex);
   } finally {
     IOUtil.close(reader);
   }
 }
  /**
   * Process HTTP request.
   *
   * @param act Action.
   * @param req Http request.
   * @param res Http response.
   */
  private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");

    GridRestCommand cmd = command(req);

    if (cmd == null) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return;
    }

    if (!authChecker.apply(req.getHeader("X-Signature"))) {
      res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      return;
    }

    GridRestResponse cmdRes;

    Map<String, Object> params = parameters(req);

    try {
      GridRestRequest cmdReq = createRequest(cmd, params, req);

      if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq);

      cmdRes = hnd.handle(cmdReq);

      if (cmdRes == null)
        throw new IllegalStateException("Received null result from handler: " + hnd);

      byte[] sesTok = cmdRes.sessionTokenBytes();

      if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok));

      res.setStatus(HttpServletResponse.SC_OK);
    } catch (Throwable e) {
      res.setStatus(HttpServletResponse.SC_OK);

      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage());

      if (e instanceof Error) throw (Error) e;
    }

    String json;

    try {
      json = jsonMapper.writeValueAsString(cmdRes);
    } catch (JsonProcessingException e1) {
      U.error(log, "Failed to convert response to JSON: " + cmdRes, e1);

      GridRestResponse resFailed = new GridRestResponse(STATUS_FAILED, e1.getMessage());

      try {
        json = jsonMapper.writeValueAsString(resFailed);
      } catch (JsonProcessingException e2) {
        json = "{\"successStatus\": \"1\", \"error:\" \"" + e2.getMessage() + "\"}}";
      }
    }

    try {
      if (log.isDebugEnabled()) log.debug("Parsed command response into JSON object: " + json);

      res.getWriter().write(json);

      if (log.isDebugEnabled())
        log.debug(
            "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']');
    } catch (IOException e) {
      U.error(log, "Failed to send HTTP response: " + json, e);
    }
  }
 /* package */ JsonPluginException(JsonProcessingException cause) {
   super(cause.getMessage(), cause);
 }
 @Override
 public Response toResponse(JsonProcessingException exception) {
   ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
   builder.entity("Invalid resource format: " + exception.getMessage());
   return builder.build();
 }
  /**
   * Display the gantt of allocations of the actor.
   *
   * @param id the actor id
   */
  @With(CheckActorExists.class)
  @Dynamic(IMafConstants.ACTOR_VIEW_DYNAMIC_PERMISSION)
  public Result allocation(Long id) {

    // get the actor
    Actor actor = ActorDao.getActorById(id);

    // prepare the data (to order them)
    SortableCollection<DateSortableObject> sortableCollection = new SortableCollection<>();
    for (PortfolioEntryResourcePlanAllocatedActor allocatedActor :
        PortfolioEntryResourcePlanDAO.getPEPlanAllocatedActorAsListByActorAndActive(id, true)) {
      if (allocatedActor.endDate != null) {
        sortableCollection.addObject(
            new DateSortableObject(allocatedActor.endDate, allocatedActor));
      }
    }
    for (TimesheetActivityAllocatedActor allocatedActivity :
        TimesheetDao.getTimesheetActivityAllocatedActorAsListByActor(id, true)) {
      if (allocatedActivity.endDate != null) {
        sortableCollection.addObject(
            new DateSortableObject(allocatedActivity.endDate, allocatedActivity));
      }
    }

    // construct the gantt

    List<SourceItem> items = new ArrayList<SourceItem>();

    for (DateSortableObject dateSortableObject : sortableCollection.getSorted()) {

      if (dateSortableObject.getObject() instanceof PortfolioEntryResourcePlanAllocatedActor) {

        PortfolioEntryResourcePlanAllocatedActor allocatedActor =
            (PortfolioEntryResourcePlanAllocatedActor) dateSortableObject.getObject();

        // get the from date
        Date from = allocatedActor.startDate;

        // get the to date
        Date to = allocatedActor.endDate;

        // get the portfolio entry
        Long portfolioEntryId =
            allocatedActor.portfolioEntryResourcePlan.lifeCycleInstancePlannings.get(0)
                .lifeCycleInstance
                .portfolioEntry
                .id;
        PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId);

        String packageName =
            allocatedActor.portfolioEntryPlanningPackage != null
                ? allocatedActor.portfolioEntryPlanningPackage.getName()
                : "";

        SourceItem item = new SourceItem(portfolioEntry.getName(), packageName);

        String cssClass = null;

        if (from != null) {

          to = JqueryGantt.cleanToDate(from, to);
          cssClass = "";

        } else {

          from = to;
          cssClass = "diamond diamond-";
        }

        if (allocatedActor.isConfirmed) {
          cssClass += "success";
        } else {
          cssClass += "warning";
        }

        SourceDataValue dataValue =
            new SourceDataValue(
                controllers.core.routes.PortfolioEntryPlanningController.resources(
                        portfolioEntry.id)
                    .url(),
                null,
                null,
                null,
                null);

        item.values.add(
            new SourceValue(
                from,
                to,
                "",
                views
                    .html
                    .framework_views
                    .parts
                    .formats
                    .display_number
                    .render(allocatedActor.days, null, false)
                    .body(),
                cssClass,
                dataValue));

        items.add(item);
      }

      if (dateSortableObject.getObject() instanceof TimesheetActivityAllocatedActor) {

        TimesheetActivityAllocatedActor allocatedActivity =
            (TimesheetActivityAllocatedActor) dateSortableObject.getObject();

        // get the from date
        Date from = allocatedActivity.startDate;

        // get the to date
        Date to = allocatedActivity.endDate;

        SourceItem item = new SourceItem(allocatedActivity.timesheetActivity.getName(), "");

        String cssClass = null;

        if (from != null) {

          to = JqueryGantt.cleanToDate(from, to);
          cssClass = "";

        } else {

          from = to;
          cssClass = "diamond diamond-";
        }

        cssClass += "info";

        SourceDataValue dataValue =
            new SourceDataValue(
                controllers.core.routes.ActorController.allocationDetails(actor.id, 0, 0, false)
                    .url(),
                null,
                null,
                null,
                null);

        item.values.add(
            new SourceValue(
                from,
                to,
                "",
                views
                    .html
                    .framework_views
                    .parts
                    .formats
                    .display_number
                    .render(allocatedActivity.days, null, false)
                    .body(),
                cssClass,
                dataValue));

        items.add(item);
      }
    }

    String ganttSource = "";
    try {
      ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
      ganttSource = ow.writeValueAsString(items);
    } catch (JsonProcessingException e) {
      Logger.error(e.getMessage());
    }

    return ok(views.html.core.actor.actor_allocation.render(actor, ganttSource));
  }
  private ChannelFuture handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (request.method() == HttpMethod.OPTIONS) {
      return HttpHelpers.sendPreflightApproval(ctx);
    }

    HttpRequestInfo CurrRequest = new HttpRequestInfo();

    try {
      CurrRequest.init(Info, request, SVID.makeSVID());
    } catch (URISyntaxException e1) {
      return HttpHelpers.sendError(CurrRequest, ApiErrors.HTTP_DECODE_ERROR);
    }

    URI uri = CurrRequest.RequestURI;

    l.debug(new SVLog("Agent HTTP request", CurrRequest));

    if (!request.decoderResult().isSuccess()) {
      return HttpHelpers.sendError(CurrRequest, ApiErrors.HTTP_DECODE_ERROR);
    }

    if (!authenticate(request, (InetSocketAddress) ctx.channel().remoteAddress())) {
      return HttpHelpers.sendError(CurrRequest, ApiErrors.BAD_AUTH);
    }

    String uriPath = uri.getPath();

    if (uriPath.equals(WEBSOCKET_PATH)) {
      String websockUrl = request.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
      WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(websockUrl, null, false);

      Handshaker = wsFactory.newHandshaker(request);
      if (Handshaker == null) {
        return WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
      } else {
        WebsocketConnected = true;
        return Handshaker.handshake(ctx.channel(), request);
      }
    }

    if (uriPath.startsWith("/api/")) {
      // Invoking an API directly over HTTP

      String messageType = uriPath.substring(5);
      String messageBody = null;
      if (request.method() == HttpMethod.POST && request.content() != null) {
        messageBody = request.content().toString(StandardCharsets.UTF_8);
      }

      ByteBuf reply = null;
      try {
        reply = Dispatcher.dispatch(messageType, messageBody);
      } catch (JsonProcessingException e) {
        return HttpHelpers.sendError(CurrRequest, ApiErrors.JSON_ERROR, e.getMessage());
      } catch (SQLException e) {
        return HttpHelpers.sendError(CurrRequest, ApiErrors.DB_ERROR, e.getMessage());
      } catch (JsonApiException e) {
        return HttpHelpers.sendErrorJson(CurrRequest, e.Error, e.HttpStatus);
      } catch (Exception e) {
        return HttpHelpers.sendError(CurrRequest, ApiErrors.INTERNAL_SERVER_ERROR, e.getMessage());
      }

      HttpResponse response =
          new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, reply);

      if (reply != null) {
        HttpHelpers.setContentTypeHeader(response, "application/json");
        HttpUtil.setContentLength(response, reply.readableBytes());
      }

      response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

      return ctx.writeAndFlush(response);
    }

    return HttpHelpers.sendError(CurrRequest, ApiErrors.NOT_FOUND);
  }