Java Code Examples for libcore.io.IoUtils#closeQuietly()

The following examples show how to use libcore.io.IoUtils#closeQuietly() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Network.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private Socket connectToHost(String host, int port, SocketAddress localAddress)
        throws IOException {
    // Lookup addresses only on this Network.
    InetAddress[] hostAddresses = getAllByName(host);
    // Try all addresses.
    for (int i = 0; i < hostAddresses.length; i++) {
        try {
            Socket socket = createSocket();
            boolean failed = true;
            try {
                if (localAddress != null) socket.bind(localAddress);
                socket.connect(new InetSocketAddress(hostAddresses[i], port));
                failed = false;
                return socket;
            } finally {
                if (failed) IoUtils.closeQuietly(socket);
            }
        } catch (IOException e) {
            if (i == (hostAddresses.length - 1)) throw e;
        }
    }
    throw new UnknownHostException(host);
}
 
Example 2
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private UserData readUserLP(int id) {
    FileInputStream fis = null;
    try {
        AtomicFile userFile =
                new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
        fis = userFile.openRead();
        return readUserLP(id, fis);
    } catch (IOException ioe) {
        Slog.e(LOG_TAG, "Error reading user list");
    } catch (XmlPullParserException pe) {
        Slog.e(LOG_TAG, "Error reading user list");
    } finally {
        IoUtils.closeQuietly(fis);
    }
    return null;
}
 
Example 3
Source File: FileBridge.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    try {
        writeCommandAndBlock(CMD_CLOSE, "close()");
    } finally {
        IoBridge.closeAndSignalBlockedThreads(mClient);
        IoUtils.closeQuietly(mClientPfd);
    }
}
 
Example 4
Source File: ResourceCertificateSource.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void ensureInitialized() {
    synchronized (mLock) {
        if (mCertificates != null) {
            return;
        }
        Set<X509Certificate> certificates = new ArraySet<X509Certificate>();
        Collection<? extends Certificate> certs;
        InputStream in = null;
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            in = mContext.getResources().openRawResource(mResourceId);
            certs = factory.generateCertificates(in);
        } catch (CertificateException e) {
            throw new RuntimeException("Failed to load trust anchors from id " + mResourceId,
                    e);
        } finally {
            IoUtils.closeQuietly(in);
        }
        TrustedCertificateIndex indexLocal = new TrustedCertificateIndex();
        for (Certificate cert : certs) {
            certificates.add((X509Certificate) cert);
            indexLocal.index((X509Certificate) cert);
        }
        mCertificates = certificates;
        mIndex = indexLocal;
        mContext = null;
    }
}
 
Example 5
Source File: MediaStore.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static String getFilePath(ContentResolver resolver, Uri mediaUri)
        throws RemoteException {

    try (ContentProviderClient client =
                 resolver.acquireUnstableContentProviderClient(AUTHORITY)) {
        final Cursor c = client.query(
                mediaUri,
                new String[]{ MediaColumns.DATA },
                null, /* selection */
                null, /* selectionArg */
                null /* sortOrder */);

        final String path;
        try {
            if (c.getCount() == 0) {
                throw new IllegalStateException("Not found media file under URI: " + mediaUri);
            }

            if (!c.moveToFirst()) {
                throw new IllegalStateException("Failed to move cursor to the first item.");
            }

            path = c.getString(0);
        } finally {
            IoUtils.closeQuietly(c);
        }

        return path;
    }
}
 
Example 6
Source File: Network.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
        int localPort) throws IOException {
    Socket socket = createSocket();
    boolean failed = true;
    try {
        socket.bind(new InetSocketAddress(localAddress, localPort));
        socket.connect(new InetSocketAddress(address, port));
        failed = false;
    } finally {
        if (failed) IoUtils.closeQuietly(socket);
    }
    return socket;
}
 
Example 7
Source File: FileInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSkipInPipes() throws Exception {
    FileDescriptor[] pipe = Libcore.os.pipe();
    DataFeeder feeder = new DataFeeder(pipe[1]);
    try {
        feeder.start();
        FileInputStream fis = new FileInputStream(pipe[0]);
        fis.skip(SKIP_SIZE);
        verifyData(fis, SKIP_SIZE, TOTAL_SIZE - SKIP_SIZE);
        assertEquals(-1, fis.read());
        feeder.join(1000);
        assertFalse(feeder.isAlive());
    } finally {
        IoUtils.closeQuietly(pipe[0]);
    }
}
 
Example 8
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private ZenModeConfig readDefaultConfig(Resources resources) {
    XmlResourceParser parser = null;
    try {
        parser = resources.getXml(R.xml.default_zen_mode_config);
        while (parser.next() != XmlPullParser.END_DOCUMENT) {
            final ZenModeConfig config = ZenModeConfig.readXml(parser);
            if (config != null) return config;
        }
    } catch (Exception e) {
        Log.w(TAG, "Error reading default zen mode config from resource", e);
    } finally {
        IoUtils.closeQuietly(parser);
    }
    return new ZenModeConfig();
}
 
Example 9
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private void handleDumpService(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        Service s = mServices.get(info.token);
        if (s != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            s.dump(info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 10
Source File: Network.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    Socket socket = createSocket();
    boolean failed = true;
    try {
        socket.connect(new InetSocketAddress(host, port));
        failed = false;
    } finally {
        if (failed) IoUtils.closeQuietly(socket);
    }
    return socket;
}
 
Example 11
Source File: AtomicFile.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
public void write(Consumer<FileOutputStream> writeContent) {
    FileOutputStream out = null;
    try {
        out = startWrite();
        writeContent.accept(out);
        finishWrite(out);
    } catch (Throwable t) {
        failWrite(out);
        throw ExceptionUtils.propagate(t);
    } finally {
        IoUtils.closeQuietly(out);
    }
}
 
Example 12
Source File: ActivityThread.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private void handleDumpActivity(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        ActivityClientRecord r = mActivities.get(info.token);
        if (r != null && r.activity != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 13
Source File: DefaultSplitAssetLoader.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public void close() throws Exception {
    IoUtils.closeQuietly(mCachedAssetManager);
}
 
Example 14
Source File: SyncLogger.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@GuardedBy("mLock")
private void closeCurrentLogLocked() {
    IoUtils.closeQuietly(mLogWriter);
    mLogWriter = null;
}
 
Example 15
Source File: FingerprintsUserState.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void doWriteState() {
    AtomicFile destination = new AtomicFile(mFile);

    ArrayList<Fingerprint> fingerprints;

    synchronized (this) {
        fingerprints = getCopy(mFingerprints);
    }

    FileOutputStream out = null;
    try {
        out = destination.startWrite();

        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(out, "utf-8");
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.startDocument(null, true);
        serializer.startTag(null, TAG_FINGERPRINTS);

        final int count = fingerprints.size();
        for (int i = 0; i < count; i++) {
            Fingerprint fp = fingerprints.get(i);
            serializer.startTag(null, TAG_FINGERPRINT);
            serializer.attribute(null, ATTR_FINGER_ID, Integer.toString(fp.getFingerId()));
            serializer.attribute(null, ATTR_NAME, fp.getName().toString());
            serializer.attribute(null, ATTR_GROUP_ID, Integer.toString(fp.getGroupId()));
            serializer.attribute(null, ATTR_DEVICE_ID, Long.toString(fp.getDeviceId()));
            serializer.endTag(null, TAG_FINGERPRINT);
        }

        serializer.endTag(null, TAG_FINGERPRINTS);
        serializer.endDocument();
        destination.finishWrite(out);

        // Any error while writing is fatal.
    } catch (Throwable t) {
        Slog.wtf(TAG, "Failed to write settings, restoring backup", t);
        destination.failWrite(out);
        throw new IllegalStateException("Failed to write fingerprints", t);
    } finally {
        IoUtils.closeQuietly(out);
    }
}
 
Example 16
Source File: StrictJarFile.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * @param name of the archive (not necessarily a path).
 * @param fd seekable file descriptor for the JAR file.
 * @param verify whether to verify the file's JAR signatures and collect the corresponding
 *        signer certificates.
 * @param signatureSchemeRollbackProtectionsEnforced {@code true} to enforce protections against
 *        stripping newer signature schemes (e.g., APK Signature Scheme v2) from the file, or
 *        {@code false} to ignore any such protections. This parameter is ignored when
 *        {@code verify} is {@code false}.
 */
private StrictJarFile(String name,
        FileDescriptor fd,
        boolean verify,
        boolean signatureSchemeRollbackProtectionsEnforced)
                throws IOException, SecurityException {
    this.nativeHandle = nativeOpenJarFile(name, fd.getInt$());
    this.fd = fd;

    try {
        // Read the MANIFEST and signature files up front and try to
        // parse them. We never want to accept a JAR File with broken signatures
        // or manifests, so it's best to throw as early as possible.
        if (verify) {
            HashMap<String, byte[]> metaEntries = getMetaEntries();
            this.manifest = new StrictJarManifest(metaEntries.get(JarFile.MANIFEST_NAME), true);
            this.verifier =
                    new StrictJarVerifier(
                            name,
                            manifest,
                            metaEntries,
                            signatureSchemeRollbackProtectionsEnforced);
            Set<String> files = manifest.getEntries().keySet();
            for (String file : files) {
                if (findEntry(file) == null) {
                    throw new SecurityException("File " + file + " in manifest does not exist");
                }
            }

            isSigned = verifier.readCertificates() && verifier.isSignedJar();
        } else {
            isSigned = false;
            this.manifest = null;
            this.verifier = null;
        }
    } catch (IOException | SecurityException e) {
        nativeClose(this.nativeHandle);
        IoUtils.closeQuietly(fd);
        closed = true;
        throw e;
    }

    guard.open("close");
}
 
Example 17
Source File: DocumentBuilderImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override
public Document parse(InputSource source) throws SAXException, IOException {
    if (source == null) {
        throw new IllegalArgumentException("source == null");
    }

    String namespaceURI = null;
    String qualifiedName = null;
    DocumentType doctype = null;
    String inputEncoding = source.getEncoding();
    String systemId = source.getSystemId();
    DocumentImpl document = new DocumentImpl(
            dom, namespaceURI, qualifiedName, doctype, inputEncoding);
    document.setDocumentURI(systemId);

    KXmlParser parser = new KXmlParser();
    try {
        parser.keepNamespaceAttributes();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, namespaceAware);

        if (source.getByteStream() != null) {
            parser.setInput(source.getByteStream(), inputEncoding);
        } else if (source.getCharacterStream() != null) {
            parser.setInput(source.getCharacterStream());
        } else if (systemId != null) {
            URL url = new URL(systemId);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            // TODO: if null, extract the inputEncoding from the Content-Type header?
            parser.setInput(urlConnection.getInputStream(), inputEncoding);
        } else {
            throw new SAXParseException("InputSource needs a stream, reader or URI", null);
        }

        if (parser.nextToken() == XmlPullParser.END_DOCUMENT) {
            throw new SAXParseException("Unexpected end of document", null);
        }

        parse(parser, document, document, XmlPullParser.END_DOCUMENT);

        parser.require(XmlPullParser.END_DOCUMENT, null, null);
    } catch (XmlPullParserException ex) {
        if (ex.getDetail() instanceof IOException) {
            throw (IOException) ex.getDetail();
        }
        if (ex.getDetail() instanceof RuntimeException) {
            throw (RuntimeException) ex.getDetail();
        }

        LocatorImpl locator = new LocatorImpl();

        locator.setPublicId(source.getPublicId());
        locator.setSystemId(systemId);
        locator.setLineNumber(ex.getLineNumber());
        locator.setColumnNumber(ex.getColumnNumber());

        SAXParseException newEx = new SAXParseException(ex.getMessage(), locator);

        if (errorHandler != null) {
            errorHandler.error(newEx);
        }

        throw newEx;
    } finally {
        IoUtils.closeQuietly(parser);
    }

    return document;
}
 
Example 18
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public void close() throws Exception {
    IoUtils.closeQuietly(getFD());
}
 
Example 19
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Open a socket via the system server and bind it to the specified port (random if port=0).
 * This will return a PFD to the user that represent a bound UDP socket. The system server will
 * cache the socket and a record of its owner so that it can and must be freed when no longer
 * needed.
 */
@Override
public synchronized IpSecUdpEncapResponse openUdpEncapsulationSocket(int port, IBinder binder)
        throws RemoteException {
    if (port != 0 && (port < FREE_PORT_MIN || port > PORT_MAX)) {
        throw new IllegalArgumentException(
                "Specified port number must be a valid non-reserved UDP port");
    }
    checkNotNull(binder, "Null Binder passed to openUdpEncapsulationSocket");

    int callingUid = Binder.getCallingUid();
    UserRecord userRecord = mUserResourceTracker.getUserRecord(callingUid);
    final int resourceId = mNextResourceId++;
    FileDescriptor sockFd = null;
    try {
        if (!userRecord.mSocketQuotaTracker.isAvailable()) {
            return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
        }

        sockFd = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        mUidFdTagger.tag(sockFd, callingUid);

        // This code is common to both the unspecified and specified port cases
        Os.setsockoptInt(
                sockFd,
                OsConstants.IPPROTO_UDP,
                OsConstants.UDP_ENCAP,
                OsConstants.UDP_ENCAP_ESPINUDP);

        mSrvConfig.getNetdInstance().ipSecSetEncapSocketOwner(sockFd, callingUid);
        if (port != 0) {
            Log.v(TAG, "Binding to port " + port);
            Os.bind(sockFd, INADDR_ANY, port);
        } else {
            port = bindToRandomPort(sockFd);
        }

        userRecord.mEncapSocketRecords.put(
                resourceId,
                new RefcountedResource<EncapSocketRecord>(
                        new EncapSocketRecord(resourceId, sockFd, port), binder));
        return new IpSecUdpEncapResponse(IpSecManager.Status.OK, resourceId, port, sockFd);
    } catch (IOException | ErrnoException e) {
        IoUtils.closeQuietly(sockFd);
    }
    // If we make it to here, then something has gone wrong and we couldn't open a socket.
    // The only reasonable condition that would cause that is resource unavailable.
    return new IpSecUdpEncapResponse(IpSecManager.Status.RESOURCE_UNAVAILABLE);
}
 
Example 20
Source File: FileBridge.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public void forceClose() {
    IoUtils.closeQuietly(mTarget);
    IoUtils.closeQuietly(mServer);
    IoUtils.closeQuietly(mClient);
    mClosed = true;
}