Example usage for org.apache.commons.codec.net URLCodec URLCodec

List of usage examples for org.apache.commons.codec.net URLCodec URLCodec

Introduction

In this page you can find the example usage for org.apache.commons.codec.net URLCodec URLCodec.

Prototype

public URLCodec() 

Source Link

Document

Default constructor.

Usage

From source file:org.owasp.jbrofuzz.encode.EncoderHashCore.java

private static String decodeUrlCodec(final String decodeText) {
    final URLCodec codec = new URLCodec();
    try {/*w w  w.  j  a v a2s .c  o  m*/
        return codec.decode(decodeText, "UTF-8");
    } catch (final DecoderException e) {
        return "Error: www-form-urlencoded value cannot be decoded...";
    } catch (final UnsupportedEncodingException e) {
        return "Error: www-form-urlencoded value cannot be decoded...";
    }
}

From source file:org.owasp.jbrofuzz.encode.EncoderHashCore.java

private static String encodeUrlCodec(final String encodeText) {
    final URLCodec codec = new URLCodec();

    try {//from ww  w.  j  a v  a  2s. c  o m
        return codec.encode(encodeText, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
        return "Error: Sting input cannot be decoded";
    }
}

From source file:org.p2pvpn.network.bittorrent.BitTorrentTracker.java

/**
 * Poll the tracker.//from ww  w. j  av  a2  s. c  o  m
 * @param hash the hash of the cuttent network
 * @param port the local port
 * @return a Bencode-Map
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException
 */
private Map<Object, Object> trackerRequest(byte[] hash, int port) throws MalformedURLException, IOException {
    String sUrl = tracker + "?info_hash=" + new String(new URLCodec().encode(hash)) + "&port=" + port
            + "&compact=1&peer_id=" + new String(new URLCodec().encode(peerId))
            + "&uploaded=0&downloaded=0&left=100";

    //System.out.println(sUrl);

    URL url = new URL(sUrl);
    PushbackInputStream in = new PushbackInputStream(url.openStream());
    return (Map<Object, Object>) Bencode.parseBencode(in);
}

From source file:org.rhq.gui.content.ContentHTTPServlet.java

public void init() throws ServletException {
    super.init();
    urlCodec = new URLCodec();
    repoMgr = LookupUtil.getRepoManagerLocal();
    contentMgr = LookupUtil.getContentManager();
    contentSourceMgr = LookupUtil.getContentSourceManager();
    distroMgr = LookupUtil.getDistributionManagerLocal();
}

From source file:org.texai.torrent.domainEntity.MetaInfo.java

/** Gets the url encoded info hash.
 *
 * @return the url encoded info hash//from w w w .j  a v a 2s . c o m
 */
public String getURLEncodedInfoHash() {
    return new String((new URLCodec()).encode(infoHash));
}

From source file:org.texai.torrent.PeerCoordinator.java

/** Gets our URL encoded id bytes
 *
 * @return our URL encoded id bytes/*from   ww w.  j a v  a  2 s.co m*/
 */
public String getURLEncodedID() {
    return new String((new URLCodec()).encode(ourIdBytes));
}

From source file:org.texai.torrent.Tracker.java

/** Handles the statistics request, which is not part of the BitTorrent protocol.  It returns an
 * HTML statistics page.//  w  w  w.  j av a2  s . c o m
 *
 * @param httpRequest the HTTP request
 * @param channel the channel
 */
public void handleStatisticsRequest(final HttpRequest httpRequest, final Channel channel) {
    assert httpRequest != null : "httpRequest must not be null";
    assert channel != null : "channel must not be null";

    final StringBuilder responseContent = new StringBuilder();
    responseContent.append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n");
    responseContent.append(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
    responseContent.append("<html lang=\"en-US\" xml:lang=\"en-US\" xmlns=\"http://www.w3.org/1999/xhtml\">\n");
    responseContent.append("  <head>\n");
    responseContent.append("    <title>Snark</title>\n");
    responseContent.append("  </head>\n");
    responseContent.append("  <body>\n");
    responseContent.append("    <h2>Snark BitTorrent Tracker</h2>\n");
    responseContent.append("    <table border=\"1\">\n");
    responseContent.append("      <tr>\n");
    responseContent.append("        <th>Torrent Hash</th>\n");
    responseContent.append("        <th>Finished</th>\n");
    responseContent.append("        <th>Seeders</th>\n");
    responseContent.append("        <th>Leechers</th>\n");
    responseContent.append("      </tr>\n");
    Map<byte[], Map<String, Object>> filesDictionary = null;

    final QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.getUri());
    final Map<String, List<String>> parameterDictionary = queryStringDecoder.getParameters();
    try {
        filesDictionary = gatherFilesDictionary(parameterDictionary);
    } catch (DecoderException ex) {
        throw new TexaiException(ex);
    }
    for (final Entry<byte[], Map<String, Object>> filesDictionaryEntry : filesDictionary.entrySet()) {
        responseContent.append("      <tr>\n");
        responseContent.append("        <td>");
        responseContent.append(new String((new URLCodec()).encode(filesDictionaryEntry.getKey())));
        responseContent.append("</td>\n");
        final Map<String, Object> peersDictionary = filesDictionaryEntry.getValue();
        responseContent.append("        <td>");
        responseContent.append(peersDictionary.get("downloaded"));
        responseContent.append("</td>\n");
        responseContent.append("        <td>");
        responseContent.append(peersDictionary.get("complete"));
        responseContent.append("</td>\n");
        responseContent.append("        <td>");
        responseContent.append(peersDictionary.get("incomplete"));
        responseContent.append("</td>\n");
        responseContent.append("      </tr>\n");
    }
    responseContent.append("    </table>\n");
    responseContent.append("  </body>\n");
    responseContent.append("</html>\n");

    NettyHTTPUtils.writeHTMLResponse(httpRequest, responseContent, channel);
}

From source file:org.texai.torrent.Tracker.java

/** Handles the announce request.
 *
 * @param httpRequest the HTTP request/*from w  w w  .j  a va  2  s . c  o  m*/
 * @param channel the channel
 */
public void handleAnnounceRequest(final HttpRequest httpRequest, final Channel channel) {
    //Preconditions
    assert httpRequest != null : "httpRequest must not be null";
    assert channel != null : "channel must not be null";

    final URI uri;
    try {
        uri = new URI(httpRequest.getUri());
    } catch (URISyntaxException ex) {
        throw new TexaiException(ex);
    }
    final Map<String, String> parameterDictionary = HTTPUtils.getQueryMap(uri.getRawQuery());
    LOGGER.warn("tracker announce request: " + channel.getRemoteAddress() + " -> " + parameterDictionary);

    // info hash
    final String requestedUrlEncodedInfoHash = parameterDictionary.get("info_hash");
    LOGGER.debug("  requestedUrlEncodedInfoHash: " + requestedUrlEncodedInfoHash);
    if (requestedUrlEncodedInfoHash == null) {
        failure(httpRequest, "No info_hash given", channel);
        return;
    }
    boolean found = false;
    LOGGER.debug("trackedPeerInfosDictionary: " + trackedPeerInfosDictionary);
    synchronized (trackedPeerInfosDictionary) {
        for (String urlEncodedInfoHash : trackedPeerInfosDictionary.keySet()) {
            if (urlEncodedInfoHash.equals(requestedUrlEncodedInfoHash)) {
                found = true;
            }
        }
    }
    if (!found) {
        failure(httpRequest, "Tracker doesn't handle given info_hash", channel);
        return;
    }

    // peer id
    byte[] peerIdBytes;
    final String peerIdValue = parameterDictionary.get("peer_id");
    if (peerIdValue == null) {
        failure(httpRequest, "No peer_id given", channel);
        return;
    }
    try {
        peerIdBytes = (new URLCodec()).decode(peerIdValue.getBytes());
    } catch (DecoderException ex) {
        failure(httpRequest, "cannot decode peer id value: " + peerIdValue, channel);
        return;
    }
    if (peerIdBytes.length != 20) {
        failure(httpRequest, "peer_id must be 20 bytes long", channel);
        return;
    }

    // port
    @SuppressWarnings("UnusedAssignment")
    int peerPort = 0;
    final String peerPortValue = parameterDictionary.get("port");
    if (peerPortValue == null) {
        failure(httpRequest, "No port given", channel);
        return;
    }
    try {
        peerPort = Integer.parseInt(peerPortValue);
    } catch (NumberFormatException nfe) {
        failure(httpRequest, "port not a number: " + nfe, channel);
        return;
    }

    // ip
    final InetAddress inetAddress = ((InetSocketAddress) channel.getRemoteAddress()).getAddress();
    InetAddress inetAddress1 = null;
    if (NetworkUtils.isPrivateNetworkAddress(inetAddress)) {
        // See http://wiki.theory.org/BitTorrentSpecification#Tracker_Response .
        // Handle the case where the peer and ourselves are both behind the same NAT router.  The ip address from the
        // socket connection will be a private address which indicates the peer is on our private network behind the
        // internet-facing router.  The optional ip parameter contains what the peer found as its local host address.
        final String peerSuppliedIPAddress = parameterDictionary.get("ip");
        if (peerSuppliedIPAddress == null) {
            failure(httpRequest, "No ip address given", channel);
            return;
        } else {
            try {
                inetAddress1 = InetAddress.getByName(peerSuppliedIPAddress);
            } catch (UnknownHostException ex) {
                LOGGER.warn("invalid ip parameter supplied by peer: '" + peerSuppliedIPAddress + "'");
            }
        }
        if (inetAddress1 == null) {
            inetAddress1 = inetAddress;
        }
    } else {
        inetAddress1 = inetAddress;
    }
    final TrackedPeerInfo trackedPeerInfo = new TrackedPeerInfo(peerIdBytes, inetAddress1, peerPort);

    // downloaded
    final int downloaded;
    final String downloaded_value = parameterDictionary.get("downloaded");
    if (downloaded_value == null) {
        failure(httpRequest, "No downloaded given", channel);
        return;
    }
    try {
        downloaded = Integer.parseInt(downloaded_value);
    } catch (NumberFormatException nfe) {
        failure(httpRequest, "downloaded not a number: " + nfe, channel);
        return;
    }

    // event
    final Map<String, Object> responseDictionary = new HashMap<>();
    final Map<TrackedPeerInfo, TrackedPeerStatus> trackedPeerInfosMap = trackedPeerInfosDictionary
            .get(requestedUrlEncodedInfoHash);
    final String event = parameterDictionary.get("event");
    if (event == null || event.isEmpty()) {
        synchronized (trackedPeerInfosMap) {
            final TrackedPeerStatus trackedPeerStatus = trackedPeerInfosMap.get(trackedPeerInfo);
            if (trackedPeerStatus == null) {
                failure(httpRequest, "peer never started", channel);
                return;
            }
            LOGGER.warn("updating peer " + trackedPeerInfo + " expiration");
            trackedPeerStatus.updatePeerExpirationMilliseconds();
        }
    } else {
        if (event.equals(COMPLETED_EVENT)) {
            final TrackedPeerStatus trackedPeerStatus = trackedPeerInfosMap.get(trackedPeerInfo);
            if (trackedPeerStatus == null) {
                failure(httpRequest, "peer never started", channel);
                return;
            }
            trackedPeerStatus.event = COMPLETED_EVENT;
            if (downloaded == 0) {
                LOGGER.warn("seeding without download: " + trackedPeerInfo);
            } else {
                LOGGER.warn("seeding after completed download: " + trackedPeerInfo);
                synchronized (completionsDictionary) {
                    final Integer nbrDownloaded = completionsDictionary.get(requestedUrlEncodedInfoHash);
                    if (nbrDownloaded == null) {
                        completionsDictionary.put(requestedUrlEncodedInfoHash, 1);
                    } else {
                        completionsDictionary.put(requestedUrlEncodedInfoHash, nbrDownloaded + 1);
                    }
                }
            }
        } else {
            synchronized (trackedPeerInfosMap) {
                switch (event) {
                case STOPPED_EVENT:
                    LOGGER.warn("removing stopped peer " + trackedPeerInfo);
                    trackedPeerInfosMap.remove(trackedPeerInfo);
                    break;
                case STARTED_EVENT:
                    LOGGER.warn("adding new peer " + trackedPeerInfo);
                    trackedPeerInfosMap.put(trackedPeerInfo, new TrackedPeerStatus(trackedPeerInfo, event));
                    break;
                default:
                    failure(httpRequest, "invalid event", channel);
                    return;
                }
            }
        }
    }

    // compose tracker response
    responseDictionary.put("interval", REQUEST_INTERVAL_SECONDS);
    final List<Map<String, Object>> peerList = new ArrayList<>();
    final Iterator<TrackedPeerStatus> trackedPeerInfos_iter = trackedPeerInfosMap.values().iterator();
    try {
        LOGGER.warn("client peer id " + new String(peerIdBytes, "US-ASCII"));
    } catch (UnsupportedEncodingException ex) {
        throw new TexaiException(ex);
    }
    LOGGER.warn("tracked peers ...");
    while (trackedPeerInfos_iter.hasNext()) {
        final TrackedPeerStatus trackedPeerStatus = trackedPeerInfos_iter.next();
        final TrackedPeerInfo trackedPeerInfo1 = trackedPeerStatus.trackedPeerInfo;
        LOGGER.warn("");
        LOGGER.warn("    peer id    " + trackedPeerInfo1.toIDString());
        LOGGER.warn("    ip         " + trackedPeerInfo1.getInetAddress().getHostAddress());
        LOGGER.warn("    port       " + trackedPeerInfo1.getPort());
        if (trackedPeerStatus.peerExpirationMilliseconds < System.currentTimeMillis()) {
            LOGGER.warn("expiring peer " + trackedPeerInfo1);
            trackedPeerInfos_iter.remove();
        } else if (trackedPeerInfo1.equals(trackedPeerInfo)) {
            LOGGER.warn("omitting self-peer from the peer list");
        } else {
            final Map<String, Object> map = new HashMap<>();
            map.put("peer id", trackedPeerInfo1.getPeerIdBytes());
            map.put("ip", trackedPeerInfo1.getInetAddress().getHostAddress());
            map.put("port", trackedPeerInfo1.getPort());
            peerList.add(map);
        }
    }
    responseDictionary.put("peers", peerList);

    LOGGER.log(Level.DEBUG, "Tracker response: " + responseDictionary);
    NettyHTTPUtils.writeBinaryResponse(httpRequest, BEncoder.bencode(responseDictionary), channel, null); // sessionCookie
}

From source file:org.texai.torrent.TrackerTest.java

/**
 * Test of bit torrent tracker./*from w  ww  . j av a2s. c  o  m*/
 */
@Test
public void testTracker() {
    LOGGER.info("tracker");

    // configure the HTTP request handler by registering the tracker
    final HTTPRequestHandler httpRequestHandler = HTTPRequestHandler.getInstance();
    final Tracker tracker = new Tracker();
    tracker.addInfoHash(new String((new URLCodec()).encode(INFO_HASH)));
    httpRequestHandler.register(tracker);

    // configure the server channel pipeline factory
    final AbstractBitTorrentHandlerFactory bitTorrentHandlerFactory = new MockBitTorrentHandlerFactory();
    final AbstractHTTPRequestHandlerFactory httpRequestHandlerFactory = new HTTPRequestHandlerFactory();
    final X509SecurityInfo x509SecurityInfo = KeyStoreTestUtils.getServerX509SecurityInfo();
    final ChannelPipelineFactory channelPipelineFactory = new PortUnificationChannelPipelineFactory(null, // albusHCNMessageHandlerFactory,
            bitTorrentHandlerFactory, httpRequestHandlerFactory, x509SecurityInfo);

    // configure the server
    final ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    assertEquals("{}", serverBootstrap.getOptions().toString());
    serverBootstrap.setPipelineFactory(channelPipelineFactory);

    // bind and start to accept incoming connections
    serverBootstrap.bind(new InetSocketAddress("localhost", SERVER_PORT));

    // test tracker client
    httpClient();

    final Timer timer = new Timer();
    timer.schedule(new ShutdownTimerTask(), 5000);

    // shut down executor threads to exit
    LOGGER.info("releasing server resources");
    serverBootstrap.releaseExternalResources();
    timer.cancel();
}

From source file:org.texai.torrent.TrackerTest.java

/** Tests the HTTP request and response messages. */
@SuppressWarnings({ "ThrowableResultIgnored", "null" })
private void httpClient() {
    final ClientBootstrap clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // configure the client pipeline
    final Object clientResume_lock = new Object();
    final AbstractHTTPResponseHandler httpResponseHandler = new MockHTTPResponseHandler(clientResume_lock);
    final X509SecurityInfo x509SecurityInfo = KeyStoreTestUtils.getClientX509SecurityInfo();
    final ChannelPipeline channelPipeline = HTTPClientPipelineFactory.getPipeline(httpResponseHandler,
            x509SecurityInfo);/*ww w  .  j a  v a 2 s .  co  m*/
    clientBootstrap.setPipeline(channelPipeline);
    LOGGER.info("pipeline: " + channelPipeline.toString());

    // start the connection attempt
    ChannelFuture channelFuture = clientBootstrap.connect(new InetSocketAddress("localhost", SERVER_PORT));

    // wait until the connection attempt succeeds or fails
    final Channel channel = channelFuture.awaitUninterruptibly().getChannel();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }
    LOGGER.info("HTTP client connected");

    URI uri = null;
    HttpRequest httpRequest;
    String host;

    // send the statistics request
    try {
        uri = new URI("https://localhost:" + SERVER_PORT + "/torrent-tracker/statistics");
    } catch (URISyntaxException ex) {
        fail(ex.getMessage());
    }
    httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    host = uri.getHost() == null ? "localhost" : uri.getHost();
    httpRequest.setHeader(HttpHeaders.Names.HOST, host);
    httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    LOGGER.info("httpRequest ...\n" + httpRequest);
    channel.write(httpRequest);

    // wait for the request message to be sent
    channelFuture.awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }

    // send the scrape request
    try {
        uri = new URI("https://localhost:" + SERVER_PORT + "/torrent-tracker/scrape");
    } catch (URISyntaxException ex) {
        fail(ex.getMessage());
    }
    httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    host = uri.getHost() == null ? "localhost" : uri.getHost();
    httpRequest.setHeader(HttpHeaders.Names.HOST, host);
    httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    LOGGER.info("httpRequest ...\n" + httpRequest);
    channel.write(httpRequest);

    // wait for the request message to be sent
    channelFuture.awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }

    // send the announce request
    final byte[] myPeerIdBytes = { 0x14, 0x13, 0x12, 0x11, 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08,
            0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };
    final int nbrBytesUploaded = 0;
    final int nbrBytesDownloaded = 0;
    final int nbrBytesLeftToDownloaded = 1024;
    final String event = "started";
    final String myIPAddress = NetworkUtils.getLocalHostAddress().getHostAddress();
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("https://localhost:");
    stringBuilder.append(SERVER_PORT);
    stringBuilder.append("/torrent-tracker/announce");
    stringBuilder.append('?');
    stringBuilder.append("info_hash=");
    stringBuilder.append(new String((new URLCodec()).encode(INFO_HASH)));
    stringBuilder.append("&peer_id=");
    stringBuilder.append(new String((new URLCodec()).encode(myPeerIdBytes)));
    stringBuilder.append("&port=");
    stringBuilder.append(SERVER_PORT);
    stringBuilder.append("&uploaded=");
    stringBuilder.append(nbrBytesUploaded);
    stringBuilder.append("&downloaded=");
    stringBuilder.append(nbrBytesDownloaded);
    stringBuilder.append("&left=");
    stringBuilder.append(nbrBytesLeftToDownloaded);
    stringBuilder.append("&event=");
    stringBuilder.append(event);
    stringBuilder.append("&ip=");
    stringBuilder.append(myIPAddress);
    try {
        uri = new URI(stringBuilder.toString());
    } catch (URISyntaxException ex) {
        fail(ex.getMessage());
    }
    httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    host = uri.getHost() == null ? "localhost" : uri.getHost();
    httpRequest.setHeader(HttpHeaders.Names.HOST, host);
    httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    LOGGER.info("httpRequest ...\n" + httpRequest);
    channel.write(httpRequest);

    // wait for the request message to be sent
    channelFuture.awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }

    // the message response handler will signal this thread when the test exchanges are completed
    synchronized (clientResume_lock) {
        try {
            clientResume_lock.wait();
        } catch (InterruptedException ex) {
        }
    }
    LOGGER.info("releasing HTTP client resources");
    channel.close();
    clientBootstrap.releaseExternalResources();
}