Example usage for java.net HttpURLConnection HTTP_PARTIAL

List of usage examples for java.net HttpURLConnection HTTP_PARTIAL

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_PARTIAL.

Prototype

int HTTP_PARTIAL

To view the source code for java.net HttpURLConnection HTTP_PARTIAL.

Click Source Link

Document

HTTP Status-Code 206: Partial Content.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_PARTIAL);
}

From source file:org.opendaylight.lispflowmapping.neutron.LispNeutronSubnetHandler.java

@Override
public int canCreateSubnet(NeutronSubnet subnet) {
    LOG.info(/*from w  w  w. j av a  2  s  .c  o m*/
            "Neutron canCreateSubnet : Subnet name: " + subnet.getName() + " Subnet Cidr: " + subnet.getCidr());
    LOG.debug("Lisp Neutron Subnet: " + subnet.toString());
    if (SIX.equals(subnet.getIpVersion())) {
        return HttpURLConnection.HTTP_PARTIAL;
    }
    return HttpURLConnection.HTTP_OK;
}

From source file:com.datos.vfs.provider.http.HttpRandomAccessContent.java

@Override
protected DataInputStream getDataInputStream() throws IOException {
    if (dis != null) {
        return dis;
    }/* ww w  .  j  ava  2 s. com*/

    final GetMethod getMethod = new GetMethod();
    fileObject.setupMethod(getMethod);
    getMethod.setRequestHeader("Range", "bytes=" + filePointer + "-");
    final int status = fileSystem.getClient().executeMethod(getMethod);
    if (status != HttpURLConnection.HTTP_PARTIAL && status != HttpURLConnection.HTTP_OK) {
        throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(),
                Long.valueOf(filePointer), Integer.valueOf(status));
    }

    mis = new HttpFileObject.HttpInputStream(getMethod);
    // If the range request was ignored
    if (status == HttpURLConnection.HTTP_OK) {
        final long skipped = mis.skip(filePointer);
        if (skipped != filePointer) {
            throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(),
                    Long.valueOf(filePointer), Integer.valueOf(status));
        }
    }
    dis = new DataInputStream(new FilterInputStream(mis) {
        @Override
        public int read() throws IOException {
            final int ret = super.read();
            if (ret > -1) {
                filePointer++;
            }
            return ret;
        }

        @Override
        public int read(final byte[] b) throws IOException {
            final int ret = super.read(b);
            if (ret > -1) {
                filePointer += ret;
            }
            return ret;
        }

        @Override
        public int read(final byte[] b, final int off, final int len) throws IOException {
            final int ret = super.read(b, off, len);
            if (ret > -1) {
                filePointer += ret;
            }
            return ret;
        }
    });

    return dis;
}

From source file:com.adaptris.http.HttpClientTransport.java

/**
 * Is the HTTP response code considered to be a success.
 * <p>//from   w  ww .j  av  a  2 s .  c o m
 * There are 7 possible HTTP codes that signify success or partial success :-
 * <code>200,201,202,203,204,205,206</code>
 * </p>
 * 
 * @return true if the transaction was successful.
 */
private boolean wasSuccessful(HttpSession session) {

    boolean rc = false;
    switch (session.getResponseLine().getResponseCode()) {
    case HttpURLConnection.HTTP_ACCEPTED:
    case HttpURLConnection.HTTP_CREATED:
    case HttpURLConnection.HTTP_NO_CONTENT:
    case HttpURLConnection.HTTP_NOT_AUTHORITATIVE:
    case HttpURLConnection.HTTP_OK:
    case HttpURLConnection.HTTP_PARTIAL:
    case HttpURLConnection.HTTP_RESET: {
        rc = true;
        break;
    }
    default: {
        rc = false;
        break;
    }
    }
    return rc;
}

From source file:com.tonyodev.fetch.FetchRunnable.java

@Override
public void run() {

    try {//from  ww  w.  j a v a  2 s  .  co  m

        setHttpConnectionPrefs();
        Utils.createFileOrThrow(filePath);

        downloadedBytes = Utils.getFileSize(filePath);
        progress = Utils.getProgress(downloadedBytes, fileSize);
        databaseHelper.updateFileBytes(id, downloadedBytes, fileSize);

        httpURLConnection.setRequestProperty("Range", "bytes=" + downloadedBytes + "-");

        if (isInterrupted()) {
            throw new DownloadInterruptedException("DIE", ErrorUtils.DOWNLOAD_INTERRUPTED);
        }

        httpURLConnection.connect();
        int responseCode = httpURLConnection.getResponseCode();

        if (isResponseOk(responseCode)) {

            if (isInterrupted()) {
                throw new DownloadInterruptedException("DIE", ErrorUtils.DOWNLOAD_INTERRUPTED);
            }

            if (fileSize < 1) {
                setContentLength();
                databaseHelper.updateFileBytes(id, downloadedBytes, fileSize);
                progress = Utils.getProgress(downloadedBytes, fileSize);
            }

            output = new RandomAccessFile(filePath, "rw");
            if (responseCode == HttpURLConnection.HTTP_PARTIAL) {
                output.seek(downloadedBytes);
            } else {
                output.seek(0);
            }

            input = new BufferedInputStream(httpURLConnection.getInputStream());
            writeToFileAndPost();

            databaseHelper.updateFileBytes(id, downloadedBytes, fileSize);

            if (isInterrupted()) {
                throw new DownloadInterruptedException("DIE", ErrorUtils.DOWNLOAD_INTERRUPTED);

            } else if (downloadedBytes >= fileSize && !isInterrupted()) {

                if (fileSize < 1) {
                    fileSize = Utils.getFileSize(filePath);
                    databaseHelper.updateFileBytes(id, downloadedBytes, fileSize);
                    progress = Utils.getProgress(downloadedBytes, fileSize);
                } else {
                    progress = Utils.getProgress(downloadedBytes, fileSize);
                }

                boolean updated = databaseHelper.updateStatus(id, FetchConst.STATUS_DONE,
                        FetchConst.DEFAULT_EMPTY_VALUE);

                if (updated) {

                    Utils.sendEventUpdate(broadcastManager, id, FetchConst.STATUS_DONE, progress,
                            downloadedBytes, fileSize, FetchConst.DEFAULT_EMPTY_VALUE);
                }
            }

        } else {
            throw new IllegalStateException("SSRV:" + responseCode);
        }

    } catch (Exception exception) {

        if (loggingEnabled) {
            exception.printStackTrace();
        }

        int error = ErrorUtils.getCode(exception.getMessage());

        if (canRetry(error)) {

            boolean updated = databaseHelper.updateStatus(id, FetchConst.STATUS_QUEUED,
                    FetchConst.DEFAULT_EMPTY_VALUE);

            if (updated) {
                Utils.sendEventUpdate(broadcastManager, id, FetchConst.STATUS_QUEUED, progress, downloadedBytes,
                        fileSize, FetchConst.DEFAULT_EMPTY_VALUE);
            }

        } else {

            boolean updated = databaseHelper.updateStatus(id, FetchConst.STATUS_ERROR, error);

            if (updated) {
                Utils.sendEventUpdate(broadcastManager, id, FetchConst.STATUS_ERROR, progress, downloadedBytes,
                        fileSize, error);
            }
        }

    } finally {
        release();
        broadcastDone();
    }
}

From source file:org.apache.hadoop.fs.azure.metrics.ResponseReceivedMetricUpdater.java

/**
 * Handle the response-received event from Azure SDK.
 *//*from w w w.jav a  2s  .c o  m*/
@Override
public void eventOccurred(ResponseReceivedEvent eventArg) {
    instrumentation.webResponse();
    if (!(eventArg.getConnectionObject() instanceof HttpURLConnection)) {
        // Typically this shouldn't happen, but just let it pass
        return;
    }
    HttpURLConnection connection = (HttpURLConnection) eventArg.getConnectionObject();
    RequestResult currentResult = eventArg.getRequestResult();
    if (currentResult == null) {
        // Again, typically shouldn't happen, but let it pass
        return;
    }

    long requestLatency = currentResult.getStopDate().getTime() - currentResult.getStartDate().getTime();

    if (currentResult.getStatusCode() == HttpURLConnection.HTTP_CREATED
            && connection.getRequestMethod().equalsIgnoreCase("PUT")) {
        // If it's a PUT with an HTTP_CREATED status then it's a successful
        // block upload.
        long length = getRequestContentLength(connection);
        if (length > 0) {
            blockUploadGaugeUpdater.blockUploaded(currentResult.getStartDate(), currentResult.getStopDate(),
                    length);
            instrumentation.rawBytesUploaded(length);
            instrumentation.blockUploaded(requestLatency);
        }
    } else if (currentResult.getStatusCode() == HttpURLConnection.HTTP_PARTIAL
            && connection.getRequestMethod().equalsIgnoreCase("GET")) {
        // If it's a GET with an HTTP_PARTIAL status then it's a successful
        // block download.
        long length = getResponseContentLength(connection);
        if (length > 0) {
            blockUploadGaugeUpdater.blockDownloaded(currentResult.getStartDate(), currentResult.getStopDate(),
                    length);
            instrumentation.rawBytesDownloaded(length);
            instrumentation.blockDownloaded(requestLatency);
        }
    }
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Searches for the ZIP central directory.
 *
 * @param length/*ww  w .j a v a 2  s .c o m*/
 *     The content length of the file to search.
 *
 * @return {@code true} if central directory was found and parsed, otherwise {@code false}
 */
private boolean findCentralDirectory(int length) {
    HttpURLConnection conn = null;
    InputStream bis = null;

    long start = length - 4096;
    long end = length - 1;
    byte[] data = new byte[2048];

    try {
        conn = openConnection();
        conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
        conn.setInstanceFollowRedirects(true);
        conn.connect();

        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
            throw new IOException("Unexpected HTTP server response: " + responseCode);
        }

        bis = conn.getInputStream();
        int read, bytes = 0;
        while ((read = bis.read(data)) != -1) {
            bytes += read;
        }

        log("Read " + bytes + " bytes");

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        close(bis);
        disconnect(conn);
    }

    return parseEndOfCentralDirectory(data);
}

From source file:com.tonyodev.fetch.FetchRunnable.java

private boolean isResponseOk(int responseCode) {

    switch (responseCode) {
    case HttpURLConnection.HTTP_OK:
    case HttpURLConnection.HTTP_PARTIAL:
    case HttpURLConnection.HTTP_ACCEPTED:
        return true;
    default://from  ww w  . ja v  a2 s. c  om
        return false;
    }
}

From source file:guru.benson.pinch.Pinch.java

/**
 * Gets the list of files included in the ZIP stored on the HTTP server.
 *
 * @return A list of ZIP entries./*  w ww .j av a 2  s .c  o  m*/
 */
public ArrayList<ExtendedZipEntry> parseCentralDirectory() {
    int contentLength = getHttpFileSize();
    if (contentLength <= 0) {
        return null;
    }

    if (!findCentralDirectory(contentLength)) {
        return null;
    }

    HttpURLConnection conn = null;
    InputStream bis = null;

    long start = centralDirectoryOffset;
    long end = start + centralDirectorySize - 1;

    byte[] data = new byte[2048];
    ByteBuffer buf = ByteBuffer.allocate(centralDirectorySize);

    try {
        conn = openConnection();
        conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
        conn.setInstanceFollowRedirects(true);
        conn.connect();

        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_PARTIAL) {
            throw new IOException("Unexpected HTTP server response: " + responseCode);
        }

        bis = conn.getInputStream();
        int read, bytes = 0;
        while ((read = bis.read(data)) != -1) {
            buf.put(data, 0, read);
            bytes += read;
        }

        log("Central directory is " + bytes + " bytes");

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        close(bis);
        disconnect(conn);
    }

    return parseHeaders(buf);
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

public String executeVSIFLaunch(String[] vsifs, String url, boolean requireAuth, String user, String password,
        BuildProgressLogger logger, boolean dynamicUserId, String buildID, String workPlacePath)
        throws Exception {

    boolean notInTestMode = true;
    if (logger == null) {
        notInTestMode = false;/*from w  w  w .  j  av  a 2 s  . c o  m*/
    }

    String apiURL = url + "/rest/sessions/launch";

    for (int i = 0; i < vsifs.length; i++) {

        if (notInTestMode) {
            logger.message("vManager vAPI - Trying to launch vsif file: '" + vsifs[i] + "'");
        }
        String input = "{\"vsif\":\"" + vsifs[i] + "\"}";
        HttpURLConnection conn = getVAPIConnection(apiURL, requireAuth, user, password, "POST", dynamicUserId,
                buildID, workPlacePath, logger);
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK
                && conn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT
                && conn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED
                && conn.getResponseCode() != HttpURLConnection.HTTP_CREATED
                && conn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL
                && conn.getResponseCode() != HttpURLConnection.HTTP_RESET) {
            String reason = "";
            if (conn.getResponseCode() == 503)
                reason = "vAPI process failed to connect to remote vManager server.";
            if (conn.getResponseCode() == 401)
                reason = "Authentication Error";
            if (conn.getResponseCode() == 412)
                reason = "vAPI requires vManager 'Integration Server' license.";
            if (conn.getResponseCode() == 406)
                reason = "VSIF file '" + vsifs[i]
                        + "' was not found on file system, or is not accessed by the vAPI process.";
            String errorMessage = "Failed : HTTP error code : " + conn.getResponseCode() + " (" + reason + ")";
            if (notInTestMode) {
                logger.message(errorMessage);
                logger.message(conn.getResponseMessage());

                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

                StringBuilder result = new StringBuilder();
                String output;
                while ((output = br.readLine()) != null) {
                    result.append(output);
                }
                logger.message(result.toString());

            }

            System.out.println(errorMessage);
            return errorMessage;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder result = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null) {
            result.append(output);
        }

        conn.disconnect();

        JSONObject tmp = JSONObject.fromObject(result.toString());

        String textOut = "Session Launch Success: Session ID: " + tmp.getString("value");

        if (notInTestMode) {
            logger.message(textOut);
        } else {

            System.out.println(textOut);
        }

    }

    return "success";
}