Search in sources :

Example 26 with Headers

use of com.sun.net.httpserver.Headers in project jetty.project by eclipse.

the class JettyHttpExchangeDelegate method getRequestHeaders.

@Override
public Headers getRequestHeaders() {
    Headers headers = new Headers();
    Enumeration<?> en = _req.getHeaderNames();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        Enumeration<?> en2 = _req.getHeaders(name);
        while (en2.hasMoreElements()) {
            String value = (String) en2.nextElement();
            headers.add(name, value);
        }
    }
    return headers;
}
Also used : Headers(com.sun.net.httpserver.Headers)

Example 27 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) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 28 with Headers

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

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) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 29 with Headers

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

the class RemoteBrowseHandler method mkBrowsePage.

private String mkBrowsePage(String id, HttpExchange t) throws IOException {
    LOGGER.debug("Make browse page " + id);
    String user = RemoteUtil.userName(t);
    RootFolder root = parent.getRoot(user, true, t);
    String search = RemoteUtil.getQueryVars(t.getRequestURI().getQuery(), "str");
    List<DLNAResource> resources = root.getDLNAResources(id, true, 0, 0, root.getDefaultRenderer(), search);
    boolean upnpAllowed = RemoteUtil.bumpAllowed(t);
    boolean upnpControl = RendererConfiguration.hasConnectedControlPlayers();
    if (!resources.isEmpty() && resources.get(0).getParent() != null && (resources.get(0).getParent() instanceof CodeEnter)) {
        // this is a code folder the search string is  entered code
        CodeEnter ce = (CodeEnter) resources.get(0).getParent();
        ce.setEnteredCode(search);
        if (!ce.validCode(ce)) {
            // invalid code throw error
            throw new IOException("Auth error");
        }
        DLNAResource real = ce.getResource();
        if (!real.isFolder()) {
            // no folder   -> redirect
            Headers hdr = t.getResponseHeaders();
            hdr.add("Location", "/play/" + real.getId());
            RemoteUtil.respond(t, "", 302, "text/html");
            // return null here to avoid multiple responses
            return null;
        }
        // redirect to ourself
        Headers hdr = t.getResponseHeaders();
        hdr.add("Location", "/browse/" + real.getResourceId());
        RemoteUtil.respond(t, "", 302, "text/html");
        return null;
    }
    if (StringUtils.isNotEmpty(search) && !(resources instanceof CodeEnter)) {
        UMSUtils.postSearch(resources, search);
    }
    boolean hasFile = false;
    ArrayList<String> folders = new ArrayList<>();
    ArrayList<HashMap<String, String>> media = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    sb.setLength(0);
    sb.append("<a href=\"javascript:history.back()\" title=\"").append(RemoteUtil.getMsgString("Web.10", t)).append("\">");
    sb.append("<span>").append(RemoteUtil.getMsgString("Web.10", t)).append("</span>");
    sb.append("</a>");
    folders.add(sb.toString());
    // Generate innerHtml snippets for folders and media items
    for (DLNAResource resource : resources) {
        String newId = resource.getResourceId();
        String idForWeb = URLEncoder.encode(newId, "UTF-8");
        String thumb = "/thumb/" + idForWeb;
        String name = StringEscapeUtils.escapeHtml(resource.resumeName());
        if (resource instanceof VirtualVideoAction) {
            // Let's take the VVA real early
            sb.setLength(0);
            HashMap<String, String> item = new HashMap<>();
            sb.append("<a href=\"#\" onclick=\"umsAjax('/play/").append(idForWeb).append("', true);return false;\" title=\"").append(name).append("\">").append("<img class=\"thumb\" src=\"").append(thumb).append("\" alt=\"").append(name).append("\">").append("</a>");
            item.put("thumb", sb.toString());
            sb.setLength(0);
            sb.append("<a href=\"#\" onclick=\"umsAjax('/play/").append(idForWeb).append("', true);return false;\" title=\"").append(name).append("\">").append("<span class=\"caption\">").append(name).append("</span>").append("</a>");
            item.put("caption", sb.toString());
            item.put("bump", "<span class=\"floatRight\"></span>");
            media.add(item);
            hasFile = true;
            continue;
        }
        if (resource.isFolder()) {
            sb.setLength(0);
            // The resource is a folder
            String p = "/browse/" + idForWeb;
            boolean code = (resource instanceof CodeEnter);
            String txt = RemoteUtil.getMsgString("Web.8", t);
            if (code) {
                txt = RemoteUtil.getMsgString("Web.9", t);
            }
            if (resource.getClass().getName().contains("SearchFolder") || code) {
                // search folder add a prompt
                // NOTE!!!
                // Yes doing getClass.getname is REALLY BAD, but this
                // is to make legacy plugins utilize this function as well
                sb.append("<a href=\"javascript:void(0);\" onclick=\"searchFun('").append(p).append("','").append(txt).append("');\" title=\"").append(name).append("\">");
            } else {
                sb.append("<a href=\"").append(p).append("\" oncontextmenu=\"searchFun('").append(p).append("','").append(txt).append("');\" title=\"").append(name).append("\">");
            }
            sb.append("<span>").append(name).append("</span>");
            sb.append("</a>");
            folders.add(sb.toString());
        } else {
            // The resource is a media file
            sb.setLength(0);
            HashMap<String, String> item = new HashMap<>();
            if (upnpAllowed) {
                if (upnpControl) {
                    sb.append("<a class=\"bumpIcon\" href=\"javascript:bump.start('//").append(parent.getAddress()).append("','/play/").append(idForWeb).append("','").append(name.replace("'", "\\'")).append("')\" title=\"").append(RemoteUtil.getMsgString("Web.1", t)).append("\"></a>");
                } else {
                    sb.append("<a class=\"bumpIcon icondisabled\" href=\"javascript:notify('warn','").append(RemoteUtil.getMsgString("Web.2", t)).append("')\" title=\"").append(RemoteUtil.getMsgString("Web.3", t)).append("\"></a>");
                }
                if (resource.getParent() instanceof Playlist) {
                    sb.append("\n<a class=\"playlist_del\" href=\"#\" onclick=\"umsAjax('/playlist/del/").append(idForWeb).append("', true);return false;\" title=\"").append(RemoteUtil.getMsgString("Web.4", t)).append("\"></a>");
                } else {
                    sb.append("\n<a class=\"playlist_add\" href=\"#\" onclick=\"umsAjax('/playlist/add/").append(idForWeb).append("', false);return false;\" title=\"").append(RemoteUtil.getMsgString("Web.5", t)).append("\"></a>");
                }
            } else {
                // ensure that we got a string
                sb.append("");
            }
            item.put("bump", sb.toString());
            sb.setLength(0);
            if (WebRender.supports(resource) || resource.isResume() || resource.getType() == Format.IMAGE) {
                sb.append("<a href=\"/play/").append(idForWeb).append("\" title=\"").append(name).append("\">").append("<img class=\"thumb\" src=\"").append(thumb).append("\" alt=\"").append(name).append("\">").append("</a>");
                item.put("thumb", sb.toString());
                sb.setLength(0);
                sb.append("<a href=\"/play/").append(idForWeb).append("\" title=\"").append(name).append("\">").append("<span class=\"caption\">").append(name).append("</span>").append("</a>");
                item.put("caption", sb.toString());
            } else if (upnpControl && upnpAllowed) {
                // Include it as a web-disabled item so it can be thrown via upnp
                sb.append("<a class=\"webdisabled\" href=\"javascript:notify('warn','").append(RemoteUtil.getMsgString("Web.6", t)).append("')\"").append(" title=\"").append(name).append(' ').append(RemoteUtil.getMsgString("Web.7", t)).append("\">").append("<img class=\"thumb\" src=\"").append(thumb).append("\" alt=\"").append(name).append("\">").append("</a>");
                item.put("thumb", sb.toString());
                sb.setLength(0);
                sb.append("<span class=\"webdisabled caption\">").append(name).append("</span>");
                item.put("caption", sb.toString());
            }
            media.add(item);
            hasFile = true;
        }
    }
    HashMap<String, Object> vars = new HashMap<>();
    vars.put("name", id.equals("0") ? configuration.getServerDisplayName() : StringEscapeUtils.escapeHtml(root.getDLNAResource(id, null).getDisplayName()));
    vars.put("hasFile", hasFile);
    vars.put("folders", folders);
    vars.put("media", media);
    if (configuration.useWebControl()) {
        vars.put("push", true);
    }
    return parent.getResources().getTemplate("browse.html").execute(vars);
}
Also used : HashMap(java.util.HashMap) Headers(com.sun.net.httpserver.Headers) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DLNAResource(net.pms.dlna.DLNAResource) Playlist(net.pms.dlna.Playlist) VirtualVideoAction(net.pms.dlna.virtual.VirtualVideoAction) RootFolder(net.pms.dlna.RootFolder) CodeEnter(net.pms.dlna.CodeEnter)

Example 30 with Headers

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

the class RemoteUtil method respond.

public static void respond(HttpExchange t, byte[] response, int status, String mime) {
    if (response != null) {
        if (mime != null) {
            Headers hdr = t.getResponseHeaders();
            hdr.add("Content-Type", mime);
        }
        try (OutputStream os = t.getResponseBody()) {
            t.sendResponseHeaders(status, response.length);
            os.write(response);
            os.close();
        } catch (Exception e) {
            LOGGER.debug("Error sending response: " + e);
        }
    }
}
Also used : Headers(com.sun.net.httpserver.Headers) MalformedURLException(java.net.MalformedURLException)

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