All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.oracle.dio.utils.Utils Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2014, 2015,  Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package com.oracle.dio.utils;

import java.util.StringTokenizer;

import jdk.dio.DeviceConfig;
import jdk.dio.DevicePermission;

/**
 * Utility class for device permission class
 */
public final class Utils {

    public static final int EMPTY = 0;
    public static final int DECIMAL_DIGITS = 1;
    public static final int HEXADECIMAL_DIGITS = 2;
    public static final int HEXADECIMAL_DIGITS_INTERVAL = 3;
    /**
     * Checks if actions1 list "implies"
     * actions2 list
     *
     * @param actions1 comma-separated list of verified and valid
     *                 actions
     * @param actions1 comma-separated list of verified and valid
     *                 actions
     *
     * @return true actions2 list is implied by
     *         actions1 list
     */
    public static boolean implies(String actions1, String actions2) {
        int index = actions2.indexOf(",");
        if (index == -1) {
            return isIncluded(actions2, actions1);
        } else {
            return implies(actions1, actions2.substring(0, index)) &&
                   implies(actions1, actions2.substring(index+1));
        }
    }

    public static String[] getActionsList(String actions) {
        StringTokenizer tokez = new StringTokenizer(actions, ",", false);

        int count = tokez.countTokens();

        String[] actionsList = new String[count];

        for (int i = 0; i < count; i++) {
            actionsList[i] = tokez.nextToken();
        }
        return actionsList;
    }

    /**
     * Checks if given what is included to
     * where list
     *
     * @param what   string to compare
     * @param where  coma-separated string list to search at
     *
     * @return true if what contains in
     *         the list
     */
    private static boolean isIncluded(String what, String where) {
        StringTokenizer tokens = new StringTokenizer(where, ",");
        while (tokens.hasMoreElements()) {
            if (tokens.nextToken().equals(what)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return true for permission specified actions
     *
     * @param action for validation
     * @param normalizedList allowed actions list
     *
     * @return true for valid
     */
    private static boolean isValidAction(String actions, String normalizedList) {
        StringTokenizer tokez = new StringTokenizer(actions, ",", true);
        // detect first empty token
        boolean lastTokenIsComma = true;
        while (tokez.hasMoreElements()) {
            String action = tokez.nextToken();
            // special case for empty actions that are not returned by StringTokenizer.nextToken() by default
            if (action.equals(",")) {
                if (lastTokenIsComma) {
                    return false;
                } else {
                    lastTokenIsComma = true;
                    continue;
                }
            } else {
                lastTokenIsComma = false;
            }
            if (!isIncluded(action, normalizedList)) {
                return false;
            }
        }
        // detects last empty token as well
        return !lastTokenIsComma;
    }

    /**
     * Returns action list in spec required order
     *
     * @param actions unordered and unverified list
     * @param normalizedList allowed actions list in normalized form
     *
     * @return ordered list
     */
    public static String verifyAndOrderActions(String actions, String normalizedList) {
        if(actions == null){
            throw new IllegalArgumentException(
                ExceptionMessage.format(ExceptionMessage.DEVICE_NULL_ACTIONS)
            );
        }
        if(actions.length() == 0){
            throw new IllegalArgumentException(
                ExceptionMessage.format(ExceptionMessage.DEVICE_EMPTY_ACTIONS)
            );
        }

        if (!isValidAction(actions, normalizedList)) {
            throw new IllegalArgumentException(actions);
        }

        boolean comma = false;
        StringBuilder sb = new StringBuilder(30);
        StringTokenizer tokez = new StringTokenizer(normalizedList, ",");
        while (tokez.hasMoreElements()) {
            String validAction = tokez.nextToken();
            if (isIncluded(validAction, actions)) {
                if (comma) {
                    sb.append(',');
                }
                sb.append(validAction);
                comma = true;
            }
        }

        return sb.toString();
    }

    /**
     * Verifies and order given actions against
     * DevicePermission actions list
     *
     * @param actions unordered and unverified list
     *
     * @return ordered and verified list
     */
    public static String verifyAndOrderDeviceActions(String actions) {
        return verifyAndOrderActions(actions, DevicePermission.OPEN + "," + DevicePermission.POWER_MANAGE);
    }

    /**
     * Checks if given value is zero or positive
     *
     */
    public static void checkIntZeroOrPozitive(final int val) {
        if (DeviceConfig.UNASSIGNED >= val) {
            throw new IllegalArgumentException(Integer.toString(val));
        }
    }

    /**
     * Checks if given value is UNASSIGNED or zero or positive
     *
     */
    public static void checkIntValue(final int val) {
        if (DeviceConfig.UNASSIGNED > val) {
            throw new IllegalArgumentException(Integer.toString(val));
        }
    }

    /**
     * Checks if given value is greater than 0 or UNASSIGNED
     *
     */
    public static void checkGreaterThanZero(final int val) {
        if (DeviceConfig.UNASSIGNED != val && val < 1){
            throw new IllegalArgumentException(Integer.toString(val));
        }
    }

    /**
     * Checks if no NaN and positive value
     */
    public static void checkDoubleGreaterThanZero(double val) {
        if (Double.compare(val, 1.0d) < 0 || Double.compare(val, Double.NaN) == 0 || Double.compare(val, Double.POSITIVE_INFINITY) == 0) {
            throw new IllegalArgumentException(Double.toString(val));
        }
    }

    public static String[] parseDevicePermissionName(String name) {
        name = name.trim();
        String[] ret = new String[2];
        int idx = -1;
        while (-1 != (idx = name.indexOf(':', idx + 1))) {
            if (idx == 0 || '\\' != name.charAt(idx - 1)) {
                break;
            }
        }
        if (-1 == idx) {
            ret[0] = name;
            ret[1] = "";

        } else {
            ret[0] = name.substring(0, idx);
            ret[1] = name.substring(idx + 1);
        }
        return ret;
    }

    // type 0 - decimal digit
    // type 1 - hexadecimal digit
    // any other type - check empty string
    public static void checkDevicePermissionChannelFormat(String name, int type) {

        String channel = parseDevicePermissionName(name)[1];

        if (channel.equals("*") || channel.equals(""))
            return;

        switch(type) {
            //decimal digit
            case DECIMAL_DIGITS:
               if (!isNonNegativeNumber(channel, 10)) {
                    throw new IllegalArgumentException();
                }
                break;
            //hexadecimal digit
            case HEXADECIMAL_DIGITS:
                if (!isNonNegativeNumber(channel, 16)) {
                    throw new IllegalArgumentException();
                }
                break;
            case HEXADECIMAL_DIGITS_INTERVAL:
                if (!isNonNegativeNumberInterval(channel)) {
                    throw new IllegalArgumentException();
                }
                break;
            default:
               throw new IllegalArgumentException(name);
        }

    }

    /** Checks new requested scaled value range e.g. sampling interval range, pulse period range */
    public static void checkNewScaledRange(final double min_er,
                                        final double max_er,
                                        final double new_factor
                                        ) {
        // new scaled ones
        final double min_sr = min_er * new_factor;
        final double max_sr = max_er * new_factor;

        if (min_sr < 1.0d || max_sr > new Integer(Integer.MAX_VALUE).doubleValue())
            throw new IllegalArgumentException();
    }

    // Check all characters in the string are decimal digits
    private static boolean isNonNegativeNumber(String str, int radix) {
        try {
           return Integer.parseInt(str, radix) >= 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    // Check the string has format {hexadecimal}-{hexadecimal}
    private static boolean isNonNegativeNumberInterval(String str) {
        int len = str.length();
        int idx = str.indexOf('-');

        if (-1 == idx || (len - 1) <= idx) {
            return false;
        }
        try {
            return Long.parseLong(str.substring(0, idx), 16) >=0
                && Integer.parseInt(str.substring(idx + 1), 16) >= 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy