Java Code Examples for com.android.internal.util.Preconditions#checkArgument()

The following examples show how to use com.android.internal.util.Preconditions#checkArgument() . 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: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static byte[] toBytes(int persistentType, int userId, int qualityForUi,
        byte[] payload) {
    if (persistentType == PersistentData.TYPE_NONE) {
        Preconditions.checkArgument(payload == null,
                "TYPE_NONE must have empty payload");
        return null;
    }
    Preconditions.checkArgument(payload != null && payload.length > 0,
            "empty payload must only be used with TYPE_NONE");

    ByteArrayOutputStream os = new ByteArrayOutputStream(
            VERSION_1_HEADER_SIZE + payload.length);
    DataOutputStream dos = new DataOutputStream(os);
    try {
        dos.writeByte(PersistentData.VERSION_1);
        dos.writeByte(persistentType);
        dos.writeInt(userId);
        dos.writeInt(qualityForUi);
        dos.write(payload);
    } catch (IOException e) {
        throw new RuntimeException("ByteArrayOutputStream cannot throw IOException");
    }
    return os.toByteArray();
}
 
Example 2
Source File: RankingHelper.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void createNotificationChannel(String pkg, int uid, NotificationChannel channel,
        boolean fromTargetApp, boolean hasDndAccess) {
    Preconditions.checkNotNull(pkg);
    Preconditions.checkNotNull(channel);
    Preconditions.checkNotNull(channel.getId());
    Preconditions.checkArgument(!TextUtils.isEmpty(channel.getName()));
    Record r = getOrCreateRecord(pkg, uid);
    if (r == null) {
        throw new IllegalArgumentException("Invalid package");
    }
    if (channel.getGroup() != null && !r.groups.containsKey(channel.getGroup())) {
        throw new IllegalArgumentException("NotificationChannelGroup doesn't exist");
    }
    if (NotificationChannel.DEFAULT_CHANNEL_ID.equals(channel.getId())) {
        throw new IllegalArgumentException("Reserved id");
    }
    NotificationChannel existing = r.channels.get(channel.getId());
    // Keep most of the existing settings
    if (existing != null && fromTargetApp) {
        if (existing.isDeleted()) {
            existing.setDeleted(false);

            // log a resurrected channel as if it's new again
            MetricsLogger.action(getChannelLog(channel, pkg).setType(
                    MetricsProto.MetricsEvent.TYPE_OPEN));
        }

        existing.setName(channel.getName().toString());
        existing.setDescription(channel.getDescription());
        existing.setBlockableSystem(channel.isBlockableSystem());
        if (existing.getGroup() == null) {
            existing.setGroup(channel.getGroup());
        }

        // Apps are allowed to downgrade channel importance if the user has not changed any
        // fields on this channel yet.
        if (existing.getUserLockedFields() == 0 &&
                channel.getImportance() < existing.getImportance()) {
            existing.setImportance(channel.getImportance());
        }

        // system apps and dnd access apps can bypass dnd if the user hasn't changed any
        // fields on the channel yet
        if (existing.getUserLockedFields() == 0 && hasDndAccess) {
            boolean bypassDnd = channel.canBypassDnd();
            existing.setBypassDnd(bypassDnd);

            if (bypassDnd != mAreChannelsBypassingDnd) {
                updateChannelsBypassingDnd();
            }
        }

        updateConfig();
        return;
    }
    if (channel.getImportance() < IMPORTANCE_NONE
            || channel.getImportance() > NotificationManager.IMPORTANCE_MAX) {
        throw new IllegalArgumentException("Invalid importance level");
    }

    // Reset fields that apps aren't allowed to set.
    if (fromTargetApp && !hasDndAccess) {
        channel.setBypassDnd(r.priority == Notification.PRIORITY_MAX);
    }
    if (fromTargetApp) {
        channel.setLockscreenVisibility(r.visibility);
    }
    clearLockedFields(channel);
    if (channel.getLockscreenVisibility() == Notification.VISIBILITY_PUBLIC) {
        channel.setLockscreenVisibility(Ranking.VISIBILITY_NO_OVERRIDE);
    }
    if (!r.showBadge) {
        channel.setShowBadge(false);
    }

    r.channels.put(channel.getId(), channel);
    if (channel.canBypassDnd() != mAreChannelsBypassingDnd) {
        updateChannelsBypassingDnd();
    }
    MetricsLogger.action(getChannelLog(channel, pkg).setType(
            MetricsProto.MetricsEvent.TYPE_OPEN));
}
 
Example 3
Source File: AppFuseBridge.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public ParcelFileDescriptor addBridge(MountScope mountScope)
        throws FuseUnavailableMountException, NativeDaemonConnectorException {
    try {
        synchronized (this) {
            Preconditions.checkArgument(mScopes.indexOfKey(mountScope.mountId) < 0);
            if (mNativeLoop == 0) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final int fd = native_add_bridge(
                    mNativeLoop, mountScope.mountId, mountScope.open().detachFd());
            if (fd == -1) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final ParcelFileDescriptor result = ParcelFileDescriptor.adoptFd(fd);
            mScopes.put(mountScope.mountId, mountScope);
            mountScope = null;
            return result;
        }
    } finally {
        IoUtils.closeQuietly(mountScope);
    }
}
 
Example 4
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public Intent createShortcutResultIntent(String packageName, ShortcutInfo shortcut, int userId)
        throws RemoteException {
    Preconditions.checkNotNull(shortcut);
    Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
    verifyCaller(packageName, userId);
    verifyShortcutInfoPackage(packageName, shortcut);

    final Intent ret;
    synchronized (mLock) {
        throwIfUserLockedL(userId);

        // Send request to the launcher, if supported.
        ret = mShortcutRequestPinProcessor.createShortcutResultIntent(shortcut, userId);
    }

    verifyStates();
    return ret;
}
 
Example 5
Source File: RapporConfig.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for {@link RapporConfig}.
 *
 * @param encoderId      Unique id for encoder.
 * @param numBits        Number of bits to be encoded in Rappor algorithm.
 * @param probabilityF   Probability F that used in Rappor algorithm. This will be
 *                       quantized to the nearest 1/128.
 * @param probabilityP   Probability P that used in Rappor algorithm.
 * @param probabilityQ   Probability Q that used in Rappor algorithm.
 * @param numCohorts     Number of cohorts that used in Rappor algorithm.
 * @param numBloomHashes Number of bloom hashes that used in Rappor algorithm.
 */
public RapporConfig(String encoderId, int numBits, double probabilityF,
        double probabilityP, double probabilityQ, int numCohorts, int numBloomHashes) {
    Preconditions.checkArgument(!TextUtils.isEmpty(encoderId), "encoderId cannot be empty");
    this.mEncoderId = encoderId;
    Preconditions.checkArgument(numBits > 0, "numBits needs to be > 0");
    this.mNumBits = numBits;
    Preconditions.checkArgument(probabilityF >= 0 && probabilityF <= 1,
            "probabilityF must be in range [0.0, 1.0]");
    this.mProbabilityF = probabilityF;
    Preconditions.checkArgument(probabilityP >= 0 && probabilityP <= 1,
            "probabilityP must be in range [0.0, 1.0]");
    this.mProbabilityP = probabilityP;
    Preconditions.checkArgument(probabilityQ >= 0 && probabilityQ <= 1,
            "probabilityQ must be in range [0.0, 1.0]");
    this.mProbabilityQ = probabilityQ;
    Preconditions.checkArgument(numCohorts > 0, "numCohorts needs to be > 0");
    this.mNumCohorts = numCohorts;
    Preconditions.checkArgument(numBloomHashes > 0, "numBloomHashes needs to be > 0");
    this.mNumBloomHashes = numBloomHashes;
}
 
Example 6
Source File: SelectionActionModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private int countWordsForward(int from) {
    Preconditions.checkArgument(from <= mStartIndex);
    int wordCount = 0;
    int offset = from;
    while (offset < mStartIndex) {
        int end = mTokenIterator.following(offset);
        if (!isWhitespace(offset, end)) {
            wordCount++;
        }
        offset = end;
    }
    return wordCount;
}
 
Example 7
Source File: TextLinks.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new TextLink.
 *
 * @param start The start index of the identified subsequence
 * @param end The end index of the identified subsequence
 * @param entityScores A mapping of entity type to confidence score
 * @param urlSpan An optional URLSpan to delegate to. NOTE: Not parcelled
 *
 * @throws IllegalArgumentException if entityScores is null or empty
 */
TextLink(int start, int end, Map<String, Float> entityScores,
        @Nullable URLSpan urlSpan) {
    Preconditions.checkNotNull(entityScores);
    Preconditions.checkArgument(!entityScores.isEmpty());
    Preconditions.checkArgument(start <= end);
    mStart = start;
    mEnd = end;
    mEntityScores = new EntityConfidence(entityScores);
    mUrlSpan = urlSpan;
}
 
Example 8
Source File: ImageTransformation.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void addOptionInternal(@NonNull Pattern regex, @DrawableRes int resId,
        @Nullable CharSequence contentDescription) {
    throwIfDestroyed();

    Preconditions.checkNotNull(regex);
    Preconditions.checkArgument(resId != 0);

    mOptions.add(new Option(regex, resId, contentDescription));
}
 
Example 9
Source File: SmartSelectionEventTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Logs a selection event.
 *
 * @param event the selection event
 */
public void logEvent(@NonNull SelectionEvent event) {
    Preconditions.checkNotNull(event);

    if (event.mEventType != SelectionEvent.EventType.SELECTION_STARTED && mSessionId == null
            && DEBUG_LOG_ENABLED) {
        Log.d(LOG_TAG, "Selection session not yet started. Ignoring event");
        return;
    }

    final long now = System.currentTimeMillis();
    switch (event.mEventType) {
        case SelectionEvent.EventType.SELECTION_STARTED:
            mSessionId = startNewSession();
            Preconditions.checkArgument(event.mEnd == event.mStart + 1);
            mOrigStart = event.mStart;
            mSessionStartTime = now;
            break;
        case SelectionEvent.EventType.SMART_SELECTION_SINGLE:  // fall through
        case SelectionEvent.EventType.SMART_SELECTION_MULTI:
            mSmartSelectionTriggered = true;
            mModelName = getModelName(event);
            mSmartIndices[0] = event.mStart;
            mSmartIndices[1] = event.mEnd;
            break;
        case SelectionEvent.EventType.SELECTION_MODIFIED:  // fall through
        case SelectionEvent.EventType.AUTO_SELECTION:
            if (mPrevIndices[0] == event.mStart && mPrevIndices[1] == event.mEnd) {
                // Selection did not change. Ignore event.
                return;
            }
    }
    writeEvent(event, now);

    if (event.isTerminal()) {
        endSession();
    }
}
 
Example 10
Source File: AutofillServiceHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
static AutofillId[] assertValid(@Nullable AutofillId[] ids) {
    Preconditions.checkArgument(ids != null && ids.length > 0, "must have at least one id");
    // Can't use Preconditions.checkArrayElementsNotNull() because it throws NPE instead of IAE
    for (int i = 0; i < ids.length; ++i) {
        if (ids[i] == null) {
            throw new IllegalArgumentException("ids[" + i + "] must not be null");
        }
    }
    return ids;
}
 
Example 11
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Apply an active transport mode transform to a socket, which will apply the IPsec security
 * association as a correspondent policy to the provided socket
 */
@Override
public synchronized void applyTransportModeTransform(
        ParcelFileDescriptor socket, int direction, int resourceId) throws RemoteException {
    UserRecord userRecord = mUserResourceTracker.getUserRecord(Binder.getCallingUid());
    checkDirection(direction);
    // Get transform record; if no transform is found, will throw IllegalArgumentException
    TransformRecord info = userRecord.mTransformRecords.getResourceOrThrow(resourceId);

    // TODO: make this a function.
    if (info.pid != getCallingPid() || info.uid != getCallingUid()) {
        throw new SecurityException("Only the owner of an IpSec Transform may apply it!");
    }

    // Get config and check that to-be-applied transform has the correct mode
    IpSecConfig c = info.getConfig();
    Preconditions.checkArgument(
            c.getMode() == IpSecTransform.MODE_TRANSPORT,
            "Transform mode was not Transport mode; cannot be applied to a socket");

    mSrvConfig
            .getNetdInstance()
            .ipSecApplyTransportModeTransform(
                    socket.getFileDescriptor(),
                    resourceId,
                    direction,
                    c.getSourceAddress(),
                    c.getDestinationAddress(),
                    info.getSpiRecord().getSpi());
}
 
Example 12
Source File: ShortcutInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Throws if any of the mandatory fields is not set.
 *
 * @hide
 */
public void enforceMandatoryFields(boolean forPinned) {
    Preconditions.checkStringNotEmpty(mId, "Shortcut ID must be provided");
    if (!forPinned) {
        Preconditions.checkNotNull(mActivity, "Activity must be provided");
    }
    if (mTitle == null && mTitleResId == 0) {
        throw new IllegalArgumentException("Short label must be provided");
    }
    Preconditions.checkNotNull(mIntents, "Shortcut Intent must be provided");
    Preconditions.checkArgument(mIntents.length > 0, "Shortcut Intent must be provided");
}
 
Example 13
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean requestPinShortcut(String packageName, ShortcutInfo shortcut,
        IntentSender resultIntent, int userId) {
    Preconditions.checkNotNull(shortcut);
    Preconditions.checkArgument(shortcut.isEnabled(), "Shortcut must be enabled");
    return requestPinItem(packageName, userId, shortcut, null, null, resultIntent);
}
 
Example 14
Source File: TextUtils.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether or not the specified spanned text has a style span.
 * @hide
 */
public static boolean hasStyleSpan(@NonNull Spanned spanned) {
    Preconditions.checkArgument(spanned != null);
    final Class<?>[] styleClasses = {
            CharacterStyle.class, ParagraphStyle.class, UpdateAppearance.class};
    for (Class<?> clazz : styleClasses) {
        if (spanned.nextSpanTransition(-1, spanned.length(), clazz) < spanned.length()) {
            return true;
        }
    }
    return false;
}
 
Example 15
Source File: SQLiteDatabase.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the maximum number of milliseconds that SQLite connection is allowed to be idle
 * before it is closed and removed from the pool.
 *
 * @param idleConnectionTimeoutMs timeout in milliseconds. Use {@link Long#MAX_VALUE}
 * to allow unlimited idle connections.
 */
@NonNull
public Builder setIdleConnectionTimeout(
        @IntRange(from = 0) long idleConnectionTimeoutMs) {
    Preconditions.checkArgument(idleConnectionTimeoutMs >= 0,
            "idle connection timeout cannot be negative");
    mIdleConnectionTimeout = idleConnectionTimeoutMs;
    return this;
}
 
Example 16
Source File: LockSettingsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void setStringUnchecked(String key, int userId, String value) {
    Preconditions.checkArgument(userId != USER_FRP, "cannot store lock settings for FRP user");

    mStorage.writeKeyValue(key, value, userId);
    if (ArrayUtils.contains(SETTINGS_TO_BACKUP, key)) {
        BackupManager.dataChanged("com.android.providers.settings");
    }
}
 
Example 17
Source File: SelectionActionModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@UiThread
public void init(Supplier<TextClassifier> textClassifier, CharSequence text,
        int selectionStart, int selectionEnd, LocaleList locales) {
    mTextClassifier = Preconditions.checkNotNull(textClassifier);
    mText = Preconditions.checkNotNull(text).toString();
    mLastClassificationText = null; // invalidate.
    Preconditions.checkArgument(selectionEnd > selectionStart);
    mSelectionStart = selectionStart;
    mSelectionEnd = selectionEnd;
    mDefaultLocales = locales;
}
 
Example 18
Source File: FillEventHistory.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new event.
 *
 * @param eventType The type of the event
 * @param datasetId The dataset the event was on, or {@code null} if the event was on the
 *                  whole response.
 * @param clientState The client state associated with the event.
 * @param selectedDatasetIds The ids of datasets selected by the user.
 * @param ignoredDatasetIds The ids of datasets NOT select by the user.
 * @param changedFieldIds The ids of fields changed by the user.
 * @param changedDatasetIds The ids of the datasets that havd values matching the
 * respective entry on {@code changedFieldIds}.
 * @param manuallyFilledFieldIds The ids of fields that were manually entered by the user
 * and belonged to datasets.
 * @param manuallyFilledDatasetIds The ids of datasets that had values matching the
 * respective entry on {@code manuallyFilledFieldIds}.
 * @param detectedFieldClassifications the field classification matches.
 *
 * @throws IllegalArgumentException If the length of {@code changedFieldIds} and
 * {@code changedDatasetIds} doesn't match.
 * @throws IllegalArgumentException If the length of {@code manuallyFilledFieldIds} and
 * {@code manuallyFilledDatasetIds} doesn't match.
 *
 * @hide
 */
public Event(int eventType, @Nullable String datasetId, @Nullable Bundle clientState,
        @Nullable List<String> selectedDatasetIds,
        @Nullable ArraySet<String> ignoredDatasetIds,
        @Nullable ArrayList<AutofillId> changedFieldIds,
        @Nullable ArrayList<String> changedDatasetIds,
        @Nullable ArrayList<AutofillId> manuallyFilledFieldIds,
        @Nullable ArrayList<ArrayList<String>> manuallyFilledDatasetIds,
        @Nullable AutofillId[] detectedFieldIds,
        @Nullable FieldClassification[] detectedFieldClassifications) {
    mEventType = Preconditions.checkArgumentInRange(eventType, 0, TYPE_CONTEXT_COMMITTED,
            "eventType");
    mDatasetId = datasetId;
    mClientState = clientState;
    mSelectedDatasetIds = selectedDatasetIds;
    mIgnoredDatasetIds = ignoredDatasetIds;
    if (changedFieldIds != null) {
        Preconditions.checkArgument(!ArrayUtils.isEmpty(changedFieldIds)
                && changedDatasetIds != null
                && changedFieldIds.size() == changedDatasetIds.size(),
                "changed ids must have same length and not be empty");
    }
    mChangedFieldIds = changedFieldIds;
    mChangedDatasetIds = changedDatasetIds;
    if (manuallyFilledFieldIds != null) {
        Preconditions.checkArgument(!ArrayUtils.isEmpty(manuallyFilledFieldIds)
                && manuallyFilledDatasetIds != null
                && manuallyFilledFieldIds.size() == manuallyFilledDatasetIds.size(),
                "manually filled ids must have same length and not be empty");
    }
    mManuallyFilledFieldIds = manuallyFilledFieldIds;
    mManuallyFilledDatasetIds = manuallyFilledDatasetIds;

    mDetectedFieldIds = detectedFieldIds;
    mDetectedFieldClassifications = detectedFieldClassifications;
}
 
Example 19
Source File: Debug.java    From android_9.0.0_r45 with Apache License 2.0 3 votes vote down vote up
/**
 * Attach a library as a jvmti agent to the current runtime, with the given classloader
 * determining the library search path.
 * <p>
 * Note: agents may only be attached to debuggable apps. Otherwise, this function will
 * throw a SecurityException.
 *
 * @param library the library containing the agent.
 * @param options the options passed to the agent.
 * @param classLoader the classloader determining the library search path.
 *
 * @throws IOException if the agent could not be attached.
 * @throws SecurityException if the app is not debuggable.
 */
public static void attachJvmtiAgent(@NonNull String library, @Nullable String options,
        @Nullable ClassLoader classLoader) throws IOException {
    Preconditions.checkNotNull(library);
    Preconditions.checkArgument(!library.contains("="));

    if (options == null) {
        VMDebug.attachAgent(library, classLoader);
    } else {
        VMDebug.attachAgent(library + "=" + options, classLoader);
    }
}
 
Example 20
Source File: SelectionEvent.java    From android_9.0.0_r45 with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an event specifying an action taken on a selection.
 * Use when the user clicks on an action to act on the selected text.
 *
 * @param start  the start (inclusive) index of the selection
 * @param end  the end (exclusive) index of the selection
 * @param actionType  the action that was performed on the selection
 *
 * @throws IllegalArgumentException if end is less than start
 */
@NonNull
public static SelectionEvent createSelectionActionEvent(
        int start, int end, @SelectionEvent.ActionType int actionType) {
    Preconditions.checkArgument(end >= start, "end cannot be less than start");
    checkActionType(actionType);
    return new SelectionEvent(
            start, end, actionType, TextClassifier.TYPE_UNKNOWN, INVOCATION_UNKNOWN,
            NO_SIGNATURE);
}