Ejemplo n.º 1
0
  private void onException(Throwable e, Response r, boolean mapped) {
    if (request.isTracingEnabled()) {
      Response.Status s = Response.Status.fromStatusCode(r.getStatus());
      if (s != null) {
        request.trace(
            String.format(
                "mapped exception to response: %s -> %d (%s)",
                ReflectionHelper.objectToString(e), r.getStatus(), s.getReasonPhrase()));
      } else {
        request.trace(
            String.format(
                "mapped exception to response: %s -> %d",
                ReflectionHelper.objectToString(e), r.getStatus()));
      }
    }

    if (!mapped && r.getStatus() >= 500) {
      logException(e, r, Level.SEVERE);
    } else if (LOGGER.isLoggable(Level.FINE)) {
      logException(e, r, Level.FINE);
    }

    setResponse(r);

    this.mappedThrowable = e;

    if (getEntity() != null && getHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE) == null) {
      Object m = request.getProperties().get(HttpMethodRule.CONTENT_TYPE_PROPERTY);
      if (m != null) {
        request.getProperties().remove(HttpMethodRule.CONTENT_TYPE_PROPERTY);
        getHttpHeaders().putSingle(HttpHeaders.CONTENT_TYPE, m);
      }
    }
  }
Ejemplo n.º 2
0
 private void logException(Throwable e, Response r, Level l) {
   Response.Status s = Response.Status.fromStatusCode(r.getStatus());
   if (s != null) {
     LOGGER.log(
         l,
         "Mapped exception to response: " + r.getStatus() + " (" + s.getReasonPhrase() + ")",
         e);
   } else {
     LOGGER.log(l, "Mapped exception to response: " + r.getStatus(), e);
   }
 }
 @POST
 @Path("checkpassword/{username}")
 @PermitAll
 public Response checkpassword(
     @PathParam("username") String username, @FormParam("password") String password) {
   username = userManager.convertToUsernameIfEmailAddress(username);
   Response.Status status = userManager.checkPassword(username, password);
   if (Response.Status.OK == status) {
     return Response.ok().build();
   } else {
     throw new WebApplicationException(status.getStatusCode());
   }
 }
  public boolean removeUserCredentialsForPaaS(String userInstanceUriId, String paaSInstanceUriId)
      throws SOAException {
    String rsUri = getBASE_URI() + "removeUserCredentialsForPaaS";

    WebClient client = WebClient.create(rsUri);
    client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN);

    registerJsonProvider();

    List<Attachment> atts = new LinkedList<Attachment>();

    atts.add(new Attachment("userInstanceUriId", MediaType.TEXT_PLAIN, userInstanceUriId));

    atts.add(new Attachment("paaSInstanceUriId", MediaType.TEXT_PLAIN, paaSInstanceUriId));

    Response response = client.post(new MultipartBody(atts));

    if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.ACCEPTED) {
      try {
        String responseString = IOUtils.readStringFromStream((InputStream) response.getEntity());
        logger.debug("Response Status ACCEPTED - " + responseString);
      } catch (IOException ex) {
        logger.error("Error reading the REST response: " + ex.getMessage());
      }
      return true;
    }
    return false;
  }
Ejemplo n.º 5
0
  /**
   * Send an HTTP message to a worker, producing helpful logging if there was a problem
   *
   * @param uriRequest The request to make
   * @param expectedStatus The expected return status
   * @return true if the method was successfully delivered & the worker gave the expected response
   */
  private boolean tellWorker(HttpUriRequest uriRequest, Response.Status expectedStatus) {
    try {
      HttpResponse response = httpClient.execute(uriRequest);

      if (response.getStatusLine().getStatusCode() != expectedStatus.getStatusCode()) {
        StatusLine statusLine = response.getStatusLine();
        EntityUtils.consume(response.getEntity());
        logger.warn(
            "Problem telling worker <"
                + metadata.getWorkerId()
                + "> "
                + "("
                + uriRequest.getURI()
                + "), "
                + "reason ["
                + statusLine.getStatusCode()
                + ": "
                + statusLine.getReasonPhrase()
                + "]");
        return false;
      }

      return true;
    } catch (IOException e) {
      logger.warn("Unable to communicated with worker " + metadata.toString());
      return false;
    }
  }
  public String storeTurtleUserProfile(String userProfile, String username, String password) {
    String rsUri = getBASE_URI() + "createNewUserAccount";

    WebClient client = WebClient.create(rsUri);
    client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN);

    registerJsonProvider();

    List<Attachment> atts = new LinkedList<Attachment>();

    atts.add(new Attachment("userProfile", MediaType.TEXT_PLAIN, userProfile));

    atts.add(new Attachment("username", MediaType.TEXT_PLAIN, username));

    atts.add(new Attachment("password", MediaType.TEXT_PLAIN, password));

    Response response = client.post(new MultipartBody(atts));
    String userInstanceUriId = null;
    if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.CREATED) {
      try {
        userInstanceUriId = IOUtils.readStringFromStream((InputStream) response.getEntity());
        logger.debug("Response Status CREATED - userInstanceUriId: " + userInstanceUriId);
      } catch (IOException ex) {
        logger.error("Error reading the REST response: " + ex.getMessage());
      }
    }
    return userInstanceUriId;
  }
Ejemplo n.º 7
0
 @Override
 public String getStatusMessage(int status) {
   Status s = javax.ws.rs.core.Response.Status.fromStatusCode(status);
   if (s != null) {
     return s.getReasonPhrase();
   }
   return null;
 }
Ejemplo n.º 8
0
 private static void sendError(HttpServletResponse response, Response.Status status, String error)
     throws IOException {
   response.reset();
   response.setStatus(status.getStatusCode());
   response.setContentType(MediaType.TEXT_PLAIN);
   PrintWriter writer = response.getWriter();
   writer.println(error);
   writer.close();
 }
Ejemplo n.º 9
0
  public NimbusWebException(Response.Status status, String msg, Throwable t) {
    super(msg, t);

    if (status == null) {
      throw new IllegalArgumentException("status may not be null");
    }

    this.status = status.getStatusCode();
    this.requestId = UUID.randomUUID().toString();
  }
  @Test
  public void testPublishDsw() throws Exception {
    DatasourceResource service = new DatasourceResource();
    Mockery mockery = new Mockery();
    final IPlatformImporter mockImporter = mockery.mock(IPlatformImporter.class);
    mp.defineInstance(IPlatformImporter.class, mockImporter);
    mockery.checking(
        new Expectations() {
          {
            oneOf(mockImporter)
                .importFile(
                    with(
                        match(
                            new TypeSafeMatcher<IPlatformImportBundle>() {
                              public boolean matchesSafely(IPlatformImportBundle bundle) {
                                return bundle.isPreserveDsw()
                                    && bundle.getProperty("domain-id").equals("AModel.xmi")
                                    && bundle.getMimeType().equals("text/xmi+xml");
                              }

                              public void describeTo(Description description) {
                                description.appendText("bundle with xmi");
                              }
                            })));
            oneOf(mockImporter)
                .importFile(
                    with(
                        match(
                            new TypeSafeMatcher<IPlatformImportBundle>() {
                              public boolean matchesSafely(IPlatformImportBundle bundle) {
                                return bundle.getProperty("domain-id").equals("AModel")
                                    && bundle
                                        .getMimeType()
                                        .equals("application/vnd.pentaho.mondrian+xml");
                              }

                              public void describeTo(Description description) {
                                description.appendText("bundle with mondrian schema");
                              }
                            })));
          }
        });
    FileInputStream in = new FileInputStream(new File(new File("test-res"), "SampleDataOlap.xmi"));
    try {
      Response resp = service.publishDsw("AModel.xmi", in, true, false);
      Assert.assertEquals(
          Response.Status.Family.SUCCESSFUL,
          Response.Status.fromStatusCode(resp.getStatus()).getFamily());
      mockery.assertIsSatisfied();
    } finally {
      IOUtils.closeQuietly(in);
    }
  }
  public UserPaaSCredentials readUserCredentialsForPaaS(
      String userInstanceUriId, String paaSInstanceUriId) throws SOAException {
    String rsUri = getBASE_URI() + "readUserCredentialsForPaaS";

    WebClient client = WebClient.create(rsUri);
    client.type("multipart/mixed").accept(MediaType.APPLICATION_JSON);

    registerJsonProvider();

    List<Attachment> atts = new LinkedList<Attachment>();

    atts.add(new Attachment("userInstanceUriId", MediaType.TEXT_PLAIN, userInstanceUriId));

    atts.add(new Attachment("paaSInstanceUriId", MediaType.TEXT_PLAIN, paaSInstanceUriId));
    UserPaaSCredentials userPaaSCredentials;
    try {
      userPaaSCredentials = client.post(new MultipartBody(atts), UserPaaSCredentials.class);
    } catch (ServerWebApplicationException cwe) {
      throw new SOAException(Response.Status.fromStatusCode(cwe.getStatus()), cwe.getMessage());
    }

    return userPaaSCredentials;
  }
  @DELETE
  @Path("/{streamRuleId}")
  @Timed
  @ApiOperation(value = "Delete a stream rule")
  @ApiResponses(
      value = {
        @ApiResponse(code = 404, message = "Stream rule not found."),
        @ApiResponse(code = 400, message = "Invalid ObjectId.")
      })
  public Response delete(
      @ApiParam(
              title = "streamid",
              description = "The stream id this new rule belongs to.",
              required = true)
          @PathParam("streamid")
          String streamid,
      @ApiParam(title = "streamRuleId", required = true) @PathParam("streamRuleId")
          String streamRuleId) {
    if (streamRuleId == null || streamRuleId.isEmpty()) {
      LOG.error("Missing streamRuleId. Returning HTTP 400.");
      throw new WebApplicationException(400);
    }
    checkPermission(RestPermissions.STREAMS_EDIT, streamid);

    try {
      StreamRule streamRule = streamRuleService.load(loadObjectId(streamRuleId));
      if (streamRule.getStreamId().equals(streamid)) {
        streamRuleService.destroy(streamRule);
      } else {
        throw new NotFoundException();
      }
    } catch (org.graylog2.database.NotFoundException e) {
      throw new WebApplicationException(404);
    }

    return Response.status(Response.Status.fromStatusCode(204)).build();
  }
 private void assertResponseStatus(Response response, Response.Status status) {
   assertThat(response, is(notNullValue()));
   assertThat(Response.Status.fromStatusCode(response.getStatus()), is(status));
 }
Ejemplo n.º 14
0
  /**
   * Receives standard HTTP requests from the public {@code service} method and dispatches them to
   * the {@code do}<i>XXX</i> methods defined in this class. This method is an HTTP-specific version
   * of the {@link javax.servlet.Servlet#service} method. There's no need to override this method.
   *
   * @param request the {@link HttpServletRequest} object that contains the request the client made
   *     of the servlet
   * @param response the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client
   * @throws IOException if an input or output error occurs while the servlet is handling the HTTP
   *     request
   * @throws ServletException if the HTTP request cannot be handled
   * @see javax.servlet.Servlet#service
   */
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /**
     * There is an annoying edge case where the service method is invoked for the case when the URI
     * is equal to the deployment URL minus the '/', for example
     * http://locahost:8080/HelloWorldWebApp
     */
    final String servletPath = request.getServletPath();
    String pathInfo = request.getPathInfo();
    StringBuffer requestURL = request.getRequestURL();
    String requestURI = request.getRequestURI();
    final boolean checkPathInfo = pathInfo == null || pathInfo.isEmpty() || pathInfo.equals("/");
    if (checkPathInfo && !request.getRequestURI().endsWith("/")) {
      // Only do this if the last segment of the servlet path does not contain '.'
      // This handles the case when the extension mapping is used with the servlet
      // see issue 506
      // This solution does not require parsing the deployment descriptor,
      // however still leaves it broken for the very rare case if a standard path
      // servlet mapping would include dot in the last segment (e.g. /.webresources/*)
      // and somebody would want to hit the root resource without the trailing slash
      int i = servletPath.lastIndexOf('/');
      if (servletPath.substring(i + 1).indexOf('.') < 0) {
        // TODO (+ handle request URL with invalid characters - see the creation of
        // absoluteUriBuilder bellow)
        //                if
        // (webComponent.getResourceConfig().getFeature(ResourceConfig.FEATURE_REDIRECT)) {
        //                    URI l = UriBuilder.fromUri(request.getRequestURL().toString()).
        //                            path("/").
        //                            replaceQuery(request.getQueryString()).build();
        //
        //                    response.setStatus(307);
        //                    response.setHeader("Location", l.toASCIIString());
        //                    return;
        //                } else {
        //                pathInfo = "/";
        //                requestURL.append("/");
        //                requestURI += "/";
        //                }
      }
    }

    /**
     * The HttpServletRequest.getRequestURL() contains the complete URI minus the query and fragment
     * components.
     */
    UriBuilder absoluteUriBuilder;
    try {
      absoluteUriBuilder = UriBuilder.fromUri(requestURL.toString());
    } catch (IllegalArgumentException iae) {
      final Response.Status badRequest = Response.Status.BAD_REQUEST;
      if (webComponent.configSetStatusOverSendError) {
        response.reset();
        response.setStatus(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      } else {
        response.sendError(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      }
      return;
    }

    /**
     * The HttpServletRequest.getPathInfo() and HttpServletRequest.getServletPath() are in decoded
     * form.
     *
     * <p>On some servlet implementations the getPathInfo() removed contiguous '/' characters. This
     * is problematic if URIs are embedded, for example as the last path segment. We need to work
     * around this and not use getPathInfo for the decodedPath.
     */
    final String decodedBasePath = request.getContextPath() + servletPath + "/";

    final String encodedBasePath = UriComponent.encode(decodedBasePath, UriComponent.Type.PATH);

    if (!decodedBasePath.equals(encodedBasePath)) {
      throw new ProcessingException(
          "The servlet context path and/or the "
              + "servlet path contain characters that are percent encoded");
    }

    final URI baseUri;
    final URI requestUri;
    try {
      baseUri = absoluteUriBuilder.replacePath(encodedBasePath).build();

      String queryParameters = request.getQueryString();
      if (queryParameters == null) {
        queryParameters = "";
      }

      requestUri = absoluteUriBuilder.replacePath(requestURI).replaceQuery(queryParameters).build();
    } catch (UriBuilderException ex) {
      final Response.Status badRequest = Response.Status.BAD_REQUEST;
      if (webComponent.configSetStatusOverSendError) {
        response.reset();
        response.setStatus(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      } else {
        response.sendError(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      }
      return;
    }

    service(baseUri, requestUri, request, response);
  }
Ejemplo n.º 15
0
 public static ParamEntityThrowingWebApplicationException fromString(String arg) {
   throw new WebApplicationException(Response.Status.valueOf(parseArg(arg)));
 }
 private Response getOrcidErrorResponse(int errorCode, Response.Status status, Throwable t) {
   return getOrcidErrorResponse(errorCode, status.getStatusCode(), t);
 }
Ejemplo n.º 17
0
 /**
  * Matches when the HTTP status code of a {@link Response} instance is equal to the given code.
  *
  * @param expectedStatusCode
  * @return
  */
 public static Matcher<Response> statusCodeIs(Response.Status expectedStatusCode) {
   return new ResponseStatusCodeMatcher(
       org.hamcrest.Matchers.is(expectedStatusCode.getStatusCode()));
 }
Ejemplo n.º 18
0
 /**
  * Returns a map representation of a throwable object with a given status code. The map has a
  * status entry with the status code, and a message entry with the message of the throwable
  * object.
  *
  * @param e The throwable object
  * @param status The status code
  * @return A map representation of the error
  */
 private Map<String, Object> toMap(Throwable e, Response.Status status) {
   Map<String, Object> result = new HashMap<>();
   result.put("status", status.getStatusCode());
   result.put("message", e.getMessage());
   return result;
 }
Ejemplo n.º 19
0
 public REST assertStatus(Response.Status expectedStatus) {
   assertEquals("status code is not " + expectedStatus, expectedStatus.getStatusCode(), status);
   return this;
 }