Search in sources :

Example 31 with Headers

use of com.sun.net.httpserver.Headers in project UniversalMediaServer by UniversalMediaServer.

the class RemoteRawHandler method handle.

@Override
public void handle(HttpExchange t) throws IOException {
    LOGGER.debug("got a raw request " + t.getRequestURI());
    if (RemoteUtil.deny(t)) {
        throw new IOException("Access denied");
    }
    RootFolder root = parent.getRoot(RemoteUtil.userName(t), t);
    if (root == null) {
        throw new IOException("Unknown root");
    }
    String id;
    id = RemoteUtil.strip(RemoteUtil.getId("raw/", t));
    LOGGER.debug("raw id " + id);
    List<DLNAResource> res = root.getDLNAResources(id, false, 0, 0, root.getDefaultRenderer());
    if (res.size() != 1) {
        // another error
        LOGGER.debug("media unkonwn");
        throw new IOException("Bad id");
    }
    DLNAResource dlna = res.get(0);
    long len;
    String mime = null;
    InputStream in;
    Range.Byte range;
    if (dlna.getMedia() != null && dlna.getMedia().isImage() && dlna.getMedia().getImageInfo() != null) {
        boolean supported = false;
        ImageInfo imageInfo = dlna.getMedia().getImageInfo();
        if (root.getDefaultRenderer() instanceof WebRender) {
            WebRender renderer = (WebRender) root.getDefaultRenderer();
            supported = renderer.isImageFormatSupported(imageInfo.getFormat());
        }
        mime = dlna.getFormat() != null ? dlna.getFormat().mimeType() : root.getDefaultRenderer().getMimeType(dlna.mimeType(), dlna.getMedia());
        len = supported && imageInfo.getSize() != ImageInfo.SIZE_UNKNOWN ? imageInfo.getSize() : dlna.length();
        range = new Range.Byte(0l, len);
        if (supported) {
            in = dlna.getInputStream();
        } else {
            InputStream imageInputStream;
            if (dlna.getPlayer() instanceof ImagePlayer) {
                ProcessWrapper transcodeProcess = dlna.getPlayer().launchTranscode(dlna, dlna.getMedia(), new OutputParams(PMS.getConfiguration()));
                imageInputStream = transcodeProcess != null ? transcodeProcess.getInputStream(0) : null;
            } else {
                imageInputStream = dlna.getInputStream();
            }
            Image image = Image.toImage(imageInputStream, 3840, 2400, ScaleType.MAX, ImageFormat.JPEG, false);
            len = image.getBytes(false).length;
            in = image == null ? null : new ByteArrayInputStream(image.getBytes(false));
        }
    } else {
        len = dlna.length();
        dlna.setPlayer(null);
        range = RemoteUtil.parseRange(t.getRequestHeaders(), len);
        in = dlna.getInputStream(range, root.getDefaultRenderer());
        if (len == 0) {
            // For web resources actual length may be unknown until we open the stream
            len = dlna.length();
        }
        mime = root.getDefaultRenderer().getMimeType(dlna.mimeType(), dlna.getMedia());
    }
    Headers hdr = t.getResponseHeaders();
    LOGGER.debug("Sending media \"{}\" with mime type \"{}\"", dlna, mime);
    hdr.add("Content-Type", mime);
    hdr.add("Accept-Ranges", "bytes");
    hdr.add("Server", PMS.get().getServerName());
    hdr.add("Connection", "keep-alive");
    hdr.add("Transfer-Encoding", "chunked");
    if (in.available() != len) {
        hdr.add("Content-Range", "bytes " + range.getStart() + "-" + in.available() + "/" + len);
        t.sendResponseHeaders(206, in.available());
    } else {
        t.sendResponseHeaders(200, 0);
    }
    OutputStream os = new BufferedOutputStream(t.getResponseBody(), 512 * 1024);
    LOGGER.debug("start raw dump");
    RemoteUtil.dump(in, os);
}
Also used : ImagePlayer(net.pms.encoders.ImagePlayer) WebRender(net.pms.configuration.WebRender) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Headers(com.sun.net.httpserver.Headers) OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) IOException(java.io.IOException) Range(net.pms.dlna.Range) Image(net.pms.image.Image) DLNAResource(net.pms.dlna.DLNAResource) ProcessWrapper(net.pms.io.ProcessWrapper) ByteArrayInputStream(java.io.ByteArrayInputStream) RootFolder(net.pms.dlna.RootFolder) ImageInfo(net.pms.image.ImageInfo) OutputParams(net.pms.io.OutputParams) BufferedOutputStream(java.io.BufferedOutputStream)

Example 32 with Headers

use of com.sun.net.httpserver.Headers in project incubator-heron by apache.

the class NetworkUtilsTest method testReadHttpRequestBodyFail.

@Test
public void testReadHttpRequestBodyFail() throws Exception {
    HttpExchange exchange = Mockito.mock(HttpExchange.class);
    Headers headers = Mockito.mock(Headers.class);
    Mockito.doReturn(headers).when(exchange).getRequestHeaders();
    Mockito.doReturn("-1").when(headers).getFirst(Matchers.anyString());
    Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));
    Mockito.doReturn("10").when(headers).getFirst(Matchers.anyString());
    InputStream inputStream = Mockito.mock(InputStream.class);
    Mockito.doReturn(inputStream).when(exchange).getRequestBody();
    Mockito.doThrow(new IOException("Designed IO exception for testing")).when(inputStream).read(Matchers.any(byte[].class), Matchers.anyInt(), Matchers.anyInt());
    Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));
    Mockito.verify(inputStream, Mockito.atLeastOnce()).close();
}
Also used : Headers(com.sun.net.httpserver.Headers) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 33 with Headers

use of com.sun.net.httpserver.Headers in project incubator-heron by apache.

the class NetworkUtilsTest method testReadHttpRequestBody.

@Test
public void testReadHttpRequestBody() throws Exception {
    byte[] expectedBytes = "TO READ".getBytes();
    InputStream is = Mockito.spy(new ByteArrayInputStream(expectedBytes));
    HttpExchange exchange = Mockito.mock(HttpExchange.class);
    Headers headers = Mockito.mock(Headers.class);
    Mockito.doReturn(Integer.toString(expectedBytes.length)).when(headers).getFirst(Matchers.anyString());
    Mockito.doReturn(headers).when(exchange).getRequestHeaders();
    Mockito.doReturn(is).when(exchange).getRequestBody();
    Assert.assertArrayEquals(expectedBytes, NetworkUtils.readHttpRequestBody(exchange));
    Mockito.verify(is, Mockito.atLeastOnce()).close();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Headers(com.sun.net.httpserver.Headers) HttpExchange(com.sun.net.httpserver.HttpExchange) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 34 with Headers

use of com.sun.net.httpserver.Headers in project data-transfer-project by google.

the class Oauth2CallbackHandler method handleExchange.

private String handleExchange(HttpExchange exchange) throws IOException {
    String redirect = "/error";
    try {
        Headers requestHeaders = exchange.getRequestHeaders();
        String requestURL = ReferenceApiUtils.createURL(requestHeaders.getFirst(HttpHeaders.HOST), exchange.getRequestURI().toString(), IS_LOCAL);
        AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(requestURL);
        // check for user-denied error
        if (authResponse.getError() != null) {
            logger.warn("Authorization DENIED: {} Redirecting to /error", authResponse.getError());
            return redirect;
        }
        // retrieve cookie from exchange
        Map<String, HttpCookie> httpCookies = ReferenceApiUtils.getCookies(requestHeaders);
        HttpCookie encodedIdCookie = httpCookies.get(JsonKeys.ID_COOKIE_KEY);
        Preconditions.checkArgument(encodedIdCookie != null && !Strings.isNullOrEmpty(encodedIdCookie.getValue()), "Encoded Id cookie required");
        UUID jobId = ReferenceApiUtils.decodeJobId(encodedIdCookie.getValue());
        logger.debug("State token: {}", authResponse.getState());
        // TODO(#258): Check job ID in state token, was broken during local demo
        // UUID jobIdFromState = ReferenceApiUtils.decodeJobId(authResponse.getState());
        // // TODO: Remove sanity check
        // Preconditions.checkState(
        // jobIdFromState.equals(jobId),
        // "Job id in cookie [%s] and request [%s] should match",
        // jobId,
        // jobIdFromState);
        PortabilityJob job = store.findJob(jobId);
        Preconditions.checkNotNull(job, "existing job not found for jobId: %s", jobId);
        // TODO: Determine service from job or from authUrl path?
        AuthMode authMode = ReferenceApiUtils.getAuthMode(exchange.getRequestHeaders());
        String service = (authMode == AuthMode.EXPORT) ? job.exportService() : job.importService();
        Preconditions.checkState(!Strings.isNullOrEmpty(service), "service not found, service: %s authMode: %s, jobId: %s", service, authMode, jobId.toString());
        AuthDataGenerator generator = registry.getAuthDataGenerator(service, job.transferDataType(), authMode);
        Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), service);
        // Obtain the session key for this job
        String encodedSessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(encodedSessionKey));
        // Retrieve initial auth data, if it existed
        AuthData initialAuthData = null;
        String encryptedInitialAuthData = (authMode == AuthMode.EXPORT) ? job.jobAuthorization().encryptedInitialExportAuthData() : job.jobAuthorization().encryptedInitialImportAuthData();
        if (encryptedInitialAuthData != null) {
            // Retrieve and parse the session key from the job
            // Decrypt and deserialize the object
            String serialized = DecrypterFactory.create(key).decrypt(encryptedInitialAuthData);
            initialAuthData = objectMapper.readValue(serialized, AuthData.class);
        }
        // TODO: Use UUID instead of UUID.toString()
        // Generate auth data
        AuthData authData = generator.generateAuthData(baseApiUrl, authResponse.getCode(), jobId.toString(), initialAuthData, null);
        Preconditions.checkNotNull(authData, "Auth data should not be null");
        // Serialize and encrypt the auth data
        String serialized = objectMapper.writeValueAsString(authData);
        String encryptedAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Set new cookie
        ReferenceApiUtils.setCookie(exchange.getResponseHeaders(), encryptedAuthData, authMode);
        redirect = baseUrl + ((authMode == AuthMode.EXPORT) ? FrontendConstantUrls.URL_NEXT_PAGE : FrontendConstantUrls.URL_COPY_PAGE);
    } catch (Exception e) {
        logger.error("Error handling request: {}", e);
        throw e;
    }
    return redirect;
}
Also used : PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) SecretKey(javax.crypto.SecretKey) AuthData(org.dataportabilityproject.types.transfer.auth.AuthData) HttpHeaders(com.google.common.net.HttpHeaders) Headers(com.sun.net.httpserver.Headers) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) UUID(java.util.UUID) HttpCookie(java.net.HttpCookie) AuthMode(org.dataportabilityproject.spi.gateway.auth.AuthServiceProviderRegistry.AuthMode) IOException(java.io.IOException)

Example 35 with Headers

use of com.sun.net.httpserver.Headers in project heron by twitter.

the class NetworkUtilsTest method testReadHttpRequestBodyFail.

@Test
public void testReadHttpRequestBodyFail() throws Exception {
    HttpExchange exchange = Mockito.mock(HttpExchange.class);
    Headers headers = Mockito.mock(Headers.class);
    Mockito.doReturn(headers).when(exchange).getRequestHeaders();
    Mockito.doReturn("-1").when(headers).getFirst(Matchers.anyString());
    Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));
    Mockito.doReturn("10").when(headers).getFirst(Matchers.anyString());
    InputStream inputStream = Mockito.mock(InputStream.class);
    Mockito.doReturn(inputStream).when(exchange).getRequestBody();
    Mockito.doThrow(new IOException("Designed IO exception for testing")).when(inputStream).read(Matchers.any(byte[].class), Matchers.anyInt(), Matchers.anyInt());
    Assert.assertArrayEquals(new byte[0], NetworkUtils.readHttpRequestBody(exchange));
    Mockito.verify(inputStream, Mockito.atLeastOnce()).close();
}
Also used : Headers(com.sun.net.httpserver.Headers) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpExchange(com.sun.net.httpserver.HttpExchange) IOException(java.io.IOException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Headers (com.sun.net.httpserver.Headers)56 OutputStream (java.io.OutputStream)23 IOException (java.io.IOException)17 InetSocketAddress (java.net.InetSocketAddress)12 InputStream (java.io.InputStream)10 HttpExchange (com.sun.net.httpserver.HttpExchange)9 Test (org.junit.Test)9 Test (org.junit.jupiter.api.Test)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 HttpServer (com.sun.net.httpserver.HttpServer)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 BufferedImage (java.awt.image.BufferedImage)5 BufferedReader (java.io.BufferedReader)5 InputStreamReader (java.io.InputStreamReader)5 Path (java.nio.file.Path)5 HashMap (java.util.HashMap)5 BeforeClass (org.junit.BeforeClass)5 Graphics2D (java.awt.Graphics2D)4 Image (java.awt.Image)4