org.glassfish.grizzly.http.server.Response Java Examples

The following examples show how to use org.glassfish.grizzly.http.server.Response. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GrizzlyHttpService.java    From linstor-server with GNU General Public License v3.0 6 votes vote down vote up
private void addHTTPSRedirectHandler(HttpServer httpServerRef, int httpsPort)
{
    httpServerRef.getServerConfiguration().addHttpHandler(
        new HttpHandler()
        {
            @Override
            public void service(Request request, Response response) throws Exception
            {
                response.setStatus(HttpStatus.NOT_FOUND_404);
                response.sendRedirect(
                    String.format("https://%s:%d", request.getServerName(), httpsPort) +
                        request.getHttpHandlerPath()
                );
            }
        }
    );
}
 
Example #2
Source File: JsonRpcHandler.java    From nuls-v2 with MIT License 6 votes vote down vote up
private RpcResult doHandler(Map<String, Object> jsonRpcParam, Response response) throws Exception {
    String method = (String) jsonRpcParam.get("method");
    String id = jsonRpcParam.get("id") + "";
    if (!"2.0".equals(jsonRpcParam.get("jsonrpc"))) {
        LoggerUtil.commonLog.warn("the request is not a json-rpc 2.0 request!");
        return responseError("-32600", "the request is not a json-rpc 2.0 request", id);
    }
    RpcMethodInvoker invoker = JsonRpcContext.RPC_METHOD_INVOKER_MAP.get(method);

    if (null == invoker) {
        LoggerUtil.commonLog.warn("Can't find the method:{}", method);
        return responseError("-32601", "Can't find the method", id);
    }

    RpcResult result = invoker.invoke(jsonRpcParam.get("params"));
    result.setId(id);
    return result;
}
 
Example #3
Source File: WebServer.java    From AthenaX with Apache License 2.0 6 votes vote down vote up
public WebServer(URI endpoint) throws IOException {
  this.server = GrizzlyServerFactory.createHttpServer(endpoint, new HttpHandler() {

    @Override
    public void service(Request rqst, Response rspns) throws Exception {
      rspns.setStatus(HttpStatus.NOT_FOUND_404.getStatusCode(), "Not found");
      rspns.getWriter().write("404: not found");
    }
  });

  WebappContext context = new WebappContext("WebappContext", BASE_PATH);
  ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
  registration.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS,
      PackagesResourceConfig.class.getName());

  StringJoiner sj = new StringJoiner(",");
  for (String s : PACKAGES) {
    sj.add(s);
  }

  registration.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, sj.toString());
  registration.addMapping(BASE_PATH);
  context.deploy(server);
}
 
Example #4
Source File: RootHttpHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void service(final Request request, final Response response) throws Exception {
	// don't decode and avoid creating a string
	final DataChunk requestURIBC = request.getRequest().getRequestURIRef().getRequestURIBC();

	if (requestURIBC.equals("/json")) {
		jsonHandler.service(request, response);
	} else if (requestURIBC.equals("/plaintext")) {
		plainTextHandler.service(request, response);
	} else {
		response.getOutputBuffer().write(
				getErrorPageGenerator(request).generate(request,
						HttpStatus.NOT_FOUND_404.getStatusCode(),
						HttpStatus.NOT_FOUND_404.getReasonPhrase(), null, null));
	}
}
 
Example #5
Source File: GrizzlyHttpServerITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException {
  final HttpServer server = new HttpServer();
  final NetworkListener listener = new NetworkListener("grizzly", DEFAULT_NETWORK_HOST, 18906);
  server.addListener(listener);
  server.start();

  server.getServerConfiguration().addHttpHandler(new HttpHandler() {
    @Override
    public void service(final Request request, final Response response) {
      TestUtil.checkActiveSpan();
      response.setStatus(200);
    }
  });

  int responseCode = -1;
  try {
    final URL url = new URL("http://localhost:18906/");
    final HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    responseCode = connection.getResponseCode();
    connection.disconnect();
  }
  finally {
    server.shutdownNow();

    if (200 != responseCode)
      throw new AssertionError("ERROR: response: " + responseCode);

    TestUtil.checkSpan(true, new ComponentSpanCount("java-grizzly-http-server", 1), new ComponentSpanCount("http-url-connection", 1));
  }
}
 
Example #6
Source File: GrizzlyHttpServer.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add the HTTP handler.
 */
private void addHttpHandler() {
    httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() {
        @Override
        public void service(Request request, Response response) throws Exception {
            GrizzlyHttpServerRequest gRequest = new GrizzlyHttpServerRequest(request);
            GrizzlyHttpServerResponse gResponse = new GrizzlyHttpServerResponse(response);
            httpServerProcessor.process(gRequest, gResponse);
        }
    });
}
 
Example #7
Source File: GatfConfigToolUtil.java    From gatf with Apache License 2.0 5 votes vote down vote up
protected static void handleErrorJson(Throwable e, Response response, HttpStatus status) throws IOException
{
	String configJson = e.getMessage()==null?ExceptionUtils.getStackTrace(e):e.getMessage();
	response.setContentType(MediaType.APPLICATION_XML);
	response.setContentLength(configJson.length());
       response.getWriter().write(configJson);
	response.setStatus(status==null?HttpStatus.INTERNAL_SERVER_ERROR_500:status);
	if(status==null)e.printStackTrace();
}
 
Example #8
Source File: GatfConfigToolUtil.java    From gatf with Apache License 2.0 5 votes vote down vote up
protected static void handleError(Throwable e, Response response, HttpStatus status) throws IOException
{
	String configJson = e.getMessage()==null?ExceptionUtils.getStackTrace(e):e.getMessage();
	response.setContentLength(configJson.length());
       response.getWriter().write(configJson);
	response.setStatus(status==null?HttpStatus.INTERNAL_SERVER_ERROR_500:status);
	if(status==null)e.printStackTrace();
}
 
Example #9
Source File: GatfConfigToolUtil.java    From gatf with Apache License 2.0 5 votes vote down vote up
protected static void handleRootContext(HttpServer server, final String mainDir, final GatfConfigToolMojoInt mojo) {
	server.getServerConfiguration().addHttpHandler(
	    new HttpHandler() {
	        public void service(Request request, Response response) throws Exception {
	        	new CacheLessStaticHttpHandler(mainDir).service(request, response);
	        }
	    }, "/");
	
	server.getServerConfiguration().addHttpHandler(new GatfProjectZipHandler(mojo), "/projectZip");
}
 
Example #10
Source File: PlainTextHttpHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void service(final Request request, final Response response) throws Exception {
	response.setContentType(CONTENT_TYPE);
	response.getWriter().write("Hello, World!");
}
 
Example #11
Source File: JsonHttpHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void service(final Request request, final Response response) throws Exception {
	response.setContentType(CONTENT_TYPE);
	// Write JSON encoded message to the response.
	MAPPER.writeValue(response.getOutputStream(), new HelloMessage());
}
 
Example #12
Source File: PlainText2HttpHandler.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void service(final Request request, final Response response) throws Exception {
	response.setContentType(CONTENT_TYPE);
	response.getOutputStream().write(HELLO_WORLD_BYTES);
}
 
Example #13
Source File: CacheLessStaticHttpHandler.java    From gatf with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean handle(final String uri,
        final Request request,
        final Response response) throws Exception {

    boolean found = false;

    final File[] fileFolders = docRoots.getArray();
    if (fileFolders == null) {
        return false;
    }

    File resource = null;

    for (int i = 0; i < fileFolders.length; i++) {
        final File webDir = fileFolders[i];
        // local file
        resource = new File(webDir, uri);
        final boolean exists = resource.exists();
        final boolean isDirectory = resource.isDirectory();

        if (exists && isDirectory) {
            final File f = new File(resource, "/index.html");
            if (f.exists()) {
                resource = f;
                found = true;
                break;
            }
        }

        if (isDirectory || !exists) {
            found = false;
        } else {
            found = true;
            break;
        }
    }

    if (!found) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "File not found {0}", resource);
        }
        return false;
    }

    assert resource != null;
    
    // If it's not HTTP GET - return method is not supported status
    if (!Method.GET.equals(request.getMethod())) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "File found {0}, but HTTP method {1} is not allowed",
                    new Object[] {resource, request.getMethod()});
        }
        response.setStatus(HttpStatus.METHOD_NOT_ALLOWED_405);
        response.setHeader(Header.Allow, "GET");
        return true;
    }
    
    pickupContentType(response, resource.getPath());
    
    sendFile(response, resource);

    return true;
}
 
Example #14
Source File: GatfReportsHandler.java    From gatf with Apache License 2.0 4 votes vote down vote up
@Override
public void service(Request request, Response response) throws Exception {
    response.setHeader("Cache-Control", "no-cache, no-store");
   	try {
   		final GatfExecutorConfig gatfConfig = GatfConfigToolUtil.getGatfExecutorConfig(mojo, null);
		String basepath = gatfConfig.getOutFilesBasePath()==null?mojo.getRootDir():gatfConfig.getOutFilesBasePath();
		String dirPath = basepath + SystemUtils.FILE_SEPARATOR + gatfConfig.getOutFilesDir();
		if(!new File(dirPath).exists()) {
			new File(dirPath).mkdir();
		}
		if(request.getMethod().equals(Method.GET) ) {
		    new CacheLessStaticHttpHandler(dirPath).service(request, response);
		} else if(request.getMethod().equals(Method.PUT) ) {
		    String action = request.getParameter("action");
		    String testcaseFileName = request.getParameter("testcaseFileName");
		    String testCaseName = request.getParameter("testCaseName");
		    boolean isServerLogsApi = request.getParameter("isServerLogsApi")!=null;
		    boolean isExternalLogsApi = request.getParameter("isExternalLogsApi")!=null;
		    TestCaseReport tcReport = null;
		    if(action.equals("replayTest"))
		    { 
		        tcReport = new org.codehaus.jackson.map.ObjectMapper().readValue(request.getInputStream(), 
		                TestCaseReport.class);
		        if(tcReport == null) {
		            throw new RuntimeException("Invalid testcase report details provided");
		        }
		    } 
		    else if(isExternalLogsApi && !action.equals("playTest"))
		    {
		        tcReport = new org.codehaus.jackson.map.ObjectMapper().readValue(request.getInputStream(), 
		                TestCaseReport.class);
		    }
		    Object[] out = executeTest(gatfConfig, tcReport, action, testcaseFileName, testCaseName, isServerLogsApi, isExternalLogsApi, 0, false);
		    if(out[1]!=null) {
		        response.setContentType(out[2].toString());
		        response.setContentLength(((String)out[1]).length());
		        response.getWriter().write((String)out[1]);
		    }
		    response.setStatus((HttpStatus)out[0]);
		}
   	} catch (Exception e) {
   		GatfConfigToolUtil.handleError(e, response, null);
	} finally {
	    if(lock.isLocked()) {
	        lock.unlock();
	    }
	}
   }
 
Example #15
Source File: VanillaExtract.java    From osm-lib with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void service(Request request, Response response) throws Exception {

    response.setContentType("application/osm");
    String uri = request.getDecodedRequestURI();
    LOG.info("VEX request: {}", uri);
    int suffixIndex = uri.lastIndexOf('.');
    String fileType = uri.substring(suffixIndex);
    OutputStream outStream = response.getOutputStream();
    try {
        String[] coords = uri.substring(1, suffixIndex).split("[,;]");
        double minLat = Double.parseDouble(coords[0]);
        double minLon = Double.parseDouble(coords[1]);
        double maxLat = Double.parseDouble(coords[2]);
        double maxLon = Double.parseDouble(coords[3]);
        if (minLat >= maxLat || minLon >= maxLon || minLat < -90 || maxLat > 90 || minLon < -180 || maxLon > 180) {
            throw new IllegalArgumentException();
        }
        /* Respond to head requests to let the client know the server is alive and the request is valid. */
        if (request.getMethod() == Method.HEAD) {
            response.setStatus(HttpStatus.OK_200);
            return;
        }
        /* TODO filter out buildings on the server side. */
        boolean buildings = coords.length > 4 && "buildings".equalsIgnoreCase(coords[4]);

        OSMEntitySink sink = OSMEntitySink.forStream(uri, outStream);
        TileOSMSource tileSource = new TileOSMSource(osm);
        tileSource.setBoundingBox(minLat, minLon, maxLat, maxLon);
        tileSource.copyTo(sink);
        response.setStatus(HttpStatus.OK_200);
    } catch (Exception ex) {
        LOG.error("Could not process request with bad URI format {}.", uri);
        response.setContentType("text/plain");
        response.setStatus(HttpStatus.BAD_REQUEST_400);
        outStream.write("URI format: /min_lat,min_lon,max_lat,max_lon[.pbf|.vex] (all coords in decimal degrees)\n".getBytes());
        ex.printStackTrace();
    } finally {
        outStream.close();
    }
}
 
Example #16
Source File: TintHandler.java    From tint with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void service(Request request, Response response) throws Exception {

    request.setCharacterEncoding("UTF-8");

    Buffer postBody = request.getPostBody(1024);
    String text = postBody.toStringContent();

    if (request.getParameter("text") != null) {
        text = request.getParameter("text");
    }

    String outputFormat = request.getParameter("format");

    InputStream inputStream = new ByteArrayInputStream(text.getBytes());
    OutputStream outputStream = new ByteArrayOutputStream();

    TintRunner.OutputFormat format = TintRunner.getOutputFormat(outputFormat, TintRunner.OutputFormat.JSON);
    pipeline.run(inputStream, outputStream, format);

    LOGGER.debug("Text: {}", text);

    String output = outputStream.toString();

    writeOutput(response, contentTypes.get(format), output);
}
 
Example #17
Source File: TintHandler.java    From tint with GNU General Public License v3.0 4 votes vote down vote up
public void writeOutput(Response response, String contentType, String output) throws IOException {
    response.setContentType(contentType);
    response.setCharacterEncoding("UTF-8");
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.getWriter().write(output);
}
 
Example #18
Source File: GrizzlyHttpService.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public javax.ws.rs.core.Response toResponse(Exception exc)
{
    String errorReport = errorReporter.reportError(exc);
    javax.ws.rs.core.Response.Status respStatus;

    ApiCallRcImpl apiCallRc = new ApiCallRcImpl();
    if (exc instanceof ApiRcException)
    {
        apiCallRc.addEntries(((ApiRcException) exc).getApiCallRc());
        respStatus = javax.ws.rs.core.Response.Status.BAD_REQUEST;
    }
    else
    if (exc instanceof JsonMappingException ||
        exc instanceof JsonParseException)
    {
        apiCallRc.addEntry(
            ApiCallRcImpl.entryBuilder(
                ApiConsts.API_CALL_PARSE_ERROR,
                "Unable to parse input json."
            )
                .setDetails(exc.getMessage())
                .addErrorId(errorReport)
                .build()
        );
        respStatus = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
    }
    else
    if (exc instanceof NotFoundException)
    {
        apiCallRc.addEntry(
            ApiCallRcImpl.entryBuilder(
                ApiConsts.FAIL_UNKNOWN_ERROR,
                String.format("Path '%s' not found on server.", uriInfo.getPath())
            ).setDetails(exc.getMessage()).build());
        respStatus = javax.ws.rs.core.Response.Status.NOT_FOUND;
    }
    else
    {
        apiCallRc.addEntry(
            ApiCallRcImpl.entryBuilder(
                ApiConsts.FAIL_UNKNOWN_ERROR,
                "An unknown error occurred."
            )
                .setDetails(exc.getMessage())
                .addErrorId(errorReport)
                .build()
        );
        respStatus = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
    }

    return javax.ws.rs.core.Response
        .status(respStatus)
        .type(MediaType.APPLICATION_JSON)
        .entity(ApiCallRcRestUtils.toJSON(apiCallRc))
        .build();
}
 
Example #19
Source File: GrizzlyHttpServerResponse.java    From piranha with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param response the Grizzly response.
 */
public GrizzlyHttpServerResponse(Response response) {
    this.response = response;
}