Search in sources :

Example 71 with ProtocolException

use of java.net.ProtocolException in project jdk8u_jdk by JetBrains.

the class EmptyInputStream method getOutputStream0.

private synchronized OutputStream getOutputStream0() throws IOException {
    try {
        if (!doOutput) {
            throw new ProtocolException("cannot write to a URLConnection" + " if doOutput=false - call setDoOutput(true)");
        }
        if (method.equals("GET")) {
            // Backward compatibility
            method = "POST";
        }
        if ("TRACE".equals(method) && "http".equals(url.getProtocol())) {
            throw new ProtocolException("HTTP method TRACE" + " doesn't support output");
        }
        // if there's already an input stream open, throw an exception
        if (inputStream != null) {
            throw new ProtocolException("Cannot write output after reading input.");
        }
        if (!checkReuseConnection())
            connect();
        boolean expectContinue = false;
        String expects = requests.findValue("Expect");
        if ("100-Continue".equalsIgnoreCase(expects) && streaming()) {
            http.setIgnoreContinue(false);
            expectContinue = true;
        }
        if (streaming() && strOutputStream == null) {
            writeRequests();
        }
        if (expectContinue) {
            expect100Continue();
        }
        ps = (PrintStream) http.getOutputStream();
        if (streaming()) {
            if (strOutputStream == null) {
                if (chunkLength != -1) {
                    /* chunked */
                    strOutputStream = new StreamingOutputStream(new ChunkedOutputStream(ps, chunkLength), -1L);
                } else {
                    /* must be fixed content length */
                    long length = 0L;
                    if (fixedContentLengthLong != -1) {
                        length = fixedContentLengthLong;
                    } else if (fixedContentLength != -1) {
                        length = fixedContentLength;
                    }
                    strOutputStream = new StreamingOutputStream(ps, length);
                }
            }
            return strOutputStream;
        } else {
            if (poster == null) {
                poster = new PosterOutputStream();
            }
            return poster;
        }
    } catch (RuntimeException e) {
        disconnectInternal();
        throw e;
    } catch (ProtocolException e) {
        // Save the response code which may have been set while enforcing
        // the 100-continue. disconnectInternal() forces it to -1
        int i = responseCode;
        disconnectInternal();
        responseCode = i;
        throw e;
    } catch (IOException e) {
        disconnectInternal();
        throw e;
    }
}
Also used : ProtocolException(java.net.ProtocolException) ChunkedOutputStream(sun.net.www.http.ChunkedOutputStream) PosterOutputStream(sun.net.www.http.PosterOutputStream)

Example 72 with ProtocolException

use of java.net.ProtocolException in project android_frameworks_base by crdroidandroid.

the class NetworkStatsFactory method readNetworkStatsSummaryDev.

/**
     * Parse and return interface-level summary {@link NetworkStats} measured
     * using {@code /proc/net/dev} style hooks, which may include non IP layer
     * traffic. Values monotonically increase since device boot, and may include
     * details about inactive interfaces.
     *
     * @throws IllegalStateException when problem parsing stats.
     */
public NetworkStats readNetworkStatsSummaryDev() throws IOException {
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
    final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 6);
    final NetworkStats.Entry entry = new NetworkStats.Entry();
    ProcFileReader reader = null;
    try {
        reader = new ProcFileReader(new FileInputStream(mStatsXtIfaceAll));
        while (reader.hasMoreData()) {
            entry.iface = reader.nextString();
            entry.uid = UID_ALL;
            entry.set = SET_ALL;
            entry.tag = TAG_NONE;
            final boolean active = reader.nextInt() != 0;
            // always include snapshot values
            entry.rxBytes = reader.nextLong();
            entry.rxPackets = reader.nextLong();
            entry.txBytes = reader.nextLong();
            entry.txPackets = reader.nextLong();
            // fold in active numbers, but only when active
            if (active) {
                entry.rxBytes += reader.nextLong();
                entry.rxPackets += reader.nextLong();
                entry.txBytes += reader.nextLong();
                entry.txPackets += reader.nextLong();
            }
            stats.addValues(entry);
            reader.finishLine();
        }
    } catch (NullPointerException e) {
        throw new ProtocolException("problem parsing stats", e);
    } catch (NumberFormatException e) {
        throw new ProtocolException("problem parsing stats", e);
    } finally {
        IoUtils.closeQuietly(reader);
        StrictMode.setThreadPolicy(savedPolicy);
    }
    return stats;
}
Also used : StrictMode(android.os.StrictMode) ProcFileReader(com.android.internal.util.ProcFileReader) ProtocolException(java.net.ProtocolException) NetworkStats(android.net.NetworkStats) FileInputStream(java.io.FileInputStream)

Example 73 with ProtocolException

use of java.net.ProtocolException in project android_frameworks_base by crdroidandroid.

the class MediaHTTPConnection method seekTo.

private void seekTo(long offset) throws IOException {
    teardownConnection();
    try {
        int response;
        int redirectCount = 0;
        URL url = mURL;
        // do not use any proxy for localhost (127.0.0.1)
        boolean noProxy = isLocalHost(url);
        while (true) {
            if (noProxy) {
                mConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
            } else {
                mConnection = (HttpURLConnection) url.openConnection();
            }
            mConnection.setConnectTimeout(CONNECT_TIMEOUT_MS);
            // handle redirects ourselves if we do not allow cross-domain redirect
            mConnection.setInstanceFollowRedirects(mAllowCrossDomainRedirect);
            if (mHeaders != null) {
                for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
                    mConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (offset > 0) {
                mConnection.setRequestProperty("Range", "bytes=" + offset + "-");
            }
            response = mConnection.getResponseCode();
            if (response != HttpURLConnection.HTTP_MULT_CHOICE && response != HttpURLConnection.HTTP_MOVED_PERM && response != HttpURLConnection.HTTP_MOVED_TEMP && response != HttpURLConnection.HTTP_SEE_OTHER && response != HTTP_TEMP_REDIRECT) {
                // not a redirect, or redirect handled by HttpURLConnection
                break;
            }
            if (++redirectCount > MAX_REDIRECTS) {
                throw new NoRouteToHostException("Too many redirects: " + redirectCount);
            }
            String method = mConnection.getRequestMethod();
            if (response == HTTP_TEMP_REDIRECT && !method.equals("GET") && !method.equals("HEAD")) {
                // automatically redirect the request"
                throw new NoRouteToHostException("Invalid redirect");
            }
            String location = mConnection.getHeaderField("Location");
            if (location == null) {
                throw new NoRouteToHostException("Invalid redirect");
            }
            url = new URL(mURL, /* TRICKY: don't use url! */
            location);
            if (!url.getProtocol().equals("https") && !url.getProtocol().equals("http")) {
                throw new NoRouteToHostException("Unsupported protocol redirect");
            }
            boolean sameProtocol = mURL.getProtocol().equals(url.getProtocol());
            if (!mAllowCrossProtocolRedirect && !sameProtocol) {
                throw new NoRouteToHostException("Cross-protocol redirects are disallowed");
            }
            boolean sameHost = mURL.getHost().equals(url.getHost());
            if (!mAllowCrossDomainRedirect && !sameHost) {
                throw new NoRouteToHostException("Cross-domain redirects are disallowed");
            }
            if (response != HTTP_TEMP_REDIRECT) {
                // update effective URL, unless it is a Temporary Redirect
                mURL = url;
            }
        }
        if (mAllowCrossDomainRedirect) {
            // remember the current, potentially redirected URL if redirects
            // were handled by HttpURLConnection
            mURL = mConnection.getURL();
        }
        if (response == HttpURLConnection.HTTP_PARTIAL) {
            // Partial content, we cannot just use getContentLength
            // because what we want is not just the length of the range
            // returned but the size of the full content if available.
            String contentRange = mConnection.getHeaderField("Content-Range");
            mTotalSize = -1;
            if (contentRange != null) {
                // format is "bytes xxx-yyy/zzz
                // where "zzz" is the total number of bytes of the
                // content or '*' if unknown.
                int lastSlashPos = contentRange.lastIndexOf('/');
                if (lastSlashPos >= 0) {
                    String total = contentRange.substring(lastSlashPos + 1);
                    try {
                        mTotalSize = Long.parseLong(total);
                    } catch (NumberFormatException e) {
                    }
                }
            }
        } else if (response != HttpURLConnection.HTTP_OK) {
            throw new IOException();
        } else {
            mTotalSize = mConnection.getContentLength();
        }
        if (offset > 0 && response != HttpURLConnection.HTTP_PARTIAL) {
            // data from the start of the content.
            throw new ProtocolException();
        }
        mInputStream = new BufferedInputStream(mConnection.getInputStream());
        mCurrentOffset = offset;
    } catch (IOException e) {
        mTotalSize = -1;
        mInputStream = null;
        mConnection = null;
        mCurrentOffset = -1;
        throw e;
    }
}
Also used : ProtocolException(java.net.ProtocolException) BufferedInputStream(java.io.BufferedInputStream) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) NoRouteToHostException(java.net.NoRouteToHostException) URL(java.net.URL)

Example 74 with ProtocolException

use of java.net.ProtocolException in project android_frameworks_base by crdroidandroid.

the class NetworkStatsCollection method readLegacyUid.

@Deprecated
public void readLegacyUid(File file, boolean onlyTags) throws IOException {
    final AtomicFile inputFile = new AtomicFile(file);
    DataInputStream in = null;
    try {
        in = new DataInputStream(new BufferedInputStream(inputFile.openRead()));
        // verify file magic header intact
        final int magic = in.readInt();
        if (magic != FILE_MAGIC) {
            throw new ProtocolException("unexpected magic: " + magic);
        }
        final int version = in.readInt();
        switch(version) {
            case VERSION_UID_INIT:
                {
                    // mapping into NetworkIdentitySet.
                    break;
                }
            case VERSION_UID_WITH_IDENT:
                {
                    // for a short time.
                    break;
                }
            case VERSION_UID_WITH_TAG:
            case VERSION_UID_WITH_SET:
                {
                    // uid := size *(NetworkIdentitySet size *(uid set tag NetworkStatsHistory))
                    final int identSize = in.readInt();
                    for (int i = 0; i < identSize; i++) {
                        final NetworkIdentitySet ident = new NetworkIdentitySet(in);
                        final int size = in.readInt();
                        for (int j = 0; j < size; j++) {
                            final int uid = in.readInt();
                            final int set = (version >= VERSION_UID_WITH_SET) ? in.readInt() : SET_DEFAULT;
                            final int tag = in.readInt();
                            final Key key = new Key(ident, uid, set, tag);
                            final NetworkStatsHistory history = new NetworkStatsHistory(in);
                            if ((tag == TAG_NONE) != onlyTags) {
                                recordHistory(key, history);
                            }
                        }
                    }
                    break;
                }
            default:
                {
                    throw new ProtocolException("unexpected version: " + version);
                }
        }
    } catch (FileNotFoundException e) {
    // missing stats is okay, probably first boot
    } finally {
        IoUtils.closeQuietly(in);
    }
}
Also used : ProtocolException(java.net.ProtocolException) AtomicFile(android.util.AtomicFile) BufferedInputStream(java.io.BufferedInputStream) FileNotFoundException(java.io.FileNotFoundException) NetworkStatsHistory(android.net.NetworkStatsHistory) DataInputStream(java.io.DataInputStream)

Example 75 with ProtocolException

use of java.net.ProtocolException in project android_frameworks_base by crdroidandroid.

the class UsageStatsXmlV1 method loadEvent.

private static void loadEvent(XmlPullParser parser, IntervalStats statsOut) throws XmlPullParserException, IOException {
    final String packageName = XmlUtils.readStringAttribute(parser, PACKAGE_ATTR);
    if (packageName == null) {
        throw new ProtocolException("no " + PACKAGE_ATTR + " attribute present");
    }
    final String className = XmlUtils.readStringAttribute(parser, CLASS_ATTR);
    final UsageEvents.Event event = statsOut.buildEvent(packageName, className);
    // Apply the offset to the beginTime to find the absolute time of this event.
    event.mTimeStamp = statsOut.beginTime + XmlUtils.readLongAttribute(parser, TIME_ATTR);
    event.mEventType = XmlUtils.readIntAttribute(parser, TYPE_ATTR);
    switch(event.mEventType) {
        case UsageEvents.Event.CONFIGURATION_CHANGE:
            event.mConfiguration = new Configuration();
            Configuration.readXmlAttrs(parser, event.mConfiguration);
            break;
        case UsageEvents.Event.SHORTCUT_INVOCATION:
            final String id = XmlUtils.readStringAttribute(parser, SHORTCUT_ID_ATTR);
            event.mShortcutId = (id != null) ? id.intern() : null;
            break;
    }
    if (statsOut.events == null) {
        statsOut.events = new TimeSparseArray<>();
    }
    statsOut.events.put(event.mTimeStamp, event);
}
Also used : ProtocolException(java.net.ProtocolException) Configuration(android.content.res.Configuration) UsageEvents(android.app.usage.UsageEvents)

Aggregations

ProtocolException (java.net.ProtocolException)143 IOException (java.io.IOException)34 HttpURLConnection (java.net.HttpURLConnection)26 URL (java.net.URL)24 FileInputStream (java.io.FileInputStream)19 NetworkStats (android.net.NetworkStats)18 NetworkStatsHistory (android.net.NetworkStatsHistory)18 StrictMode (android.os.StrictMode)18 ProcFileReader (com.android.internal.util.ProcFileReader)18 BufferedInputStream (java.io.BufferedInputStream)17 FileNotFoundException (java.io.FileNotFoundException)17 AtomicFile (android.util.AtomicFile)12 DataInputStream (java.io.DataInputStream)12 Test (org.junit.Test)12 InputStream (java.io.InputStream)11 OutputStream (java.io.OutputStream)11 MalformedURLException (java.net.MalformedURLException)11 Map (java.util.Map)11 BufferedReader (java.io.BufferedReader)10 InputStreamReader (java.io.InputStreamReader)10