javatips.net counter

Java Examples for java.security.InvalidParameterException

The following java examples will help you to understand the usage of java.security.InvalidParameterException. These source code samples are taken from different open source projects.

Example 1
Project: Yhb-2.0-master  File: SimpleMonthView.java View source code
public void setMonthParams(HashMap<String, Integer> params) {
    if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {
        throw new InvalidParameterException("You must specify month and year for this view");
    }
    setTag(params);
    if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
        mRowHeight = params.get(VIEW_PARAMS_HEIGHT);
        if (mRowHeight < MIN_HEIGHT) {
            mRowHeight = MIN_HEIGHT;
        }
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_DAY)) {
        mSelectedBeginDay = params.get(VIEW_PARAMS_SELECTED_BEGIN_DAY);
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_DAY)) {
        mSelectedLastDay = params.get(VIEW_PARAMS_SELECTED_LAST_DAY);
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_MONTH)) {
        mSelectedBeginMonth = params.get(VIEW_PARAMS_SELECTED_BEGIN_MONTH);
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_MONTH)) {
        mSelectedLastMonth = params.get(VIEW_PARAMS_SELECTED_LAST_MONTH);
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_YEAR)) {
        mSelectedBeginYear = params.get(VIEW_PARAMS_SELECTED_BEGIN_YEAR);
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_YEAR)) {
        mSelectedLastYear = params.get(VIEW_PARAMS_SELECTED_LAST_YEAR);
    }
    mMonth = params.get(VIEW_PARAMS_MONTH);
    mYear = params.get(VIEW_PARAMS_YEAR);
    mHasToday = false;
    mToday = -1;
    mCalendar.set(Calendar.MONTH, mMonth);
    mCalendar.set(Calendar.YEAR, mYear);
    mCalendar.set(Calendar.DAY_OF_MONTH, 1);
    mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);
    if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
        mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
    } else {
        mWeekStart = mCalendar.getFirstDayOfWeek();
    }
    mNumCells = CalendarUtils.getDaysInMonth(mMonth, mYear);
    for (int i = 0; i < mNumCells; i++) {
        final int day = i + 1;
        if (sameDay(day, today)) {
            mHasToday = true;
            mToday = day;
        }
        mIsPrev = prevDay(day, today);
    }
    mNumRows = calculateNumRows();
}
Example 2
Project: openjdk-master  File: TestDSAGenParameterSpec.java View source code
private static void testDSAGenParameterSpec(DataTuple dataTuple) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
    System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n", dataTuple.primePLen, dataTuple.subprimeQLen);
    AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME, PROVIDER_NAME);
    DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
    // genParamSpec will be null if IllegalAE is thrown when expected.
    if (genParamSpec == null) {
        return;
    }
    try {
        apg.init(genParamSpec, null);
        AlgorithmParameters param = apg.generateParameters();
        checkParam(param, genParamSpec);
        System.out.println("Test case passed");
    } catch (InvalidParameterException ipe) {
        throw new RuntimeException("Test case failed.", ipe);
    }
}
Example 3
Project: sslcertx-master  File: DecompressInputStream.java View source code
@Override
public int read(byte[] bytes, int off, int len) throws IOException {
    if (len == 0 || off < 0 || bytes == null)
        throw new InvalidParameterException();
    if (remainingBytes == 0) {
        nextPacket();
    }
    int ret;
    int bytesToRead = Math.min(remainingBytes, len);
    if (doDecompress) {
        ret = decompressedByteStream.read(bytes, off, bytesToRead);
    } else {
        ret = baseStream.read(bytes, off, bytesToRead);
    }
    if (ret <= 0) {
        throw new EOFException("got " + ret + "bytes, bytesToRead = " + bytesToRead);
    }
    remainingBytes -= ret;
    return ret;
}
Example 4
Project: android_platform_libcore-master  File: OpenSSLCipher.java View source code
private void engineInitInternal(int opmode, Key key, byte[] iv) throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) {
        encrypting = true;
    } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) {
        encrypting = false;
    } else {
        throw new InvalidParameterException("Unsupported opmode " + opmode);
    }
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Only SecretKey is supported");
    }
    final byte[] encodedKey = key.getEncoded();
    if (encodedKey == null) {
        throw new InvalidKeyException("key.getEncoded() == null");
    }
    checkSupportedKeySize(encodedKey.length);
    final int cipherType = NativeCrypto.EVP_get_cipherbyname(getCipherName(encodedKey.length, mode));
    if (cipherType == 0) {
        throw new InvalidAlgorithmParameterException("Cannot find name for key length = " + (encodedKey.length * 8) + " and mode = " + mode);
    }
    final int ivLength = NativeCrypto.EVP_CIPHER_iv_length(cipherType);
    if (iv == null) {
        iv = new byte[ivLength];
    } else if (iv.length != ivLength) {
        throw new InvalidAlgorithmParameterException("expected IV length of " + ivLength);
    }
    this.iv = iv;
    NativeCrypto.EVP_CipherInit_ex(cipherCtx.getContext(), cipherType, encodedKey, iv, encrypting);
    // OpenSSL only supports PKCS5 Padding.
    NativeCrypto.EVP_CIPHER_CTX_set_padding(cipherCtx.getContext(), padding == Padding.PKCS5PADDING);
    modeBlockSize = NativeCrypto.EVP_CIPHER_CTX_block_size(cipherCtx.getContext());
    calledUpdate = false;
}
Example 5
Project: cm4mm-updater-master  File: StartupReceiver.java View source code
public static void scheduleUpdateService(Context ctx, int updateFrequency) {
    if (updateFrequency < 0)
        throw new InvalidParameterException("updateFrequency can't be negative");
    Preferences prefs = new Preferences(ctx);
    if (showDebugOutput)
        Log.d(TAG, "Scheduling alarm to go off every " + updateFrequency + " msegs");
    Intent i = new Intent(ctx, UpdateCheckService.class);
    PendingIntent pi = PendingIntent.getService(ctx, 0, i, 0);
    Date lastCheck = prefs.getLastUpdateCheck();
    if (showDebugOutput)
        Log.d(TAG, "Last check on " + lastCheck.toString());
    cancelUpdateChecks(ctx);
    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    if (showDebugOutput)
        Log.d(TAG, "Setting alarm for UpdateService");
    am.setRepeating(AlarmManager.RTC_WAKEUP, lastCheck.getTime() + updateFrequency, updateFrequency, pi);
}
Example 6
Project: android-libcore64-master  File: OpenSSLECGroupContext.java View source code
public static OpenSSLECGroupContext getInstance(ECParameterSpec params) throws InvalidAlgorithmParameterException {
    final String curveName = params.getCurveName();
    if (curveName != null) {
        return OpenSSLECGroupContext.getCurveByName(curveName);
    }
    final EllipticCurve curve = params.getCurve();
    final ECField field = curve.getField();
    final int type;
    final BigInteger p;
    if (field instanceof ECFieldFp) {
        type = NativeCrypto.EC_CURVE_GFP;
        p = ((ECFieldFp) field).getP();
    } else if (field instanceof ECFieldF2m) {
        type = NativeCrypto.EC_CURVE_GF2M;
        p = ((ECFieldF2m) field).getReductionPolynomial();
    } else {
        throw new InvalidParameterException("unhandled field class " + field.getClass().getName());
    }
    final ECPoint generator = params.getGenerator();
    return OpenSSLECGroupContext.getInstance(type, p, curve.getA(), curve.getB(), generator.getAffineX(), generator.getAffineY(), params.getOrder(), BigInteger.valueOf(params.getCofactor()));
}
Example 7
Project: deck_old-master  File: Card.java View source code
@Override
public int compare(Card card, Card card2) {
    if (card == null) {
        return -1;
    } else if (card2 == null) {
        return 1;
    }
    switch(mSortingType) {
        case SORT_BY_RANK:
            {
                int comp = compareRank(card, card2);
                if (comp != 0) {
                    return comp;
                } else {
                    return compareSuit(card, card2);
                }
            }
        case SORT_BY_SUIT:
            {
                int comp = compareSuit(card, card2);
                if (comp != 0) {
                    return comp;
                } else {
                    return compareRank(card, card2);
                }
            }
        case SORT_BY_CARD_NUMBER:
            {
                return compareCardNumber(card, card2);
            }
        default:
            {
                throw new InvalidParameterException("Invalid sorting type.");
            }
    }
}
Example 8
Project: MobileSensing-master  File: TestFileCompressor.java View source code
/**
   * Test method for
   * [email protected] [email protected]sor(de.unikassel.android.sdcframework.util.facade.CompressionStrategy)}
   * .
   */
public final void testFileCompressor() {
    try {
        new FileCompressor(null);
        fail("Expected InvalidParameterException exception");
    } catch (InvalidParameterException e) {
    } catch (Exception e) {
        fail("Unexpected exception type");
    }
    CompressionStrategy strategy = new ZipCompressionStrategy();
    FileCompressor compressor = new FileCompressor(strategy);
    assertNotNull("Expected strategy not null", compressor.getStrategy());
    assertEquals("Expected strategy set", strategy, compressor.getStrategy());
}
Example 9
Project: records-management-master  File: RMNodesImplUnitTest.java View source code
@Test
public void testGetNonFileplanComponent() throws Exception {
    NodeRef nodeRef = AlfMock.generateNodeRef(mockedNodeService);
    QName mockedType = AlfMock.generateQName();
    when(mockedNodeService.getType(nodeRef)).thenReturn(mockedType);
    when(mockedDictionaryService.isSubClass(mockedType, ContentModel.TYPE_CMOBJECT)).thenReturn(true);
    when(mockedDictionaryService.isSubClass(mockedType, ContentModel.TYPE_SYSTEM_FOLDER)).thenReturn(false);
    setupCompanyHomeAndPrimaryParent(nodeRef);
    when(mockedFilePlanService.isFilePlanComponent(nodeRef)).thenReturn(false);
    List<String> includeParamList = new ArrayList<String>();
    try {
        rmNodesImpl.getFolderOrDocument(nodeRef, null, null, includeParamList, null);
        fail("Expected exception since the requested node is not a fileplan component.");
    } catch (InvalidParameterException ex) {
        assertEquals("The provided node is not a fileplan component", ex.getMessage());
    }
}
Example 10
Project: strongback-java-master  File: NewProject.java View source code
public static void main(String[] args) {
    // Parse the parameters ...
    Map<String, String> params = null;
    try {
        params = Parser.parse(args, "npr", "D|v|h|i|nd!r|r!n!d");
    } catch (InvalidParameterException e) {
        System.err.println(e.getLocalizedMessage());
        System.out.println(Strings.HELP);
        exit("", ExitCodes.BAD_ARGS);
    }
    assert params != null;
    debug = params.containsKey("D");
    if (params.containsKey("h")) {
        System.out.println(Strings.HELP);
        exit();
    }
    if (params.containsKey("v")) {
        System.out.println(Strings.VERSION_HEAD);
        System.out.println(Strings.VERSION);
        exit();
    }
    // Resolve the Strongback installation directory ...
    debug("Resolving '~/strongback'");
    File strongbackDirectory = FileUtils.resolvePath("~/strongback");
    if (strongbackDirectory == null || !strongbackDirectory.exists()) {
        exit("Unable to find the 'strongback' installation directory. Check the Strongback installation.", ExitCodes.BAD_ENV);
    }
    strongbackDirectory = strongbackDirectory.getAbsoluteFile();
    if (!strongbackDirectory.isDirectory()) {
        exit("Expecting '" + strongbackDirectory + "' to be a directory. Check the Strongback installation.", ExitCodes.BAD_ENV);
    }
    if (!strongbackDirectory.canRead()) {
        exit("Unable to read the 'strongback' installation directory at " + strongbackDirectory, ExitCodes.BAD_ENV);
    }
    // replace the windows backslashes with forward slashes so i) string.replaceAll works, and ii) Eclipse paths are correct
    final String strongbackPath = strongbackDirectory.getAbsolutePath().replaceAll("\\\\", "/");
    debug("Resolved '~/strongback' to '" + strongbackPath + "'");
    // Load the strongback properties ...
    debug("Checking '~/strongback/strongback.properties' file");
    File strongbackPropsFile = new File(strongbackDirectory, "/strongback.properties");
    if (!strongbackPropsFile.exists()) {
        exit("Unable to find the 'strongback.properties' file in the installation directory. Check the Strongback installation.", ExitCodes.BAD_ENV);
    }
    strongbackPropsFile = strongbackPropsFile.getAbsoluteFile();
    if (!strongbackPropsFile.isFile()) {
        exit("Expecting '" + strongbackPropsFile + "' to be a file but was a directory. Check the Strongback installation.", ExitCodes.BAD_ENV);
    }
    if (!strongbackPropsFile.canRead()) {
        exit("Unable to read the '" + strongbackPropsFile + "' file. Check the Strongback installation.", ExitCodes.BAD_ENV);
    }
    Properties strongbackProperties = null;
    try {
        debug("Loading '" + strongbackPropsFile + "' file");
        strongbackProperties = PropertiesUtils.load(strongbackPropsFile);
        PropertiesUtils.antify(strongbackProperties);
        debug("Loaded '" + strongbackPropsFile.getAbsoluteFile() + "' file");
    } catch (IOException e) {
        exit("Unable to load the '" + strongbackPropsFile + "' file: " + e.getMessage(), ExitCodes.BAD_ENV);
    } catch (InvalidPropertiesException e) {
        exit("Invalid property field in '" + strongbackPropsFile + "' file: " + e.getMessage(), ExitCodes.BAD_ENV);
    }
    // Resolve the WPILib installation directory ...
    String wpiPath = strongbackProperties.getProperty("wpilib.home");
    debug("Checking for the WPILib installation directory " + wpiPath);
    if (wpiPath == null) {
        exit("Strongback properties file '" + strongbackPropsFile + "' must specify the WPILIb directory in 'wpilib.home'", ExitCodes.BAD_ENV);
    }
    File wpiLibDir = new File(wpiPath).getAbsoluteFile();
    if (!wpiLibDir.exists()) {
        exit("Unable to find the '" + wpiLibDir.getName() + "' installation directory.  Make sure the 'wpilib.home' property in '" + strongbackPropsFile + "' points to a valid version of WPILib installation.", ExitCodes.BAD_ENV);
    }
    if (!wpiLibDir.isDirectory()) {
        exit("Expecting '" + wpiLibDir + "' to be a directory but was a file. Make sure the 'wpilib.home' property in '" + strongbackPropsFile + "' points to a valid version of WPILib installation.", ExitCodes.BAD_ENV);
    }
    if (!wpiLibDir.canRead()) {
        exit("Unable to read the '" + wpiLibDir + "' file. Check the WPILib version and file permissions.", ExitCodes.BAD_ENV);
    }
    debug("Found valid WPILib installation directory: " + wpiLibDir);
    // Load the WPILib properties (which may not exist anymore) ...
    debug("Looking for WPILib properties file");
    String wpiLibPropsPath = strongbackProperties.getProperty("wpilib.props", new File(wpiLibDir, "wpilib.properties").getAbsolutePath());
    debug("Checking '" + wpiLibPropsPath + "' file");
    File wpiLibPropsFile = new File(wpiLibPropsPath);
    Properties wpi = new Properties();
    if (wpiLibPropsFile.exists() && wpiLibPropsFile.isFile() && wpiLibPropsFile.canRead()) {
        wpiLibPropsFile = wpiLibPropsFile.getAbsoluteFile();
        try {
            debug("Loading '" + wpiLibPropsFile + "' file");
            wpi = PropertiesUtils.load(wpiLibPropsFile);
            PropertiesUtils.antify(wpi);
            debug("Loaded '" + wpiLibPropsFile.getAbsoluteFile() + "' file");
        } catch (IOException e) {
            exit("Unable to load the '" + wpiLibPropsFile + "' file: " + e.getMessage(), ExitCodes.BAD_PROPS);
        } catch (InvalidPropertiesException e) {
            exit("Invalid property field in '" + wpiLibPropsFile + "' file: " + e.getMessage(), ExitCodes.BAD_PROPS);
        }
    } else {
        debug("WPILib installation does not contain a properties file, so skipping this step");
    }
    final Properties strongback = PropertiesUtils.concat(strongbackProperties, wpi);
    debug("The Strongback properties are: " + strongback);
    File projectRoot;
    String projectName;
    String mainPackage;
    if (params.containsKey("r")) {
        projectRoot = FileUtils.resolvePath(params.get("r"));
        projectName = projectRoot.getName();
    } else {
        projectName = params.get("n");
        projectRoot = FileUtils.resolvePath(params.get("d") + File.separator + projectName);
    }
    debug("The project root will be: " + projectRoot);
    debug("The project name will be: " + projectName);
    if (params.containsKey("p")) {
        mainPackage = params.get("p");
    } else {
        mainPackage = "org.usfirst.frc.team" + strongback.getProperty("team-number") + ".robot";
    }
    debug("The main package for the robot will be '" + mainPackage + "'");
    /* Application Begins */
    // Source folders
    File src = new File(projectRoot, "src" + File.separator + mainPackage.replace('.', File.separatorChar));
    File testsrc = new File(projectRoot, "testsrc" + File.separator + mainPackage.replace('.', File.separatorChar));
    // Source files to copy
    File buildTemplate = new File(strongback.getProperty("strongback.templates.dir"), "build.xml.template");
    File propsTemplate = new File(strongback.getProperty("strongback.templates.dir"), "build.properties.template");
    File robotTemplate = new File(strongback.getProperty("strongback.templates.dir"), "Robot.java.template");
    File testTemplate = new File(strongback.getProperty("strongback.templates.dir"), "TestRobot.java.template");
    // Eclipse specific
    File projectTemplate = new File(strongback.getProperty("strongback.templates.dir"), "project.template");
    File classpathTemplate = new File(strongback.getProperty("strongback.templates.dir"), "classpath.template");
    File userlibTemplate = new File(strongback.getProperty("strongback.templates.dir"), "Strongback.userlibraries.template");
    File userlibImportTemplate = new File(strongback.getProperty("strongback.templates.dir"), "Strongback.userlibraries.import.template");
    // Verify templates exist
    if (!buildTemplate.exists())
        exit(Strings.MISSING_TEMPLATE + buildTemplate.getPath(), ExitCodes.MISSING_FILE);
    if (!propsTemplate.exists())
        exit(Strings.MISSING_TEMPLATE + propsTemplate.getPath(), ExitCodes.MISSING_FILE);
    if (!robotTemplate.exists())
        exit(Strings.MISSING_TEMPLATE + robotTemplate.getPath(), ExitCodes.MISSING_FILE);
    if (!testTemplate.exists())
        exit(Strings.MISSING_TEMPLATE + testTemplate.getPath(), ExitCodes.MISSING_FILE);
    // Destination files
    File buildProps = new File(projectRoot, "build.properties");
    File buildXML = new File(projectRoot, "build.xml");
    File robotJava = new File(src, "Robot.java");
    File testJava = new File(testsrc, "TestRobot.java");
    // Eclipse specific
    File project = new File(projectRoot, ".project");
    File classpath = new File(projectRoot, ".classpath");
    File metadataDir = new File(projectRoot.getParentFile(), ".metadata");
    // Be sure to always generate the Eclipse files that are part of the installation ...
    try {
        File eclipseDir = FileUtils.resolvePath("~/strongback/java/eclipse");
        eclipseDir.mkdirs();
        debug("Created the '" + eclipseDir + "' directory to hold generated files.");
        // user libraries importable file ...
        File userlibraries = new File(eclipseDir, "Strongback.userlibraries");
        if (!userlibraries.exists()) {
            // don't overwrite
            copyTo(userlibImportTemplate, userlibraries, ( line) -> line.replaceAll("STRONGBACKHOME", strongbackPath));
        }
        debug("Created the '" + userlibraries + "' file for manually importing the Strongback user libraries.");
    } catch (IOException e) {
        exit(Strings.IO_EXCEPTION + e.getLocalizedMessage(), ExitCodes.IO_EXCEPT);
    }
    // If any of the files to write to already exist, give up and write message about the overwrite flag
    if (!params.containsKey("o")) {
        if (buildProps.exists())
            exit(Strings.OVERWRITE_WARN + buildProps.getPath(), ExitCodes.OVERWRITE);
        if (buildXML.exists())
            exit(Strings.OVERWRITE_WARN + buildXML.getPath(), ExitCodes.OVERWRITE);
        if (robotJava.exists())
            exit(Strings.OVERWRITE_WARN + robotJava.getPath(), ExitCodes.OVERWRITE);
        if (testJava.exists())
            exit(Strings.OVERWRITE_WARN + testJava.getPath(), ExitCodes.OVERWRITE);
        // Eclipse specific
        if (params.containsKey("e")) {
            if (project.exists())
                exit(Strings.OVERWRITE_WARN + project.getPath(), ExitCodes.OVERWRITE);
            if (classpath.exists())
                exit(Strings.OVERWRITE_WARN + classpath.getPath(), ExitCodes.OVERWRITE);
        }
    }
    // Eclipse specific
    if (params.containsKey("e")) {
        if (!projectTemplate.exists())
            exit(Strings.MISSING_TEMPLATE + projectTemplate.getPath(), ExitCodes.MISSING_FILE);
        if (!classpathTemplate.exists())
            exit(Strings.MISSING_TEMPLATE + classpathTemplate.getPath(), ExitCodes.MISSING_FILE);
    }
    // Make the directories
    if (!projectRoot.exists() & !projectRoot.mkdirs())
        exit(Strings.FAILED_MKDIR + projectRoot.getPath(), ExitCodes.FAILED_MKDIR);
    if (!src.exists() & !src.mkdirs())
        exit(Strings.FAILED_MKDIR + src.getPath(), ExitCodes.FAILED_MKDIR);
    if (!testsrc.exists() & !testsrc.mkdirs())
        exit(Strings.FAILED_MKDIR + testsrc.getPath(), ExitCodes.FAILED_MKDIR);
    // Copy templates
    boolean eclipseProject = false;
    boolean foundMetadata = false;
    boolean updatedMetadata = false;
    try {
        copyTo(buildTemplate, buildXML, ( line) -> line.replace("PROJECT_NAME", projectName));
        copyTo(propsTemplate, buildProps, ( line) -> line.replace("PACKAGE", mainPackage));
        copyTo(robotTemplate, robotJava, ( line) -> line.replace("PACKAGE", mainPackage));
        copyTo(testTemplate, testJava, ( line) -> line.replace("PACKAGE", mainPackage));
        // Eclipse specific
        if (params.containsKey("e")) {
            copyTo(projectTemplate, project, ( line) -> line.replace("PROJECT_NAME", projectName));
            copyTo(classpathTemplate, classpath, ( line) -> line);
            // See if the `Strongback` user library is in the workspace ...
            if (metadataDir.exists()) {
                foundMetadata = true;
                File jdtPrefsFile = new File(metadataDir, ".plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.core.prefs");
                if (jdtPrefsFile.exists()) {
                    Properties jdtPrefs = new Properties();
                    try (InputStream is = new FileInputStream(jdtPrefsFile)) {
                        jdtPrefs.load(is);
                    }
                    if (!jdtPrefs.isEmpty() && !jdtPrefs.containsKey("org.eclipse.jdt.core.userLibrary.Strongback")) {
                        debug("Adding the Strongback user library to the Eclipse workspace at " + metadataDir.getParent());
                        // Make a backup of the original preferences file ...
                        File jdtPrefsFileCopy = new File(jdtPrefsFile.getParentFile(), "org.eclipse.jdt.core.prefs.backup");
                        copyTo(jdtPrefsFile, jdtPrefsFileCopy, ( line) -> line);
                        debug("Created backup of " + jdtPrefsFile);
                        // Read in the userlibrary file and escape all the required characters ...
                        List<String> lines = Files.readAllLines(userlibTemplate.toPath(), StandardCharsets.UTF_8);
                        String escapedContents = combineAndEscape(lines, strongbackPath);
                        debug("Escaped contents of the preference file:" + System.lineSeparator() + escapedContents);
                        // Set the property and output the file ...
                        jdtPrefs.setProperty("org.eclipse.jdt.core.userLibrary.Strongback", escapedContents);
                        try (OutputStream os = new FileOutputStream(jdtPrefsFile)) {
                            jdtPrefs.store(os, "");
                            debug("Updated preference file");
                            updatedMetadata = true;
                        }
                    }
                }
            }
            eclipseProject = true;
        }
    } catch (IOException e) {
        exit(Strings.IO_EXCEPTION + e.getLocalizedMessage(), ExitCodes.IO_EXCEPT);
    }
    // Print success
    System.out.print(Strings.SUCCESS);
    try {
        System.out.println(projectRoot.getCanonicalPath());
    } catch (IOException e) {
        System.out.println(projectRoot.getPath());
    }
    if (foundMetadata && updatedMetadata) {
        System.out.print(Strings.UPDATED_WORKSPACE);
        System.out.println(metadataDir.getParentFile().getAbsolutePath());
        System.out.print(Strings.RESTART_ECLIPSE);
    } else if (eclipseProject) {
        System.out.println(Strings.IMPORT_ECLIPSE);
        if (!foundMetadata) {
            System.out.print(Strings.IMPORT_USERLIB);
            System.out.println(strongbackDirectory.getAbsolutePath() + "/java/eclipse/Strongback.userlibraries");
        }
    }
}
Example 11
Project: oobd-master  File: BaseBlockCipher.java View source code
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    CipherParameters param;
    this.pbeSpec = null;
    this.pbeAlgorithm = null;
    this.engineParams = null;
    //
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Key for algorithm " + key.getAlgorithm() + " not suitable for symmetric enryption.");
    }
    //
    if (params == null && baseEngine.getAlgorithmName().startsWith("RC5-64")) {
        throw new InvalidAlgorithmParameterException("RC5 requires an RC5ParametersSpec to be passed in.");
    }
    //
    if (key instanceof BCPBEKey) {
        BCPBEKey k = (BCPBEKey) key;
        if (k.getOID() != null) {
            pbeAlgorithm = k.getOID().getId();
        } else {
            pbeAlgorithm = k.getAlgorithm();
        }
        if (k.getParam() != null) {
            param = k.getParam();
            pbeSpec = new PBEParameterSpec(k.getSalt(), k.getIterationCount());
        } else if (params instanceof PBEParameterSpec) {
            pbeSpec = (PBEParameterSpec) params;
            param = PBE.Util.makePBEParameters(k, params, cipher.getUnderlyingCipher().getAlgorithmName());
        } else {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
        if (param instanceof ParametersWithIV) {
            ivParam = (ParametersWithIV) param;
        }
    } else if (params == null) {
        param = new KeyParameter(key.getEncoded());
    } else if (params instanceof IvParameterSpec) {
        if (ivLength != 0) {
            IvParameterSpec p = (IvParameterSpec) params;
            if (p.getIV().length != ivLength && !isAEADModeName(modeName)) {
                throw new InvalidAlgorithmParameterException("IV must be " + ivLength + " bytes long.");
            }
            if (key instanceof RepeatedSecretKeySpec) {
                param = new ParametersWithIV(null, p.getIV());
                ivParam = (ParametersWithIV) param;
            } else {
                param = new ParametersWithIV(new KeyParameter(key.getEncoded()), p.getIV());
                ivParam = (ParametersWithIV) param;
            }
        } else {
            if (modeName != null && modeName.equals("ECB")) {
                throw new InvalidAlgorithmParameterException("ECB mode does not use an IV");
            }
            param = new KeyParameter(key.getEncoded());
        }
    } else if (params instanceof GOST28147ParameterSpec) {
        GOST28147ParameterSpec gost28147Param = (GOST28147ParameterSpec) params;
        param = new ParametersWithSBox(new KeyParameter(key.getEncoded()), ((GOST28147ParameterSpec) params).getSbox());
        if (gost28147Param.getIV() != null && ivLength != 0) {
            param = new ParametersWithIV(param, gost28147Param.getIV());
            ivParam = (ParametersWithIV) param;
        }
    } else if (params instanceof RC2ParameterSpec) {
        RC2ParameterSpec rc2Param = (RC2ParameterSpec) params;
        param = new RC2Parameters(key.getEncoded(), ((RC2ParameterSpec) params).getEffectiveKeyBits());
        if (rc2Param.getIV() != null && ivLength != 0) {
            param = new ParametersWithIV(param, rc2Param.getIV());
            ivParam = (ParametersWithIV) param;
        }
    } else if (params instanceof RC5ParameterSpec) {
        RC5ParameterSpec rc5Param = (RC5ParameterSpec) params;
        param = new RC5Parameters(key.getEncoded(), ((RC5ParameterSpec) params).getRounds());
        if (baseEngine.getAlgorithmName().startsWith("RC5")) {
            if (baseEngine.getAlgorithmName().equals("RC5-32")) {
                if (rc5Param.getWordSize() != 32) {
                    throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 32 not " + rc5Param.getWordSize() + ".");
                }
            } else if (baseEngine.getAlgorithmName().equals("RC5-64")) {
                if (rc5Param.getWordSize() != 64) {
                    throw new InvalidAlgorithmParameterException("RC5 already set up for a word size of 64 not " + rc5Param.getWordSize() + ".");
                }
            }
        } else {
            throw new InvalidAlgorithmParameterException("RC5 parameters passed to a cipher that is not RC5.");
        }
        if ((rc5Param.getIV() != null) && (ivLength != 0)) {
            param = new ParametersWithIV(param, rc5Param.getIV());
            ivParam = (ParametersWithIV) param;
        }
    } else {
        throw new InvalidAlgorithmParameterException("unknown parameter type.");
    }
    if ((ivLength != 0) && !(param instanceof ParametersWithIV)) {
        SecureRandom ivRandom = random;
        if (ivRandom == null) {
            ivRandom = new SecureRandom();
        }
        if ((opmode == Cipher.ENCRYPT_MODE) || (opmode == Cipher.WRAP_MODE)) {
            byte[] iv = new byte[ivLength];
            ivRandom.nextBytes(iv);
            param = new ParametersWithIV(param, iv);
            ivParam = (ParametersWithIV) param;
        } else if (cipher.getUnderlyingCipher().getAlgorithmName().indexOf("PGPCFB") < 0) {
            throw new InvalidAlgorithmParameterException("no IV set when one expected");
        }
    }
    if (random != null && padded) {
        param = new ParametersWithRandom(param, random);
    }
    try {
        switch(opmode) {
            case Cipher.ENCRYPT_MODE:
            case Cipher.WRAP_MODE:
                cipher.init(true, param);
                break;
            case Cipher.DECRYPT_MODE:
            case Cipher.UNWRAP_MODE:
                cipher.init(false, param);
                break;
            default:
                throw new InvalidParameterException("unknown opmode " + opmode + " passed");
        }
    } catch (Exception e) {
        throw new InvalidKeyException(e.getMessage());
    }
}
Example 12
Project: open-mika-master  File: JCERSACipher.java View source code
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    CipherParameters param;
    if (params == null || params instanceof OAEPParameterSpec) {
        if (key instanceof RSAPublicKey) {
            if (privateKeyOnly) {
                throw new InvalidKeyException("mode 1 requires RSAPrivateKey");
            }
            param = RSAUtil.generatePublicKeyParameter((RSAPublicKey) key);
        } else if (key instanceof RSAPrivateKey) {
            if (publicKeyOnly) {
                throw new InvalidKeyException("mode 2 requires RSAPublicKey");
            }
            param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey) key);
        } else {
            throw new InvalidKeyException("unknown key type passed to RSA");
        }
        if (params != null) {
            OAEPParameterSpec spec = (OAEPParameterSpec) params;
            paramSpec = params;
            if (!spec.getMGFAlgorithm().equalsIgnoreCase("MGF1") && !spec.getMGFAlgorithm().equals(PKCSObjectIdentifiers.id_mgf1.getId())) {
                throw new InvalidAlgorithmParameterException("unknown mask generation function specified");
            }
            if (!(spec.getMGFParameters() instanceof MGF1ParameterSpec)) {
                throw new InvalidAlgorithmParameterException("unkown MGF parameters");
            }
            MGF1ParameterSpec mgfParams = (MGF1ParameterSpec) spec.getMGFParameters();
            if (!JCEDigestUtil.isSameDigest(mgfParams.getDigestAlgorithm(), spec.getDigestAlgorithm())) {
                throw new InvalidAlgorithmParameterException("digest algorithm for MGF should be the same as for OAEP parameters.");
            }
            Digest digest = JCEDigestUtil.getDigest(mgfParams.getDigestAlgorithm());
            if (digest == null) {
                throw new InvalidAlgorithmParameterException("no match on MGF digest algorithm: " + mgfParams.getDigestAlgorithm());
            }
            cipher = new OAEPEncoding(new RSAEngine(), digest, ((PSource.PSpecified) spec.getPSource()).getValue());
        }
    } else {
        throw new IllegalArgumentException("unknown parameter type.");
    }
    if (!(cipher instanceof RSAEngine)) {
        if (random != null) {
            param = new ParametersWithRandom(param, random);
        } else {
            param = new ParametersWithRandom(param, new SecureRandom());
        }
    }
    switch(opmode) {
        case Cipher.ENCRYPT_MODE:
        case Cipher.WRAP_MODE:
            cipher.init(true, param);
            break;
        case Cipher.DECRYPT_MODE:
        case Cipher.UNWRAP_MODE:
            cipher.init(false, param);
            break;
        default:
            throw new InvalidParameterException("unknown opmode " + opmode + " passed to RSA");
    }
}
Example 13
Project: geotools-old-master  File: ProcessFunction.java View source code
public Object evaluate(Object object) {
    // collect the entries
    Map<String, Object> processInputs = new HashMap<String, Object>();
    for (Expression input : inputExpressions) {
        Object result = input.evaluate(object, Map.class);
        if (result != null) {
            Map map = (Map) result;
            if (map.size() > 1) {
                throw new InvalidParameterException("The parameters to a ProcessFunction " + "must all be maps with a single entry, " + "the key is the process argument name, " + "the value is the argument value");
            } else {
                // handle the key/value
                Iterator it = map.entrySet().iterator();
                Map.Entry<String, Object> entry = (Entry<String, Object>) it.next();
                final String paramName = entry.getKey();
                final Object paramValue = entry.getValue();
                // see if we have a parameter with that name
                Parameter param = parameters.get(paramName);
                if (param == null) {
                    throw new InvalidParameterException("Parameter " + paramName + " is not among the process parameters: " + parameters.keySet());
                } else {
                    // to the process invocation params
                    if (paramValue != null) {
                        Object converted;
                        if (param.maxOccurs > 1) {
                            // they have to deal with two conversions, from single to multi, from type to type
                            if (!(paramValue instanceof Collection) && !(paramValue.getClass().isArray())) {
                                List<Object> collection = Collections.singletonList(paramValue);
                                converted = Converters.convert(collection, Array.newInstance(param.type, 0).getClass());
                            } else {
                                converted = Converters.convert(paramValue, Array.newInstance(param.type, 0).getClass());
                            }
                        } else {
                            converted = Converters.convert(paramValue, param.type);
                        }
                        if (converted == null) {
                            if (param.maxOccurs > 1 && Collection.class.isAssignableFrom(paramValue.getClass())) {
                                final Collection collection = (Collection) paramValue;
                                Collection convertedCollection = new ArrayList(collection.size());
                                for (Object original : collection) {
                                    Object convertedItem = Converters.convert(original, param.type);
                                    if (original != null && convertedItem == null) {
                                        throw new InvalidParameterException("Could not convert the value " + original + " into the expected type " + param.type + " for parameter " + paramName);
                                    }
                                    convertedCollection.add(convertedItem);
                                }
                                Object array = Array.newInstance(param.type, convertedCollection.size());
                                int i = 0;
                                for (Object item : convertedCollection) {
                                    Array.set(array, i, item);
                                    i++;
                                }
                                converted = array;
                            } else {
                                throw new InvalidParameterException("Could not convert the value " + paramValue + " into the expected type " + param.type + " for parameter " + paramName);
                            }
                        }
                        processInputs.put(paramName, converted);
                    }
                }
            }
        }
    }
    // execute the process
    try {
        ExceptionProgressListener listener = new ExceptionProgressListener();
        Map<String, Object> results = process.execute(processInputs, listener);
        // report them to the listener
        if (listener.getExceptions().size() > 0) {
            // uh oh, an exception occurred during processing
            Throwable t = listener.getExceptions().get(0);
            throw new RuntimeException("Failed to evaluate process function, error is: " + t.getMessage(), t);
        }
        return getResult(results, processInputs);
    } catch (ProcessException e) {
        throw new RuntimeException("Failed to evaluate the process function, error is: " + e.getMessage(), e);
    }
}
Example 14
Project: JBossAS51-master  File: Scheduler.java View source code
private void createSchedulable() {
    if (mSchedulableClass == null) {
        throw new InvalidParameterException("Schedulable Class not set");
    }
    if (mSchedulableArgumentList.length != mSchedulableArgumentTypeList.length) {
        throw new InvalidParameterException("Schedulable Class Arguments and Types do not match in length");
    }
    // Create all the Objects for the Constructor to be called
    Object[] lArgumentList = new Object[mSchedulableArgumentTypeList.length];
    try {
        for (int i = 0; i < mSchedulableArgumentTypeList.length; i++) {
            Class lClass = mSchedulableArgumentTypeList[i];
            if (lClass == Boolean.TYPE) {
                lArgumentList[i] = new Boolean(mSchedulableArgumentList[i]);
            } else if (lClass == Integer.TYPE) {
                lArgumentList[i] = new Integer(mSchedulableArgumentList[i]);
            } else if (lClass == Long.TYPE) {
                lArgumentList[i] = new Long(mSchedulableArgumentList[i]);
            } else if (lClass == Short.TYPE) {
                lArgumentList[i] = new Short(mSchedulableArgumentList[i]);
            } else if (lClass == Float.TYPE) {
                lArgumentList[i] = new Float(mSchedulableArgumentList[i]);
            } else if (lClass == Double.TYPE) {
                lArgumentList[i] = new Double(mSchedulableArgumentList[i]);
            } else if (lClass == Byte.TYPE) {
                lArgumentList[i] = new Byte(mSchedulableArgumentList[i]);
            } else if (lClass == Character.TYPE) {
                lArgumentList[i] = new Character(mSchedulableArgumentList[i].charAt(0));
            } else {
                Constructor lConstructor = lClass.getConstructor(new Class[] { String.class });
                lArgumentList[i] = lConstructor.newInstance(new Object[] { mSchedulableArgumentList[i] });
            }
        }
    } catch (Exception e) {
        log.error("Could not load or create constructor argument", e);
        throw new InvalidParameterException("Could not load or create a constructor argument");
    }
    try {
        // Check if constructor is found
        Constructor lSchedulableConstructor = mSchedulableClass.getConstructor(mSchedulableArgumentTypeList);
        // Create an instance of it
        mSchedulable = (Schedulable) lSchedulableConstructor.newInstance(lArgumentList);
    } catch (Exception e) {
        log.error("Could not find the constructor or create Schedulable instance", e);
        throw new InvalidParameterException("Could not find the constructor or create the Schedulable Instance");
    }
}
Example 15
Project: picard-tools-master  File: FormatUtil.java View source code
/**
     * Attempts to determine the correct parse method to call based on the desired
     * return type and then parses the String and returns the value.
     *
     * @param value the String value to be parsed
     * @param returnType the desired return type
     * @return an object of the returnType
     */
public Object parseObject(String value, Class<?> returnType) {
    if (returnType == Short.class || returnType == Short.TYPE)
        return parseShort(value);
    if (returnType == Integer.class || returnType == Integer.TYPE)
        return parseInt(value);
    if (returnType == Long.class || returnType == Long.TYPE)
        return parseLong(value);
    if (returnType == Float.class || returnType == Float.TYPE)
        return parseFloat(value);
    if (returnType == Double.class || returnType == Double.TYPE)
        return parseDouble(value);
    if (returnType == Boolean.class || returnType == Boolean.TYPE)
        return parseBoolean(value);
    if (returnType == Iso8601Date.class)
        return parseIso8601Date(value);
    if (returnType == Date.class)
        return parseDate(value);
    if (returnType == Byte.class || returnType == Byte.TYPE)
        return parseInt(value);
    if (returnType == File.class)
        return new File(value);
    if (Enum.class.isAssignableFrom(returnType))
        return parseEnum(value, (Class<? extends Enum>) returnType);
    if (returnType == String.class)
        return value;
    throw new InvalidParameterException("Don't know how to convert a String to a " + returnType.getName());
}
Example 16
Project: openjdk8-jdk-master  File: DSAParameterGenerator.java View source code
/**
     * Initializes this parameter generator with a set of
     * algorithm-specific parameter generation values.
     *
     * @param genParamSpec the set of algorithm-specific parameter generation values
     * @param random the source of randomness
     *
     * @exception InvalidAlgorithmParameterException if the given parameter
     * generation values are inappropriate for this parameter generator
     */
protected void engineInit(AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException {
    if (!(genParamSpec instanceof DSAGenParameterSpec)) {
        throw new InvalidAlgorithmParameterException("Invalid parameter");
    }
    DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec) genParamSpec;
    int primePLen = dsaGenParams.getPrimePLength();
    if (primePLen > 2048) {
        throw new InvalidParameterException("No support for prime size " + primePLen);
    }
    // directly initialize using the already validated values
    this.valueL = primePLen;
    this.valueN = dsaGenParams.getSubprimeQLength();
    this.seedLen = dsaGenParams.getSeedLength();
    this.random = random;
}
Example 17
Project: WS171-development-master  File: AndroidDebugBridge.java View source code
/**
     * Creates a [email protected] AndroidDebugBridge} that is not linked to any particular executable.
     * <p/>This bridge will expect adb to be running. It will not be able to start/stop/restart
     * adb.
     * <p/>If a bridge has already been started, it is directly returned with no changes (similar
     * to calling [email protected] #getBridge()}).
     * @return a connected bridge.
     */
public static AndroidDebugBridge createBridge() {
    synchronized (sLock) {
        if (sThis != null) {
            return sThis;
        }
        try {
            sThis = new AndroidDebugBridge();
            sThis.start();
        } catch (InvalidParameterException e) {
            sThis = null;
        }
        // because the listeners could remove themselves from the list while processing
        // their event callback, we make a copy of the list and iterate on it instead of
        // the main list.
        // This mostly happens when the application quits.
        IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray(new IDebugBridgeChangeListener[sBridgeListeners.size()]);
        // notify the listeners of the change
        for (IDebugBridgeChangeListener listener : listenersCopy) {
            // thread
            try {
                listener.bridgeChanged(sThis);
            } catch (Exception e) {
                Log.e(DDMS, e);
            }
        }
        return sThis;
    }
}
Example 18
Project: GeoGig-master  File: Show.java View source code
public void printFormatted(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline();
                ansi.fg(Color.YELLOW).a("FEATURE TYPE ID:  ").reset().a(ft.getId().toString()).newline().newline();
                ansi.a("ATTRIBUTES  ").newline();
                ansi.a("----------  ").newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject)).call();
                console.println(s);
            }
        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset().a(Integer.toString(tree.numTrees()).toString()).newline();
            printFeatureType(ansi, ft, true);
            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset().newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor())).reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor())).reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED).a(estimateSince(geogig.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ").a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED).a(estimateSince(geogig.getPlatform(), commit.getCommitter().getTimestamp())).reset().a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException("Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }
}
Example 19
Project: castor-master  File: FieldInfoFactory.java View source code
/**
     * Creates a [email protected] CollectionInfo} instance based upon the various parameters provided.
     * @param contentType Content type of the collection.
     * @param name Name of the collection member.
     * @param elementName Name of the (content) element.
     * @param collectionName Name of the collection.
     * @param javaNaming the Java naming to be used
     * @param useJava50 Whether we are targeting Java 5.0 or above or not
     * @return A [email protected] CollectionInfo} instance representing a collection typed member.
     */
public CollectionInfo createCollection(final XSType contentType, final String name, final String elementName, final String collectionName, final JavaNaming javaNaming, final boolean useJava50) {
    String temp = collectionName;
    if (temp == null || temp.length() == 0) {
        temp = _default;
    }
    final CollectionInfo cInfo;
    if (temp.equalsIgnoreCase(SourceGeneratorConstants.FIELD_INFO_VECTOR)) {
        cInfo = new CollectionInfo(contentType, name, elementName, useJava50, this._collectionMemberAndAccessorFactory, this._fieldMemberAndAccessorFactory);
    } else if (temp.equalsIgnoreCase(SourceGeneratorConstants.FIELD_INFO_ARRAY_LIST)) {
        cInfo = new CollectionInfoJ2(contentType, name, elementName, "arraylist", useJava50, this._collectionJ2MemberAndAccessorFactory, this._fieldMemberAndAccessorFactory);
    } else if (temp.equalsIgnoreCase(SourceGeneratorConstants.FIELD_INFO_ODMG)) {
        cInfo = new CollectionInfoODMG30(contentType, name, elementName, useJava50, this._collectionODMG30MemberAndAccessorFactory, this._fieldMemberAndAccessorFactory);
    } else if (temp.equalsIgnoreCase(SourceGeneratorConstants.FIELD_INFO_COLLECTION)) {
        cInfo = new CollectionInfoJ2Collection(contentType, name, elementName, useJava50, this._collectionJ2NoIndexMemberAndAccessorFactory, this._fieldMemberAndAccessorFactory);
    } else if (temp.equalsIgnoreCase(SourceGeneratorConstants.FIELD_INFO_SET)) {
        cInfo = new CollectionInfoJ2Set(contentType, name, elementName, useJava50, this._collectionJ2NoIndexMemberAndAccessorFactory, this._fieldMemberAndAccessorFactory);
    } else if (temp.equalsIgnoreCase(SourceGeneratorConstants.FIELD_INFO_SORTED_SET)) {
        cInfo = new CollectionInfoJ2SortedSet(contentType, name, elementName, useJava50, this._collectionJ2NoIndexMemberAndAccessorFactory, this._fieldMemberAndAccessorFactory);
    } else {
        throw new InvalidParameterException("Unrecognized collection type: " + temp);
    }
    //--not sure it is pluggable enough, it is not really beautiful to specify
    //--the collection to use here
    cInfo.setCreateExtraMethods(_extraMethods);
    if (_referenceSuffix != null) {
        cInfo.setReferenceMethodSuffix(_referenceSuffix);
    }
    if (_bound) {
        cInfo.setBound(true);
    }
    return cInfo;
}
Example 20
Project: abiquo-master  File: DatacenterTaskBuilder.java View source code
/**
     * End builder-method to get the [email protected] Task} for Redis persistence.
     * 
     * @return The [email protected] Task} for Redis persistence
     */
public Task buildAsyncTask(final String ownerId, final TaskType taskType) {
    if (StringUtils.isBlank(ownerId) || taskType == null) {
        throw new InvalidParameterException();
    }
    this.asyncTask.setOwnerId(ownerId);
    this.asyncTask.setType(taskType);
    for (Job job : this.asyncTask.getJobs()) {
        String jobName = format(job.getType().name(), false);
        String taskName = format(this.asyncTask.getType().name(), true);
        String ownerName = format(this.asyncTask.getType().getOwnerType().name(), false);
        job.setDescription(String.format("%s task's %s on %s with id %s", taskName, jobName, ownerName, ownerId));
    }
    return this.asyncTask;
}
Example 21
Project: blogracy-master  File: MediaController.java View source code
/**
     * Create a new Album for the user. Adds the album to the user's recordDB
     * entry Adds the action to the ActivityStream (verb: create)
     * 
     * @param userId
     * @param photoAlbumName
     */
public synchronized String createPhotoAlbum(String userId, String photoAlbumTitle) {
    if (userId == null)
        throw new InvalidParameterException("userId cannot be null");
    if (photoAlbumTitle == null || photoAlbumTitle.isEmpty())
        return null;
    String albumHash = null;
    try {
        albumHash = sharing.hash(userId + photoAlbumTitle);
        Album album = new AlbumImpl();
        album.setTitle(photoAlbumTitle);
        album.setId(albumHash);
        album.setOwnerId(userId);
        List<Type> types = new ArrayList<Type>();
        types.add(Type.IMAGE);
        album.setMediaType(types);
        // Album is empty where created
        album.setMediaItemCount(0);
        final List<ActivityEntry> feed = activities.getFeed(userId);
        final ActivityEntry entry = new ActivityEntryImpl();
        entry.setVerb("create");
        ActivityObject mediaAlbumObject = new ActivityObjectImpl();
        mediaAlbumObject.setObjectType("collection");
        mediaAlbumObject.setContent(photoAlbumTitle);
        entry.setObject(mediaAlbumObject);
        entry.setPublished(ISO_DATE_FORMAT.format(new Date()));
        entry.setContent(photoAlbumTitle);
        feed.add(0, entry);
        String feedUri = activities.seedActivityStream(userId, feed);
        // Append another album into the user's recordDB
        JSONObject recordDb = DistributedHashTable.getSingleton().getRecord(userId);
        if (recordDb == null)
            recordDb = new JSONObject();
        JSONArray albums = recordDb.optJSONArray("albums");
        if (albums != null) {
            // Simply append new album
            albums.put(new JSONObject(CONVERTER.convertToString(album)));
        } else {
            albums = new JSONArray();
            albums.put(new JSONObject(CONVERTER.convertToString(album)));
        }
        DistributedHashTable.getSingleton().store(userId, feedUri, entry.getPublished(), albums, recordDb.optJSONArray("mediaItems"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return albumHash;
}
Example 22
Project: android_packages_apps-master  File: SimpleWeekView.java View source code
/**
     * Sets all the parameters for displaying this week. The only required
     * parameter is the week number. Other parameters have a default value and
     * will only update if a new value is included, except for focus month,
     * which will always default to no focus month if no value is passed in. See
     * [email protected] #VIEW_PARAMS_HEIGHT} for more info on parameters.
     *
     * @param params A map of the new parameters, see
     *            [email protected] #VIEW_PARAMS_HEIGHT}
     * @param tz The time zone this view should reference times in
     */
public void setWeekParams(HashMap<String, Integer> params, String tz) {
    if (!params.containsKey(VIEW_PARAMS_WEEK)) {
        throw new InvalidParameterException("You must specify the week number for this view");
    }
    setTag(params);
    mTimeZone = tz;
    // We keep the current value for any params not present
    if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
        mHeight = params.get(VIEW_PARAMS_HEIGHT);
        if (mHeight < MIN_HEIGHT) {
            mHeight = MIN_HEIGHT;
        }
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) {
        mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY);
    }
    mHasSelectedDay = mSelectedDay != -1;
    if (params.containsKey(VIEW_PARAMS_NUM_DAYS)) {
        mNumDays = params.get(VIEW_PARAMS_NUM_DAYS);
    }
    if (params.containsKey(VIEW_PARAMS_SHOW_WK_NUM)) {
        if (params.get(VIEW_PARAMS_SHOW_WK_NUM) != 0) {
            mShowWeekNum = true;
        } else {
            mShowWeekNum = false;
        }
    }
    mNumCells = mShowWeekNum ? mNumDays + 1 : mNumDays;
    // Allocate space for caching the day numbers and focus values
    mDayNumbers = new String[mNumCells];
    mFocusDay = new boolean[mNumCells];
    mWeek = params.get(VIEW_PARAMS_WEEK);
    int julianMonday = Utils.getJulianMondayFromWeeksSinceEpoch(mWeek);
    Time time = new Time(tz);
    time.setJulianDay(julianMonday);
    // If we're showing the week number calculate it based on Monday
    int i = 0;
    if (mShowWeekNum) {
        mDayNumbers[0] = Integer.toString(time.getWeekNumber());
        i++;
    }
    if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
        mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
    }
    // Dec 27th 1969 -Jan 2nd, 1970
    if (time.weekDay != mWeekStart) {
        int diff = time.weekDay - mWeekStart;
        if (diff < 0) {
            diff += 7;
        }
        time.monthDay -= diff;
        time.normalize(true);
    }
    mFirstJulianDay = Time.getJulianDay(time.toMillis(true), time.gmtoff);
    mFirstMonth = time.month;
    // Figure out what day today is
    Time today = new Time(tz);
    today.setToNow();
    mHasToday = false;
    mToday = -1;
    int focusMonth = params.containsKey(VIEW_PARAMS_FOCUS_MONTH) ? params.get(VIEW_PARAMS_FOCUS_MONTH) : DEFAULT_FOCUS_MONTH;
    for (; i < mNumCells; i++) {
        if (time.monthDay == 1) {
            mFirstMonth = time.month;
        }
        if (time.month == focusMonth) {
            mFocusDay[i] = true;
        } else {
            mFocusDay[i] = false;
        }
        if (time.year == today.year && time.yearDay == today.yearDay) {
            mHasToday = true;
            mToday = i;
        }
        mDayNumbers[i] = Integer.toString(time.monthDay++);
        time.normalize(true);
    }
    // new month undo it
    if (time.monthDay == 1) {
        time.monthDay--;
        time.normalize(true);
    }
    mLastMonth = time.month;
    updateSelectionPositions();
}
Example 23
Project: ARTPart-master  File: ProviderTest.java View source code
public void test_Provider_getServices_supportsParameter() throws Exception {
    HashSet<String> remainingTypes = new HashSet<String>(Arrays.asList(TYPES_SERVICES_CHECKED));
    HashSet<String> supportsParameterTypes = new HashSet<String>();
    HashSet<String> noSupportsParameterTypes = new HashSet<String>();
    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
        Set<Provider.Service> services = provider.getServices();
        assertNotNull(services);
        assertFalse(services.isEmpty());
        for (Provider.Service service : services) {
            final String type = service.getType();
            remainingTypes.remove(type);
            try {
                service.supportsParameter(new MockKey());
                supportsParameterTypes.add(type);
            } catch (InvalidParameterException e) {
                noSupportsParameterTypes.add(type);
                try {
                    service.supportsParameter(new Object());
                    fail("Should throw on non-Key parameter");
                } catch (InvalidParameterException expected) {
                }
            }
        }
    }
    supportsParameterTypes.retainAll(TYPES_SUPPORTS_PARAMETER);
    assertEquals("Types that should support parameters", TYPES_SUPPORTS_PARAMETER, supportsParameterTypes);
    noSupportsParameterTypes.retainAll(TYPES_NOT_SUPPORTS_PARAMETER);
    assertEquals("Types that should not support parameters", TYPES_NOT_SUPPORTS_PARAMETER, noSupportsParameterTypes);
    assertEquals("Types that should be checked", Collections.EMPTY_SET, remainingTypes);
}
Example 24
Project: cdt-master  File: PersistentSettingsManager.java View source code
/**
	 * Creates a new persistent parameter, using the namespace and instance id of this manager.
	 * @param clazz: the class of the persistent parameter. Supported types: String, Integer, Boolean
	 * @param label: unique label that identifies this parameter. 
	 * @param perInstance: whether the parameter's value should be persisted per client instance or  
	 *    globally (one common shared stored value for all instances)
	 * @param defaultValue: default value to use (mandatory)
	 */
public <T> PersistentParameter<T> getNewParameter(Class<T> clazz, String label, boolean perInstance, T defaultValue) {
    PersistentParameter<T> setting;
    // build the final store key with category, parameter label and specific instance, if applicable
    //$NON-NLS-1$
    setting = new PersistentParameter<T>(clazz, perInstance, getStorageKey(perInstance) + "." + label);
    // check that we're dealing with one of a few supported types
    if (setting.isTypeSupported(clazz)) {
        setting.setDefault(defaultValue);
        return setting;
    } else {
        //$NON-NLS-1$
        throw new InvalidParameterException("Unsupported class type: " + clazz.toString());
    }
}
Example 25
Project: flink-master  File: CoGroupOperator.java View source code
private static <I1, I2, K, OUT> PlanRightUnwrappingCoGroupOperator<I1, I2, OUT, K> translateSelectorFunctionCoGroupRight(int[] logicalKeyPositions1, SelectorFunctionKeys<I2, ?> rawKeys2, CoGroupFunction<I1, I2, OUT> function, TypeInformation<I1> inputType1, TypeInformation<OUT> outputType, String name, Operator<I1> input1, Operator<I2> input2) {
    if (!inputType1.isTupleType()) {
        throw new InvalidParameterException("Should not happen.");
    }
    @SuppressWarnings("unchecked") final SelectorFunctionKeys<I2, K> keys2 = (SelectorFunctionKeys<I2, K>) rawKeys2;
    final TypeInformation<Tuple2<K, I2>> typeInfoWithKey2 = KeyFunctions.createTypeWithKey(keys2);
    final Operator<Tuple2<K, I2>> keyedInput2 = KeyFunctions.appendKeyExtractor(input2, keys2);
    final PlanRightUnwrappingCoGroupOperator<I1, I2, OUT, K> cogroup = new PlanRightUnwrappingCoGroupOperator<>(function, logicalKeyPositions1, keys2, name, outputType, inputType1, typeInfoWithKey2);
    cogroup.setFirstInput(input1);
    cogroup.setSecondInput(keyedInput2);
    return cogroup;
}
Example 26
Project: property-db-master  File: ContentService.java View source code
/**
     * Register a content observer tied to a specific user's view of the provider.
     * @param userHandle the user whose view of the provider is to be observed.  May be
     *     the calling user without requiring any permission, otherwise the caller needs to
     *     hold the INTERACT_ACROSS_USERS_FULL permission.  Pseudousers USER_ALL and
     *     USER_CURRENT are properly handled; all other pseudousers are forbidden.
     */
@Override
public void registerContentObserver(Uri uri, boolean notifyForDescendants, IContentObserver observer, int userHandle) {
    if (observer == null || uri == null) {
        throw new IllegalArgumentException("You must pass a valid uri and observer");
    }
    final int callingUser = UserHandle.getCallingUserId();
    if (callingUser != userHandle) {
        mContext.enforceCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL, "no permission to observe other users' provider view");
    }
    if (userHandle < 0) {
        if (userHandle == UserHandle.USER_CURRENT) {
            userHandle = ActivityManager.getCurrentUser();
        } else if (userHandle != UserHandle.USER_ALL) {
            throw new InvalidParameterException("Bad user handle for registerContentObserver: " + userHandle);
        }
    }
    synchronized (mRootNode) {
        mRootNode.addObserverLocked(uri, observer, notifyForDescendants, mRootNode, Binder.getCallingUid(), Binder.getCallingPid(), userHandle);
        if (false)
            Log.v(TAG, "Registered observer " + observer + " at " + uri + " with notifyForDescendants " + notifyForDescendants);
    }
}
Example 27
Project: android-betterpickers-master  File: MonthView.java View source code
/**
     * Sets all the parameters for displaying this week. The only required parameter is the week number. Other
     * parameters have a default value and will only update if a new value is included, except for focus month, which
     * will always default to no focus month if no value is passed in. See [email protected] #VIEW_PARAMS_HEIGHT} for more info on
     * parameters.
     *
     * @param params A map of the new parameters, see [email protected] #VIEW_PARAMS_HEIGHT}
     */
public void setMonthParams(HashMap<String, Integer> params) {
    if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {
        throw new InvalidParameterException("You must specify month and year for this view");
    }
    setTag(params);
    // We keep the current value for any params not present
    if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
        mRowHeight = params.get(VIEW_PARAMS_HEIGHT);
        if (mRowHeight < MIN_HEIGHT) {
            mRowHeight = MIN_HEIGHT;
        }
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) {
        mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY);
    }
    if (params.containsKey(VIEW_PARAMS_RANGE_MIN)) {
        mRangeMin = params.get(VIEW_PARAMS_RANGE_MIN);
    }
    if (params.containsKey(VIEW_PARAMS_RANGE_MAX)) {
        mRangeMax = params.get(VIEW_PARAMS_RANGE_MAX);
    }
    // Allocate space for caching the day numbers and focus values
    mMonth = params.get(VIEW_PARAMS_MONTH);
    mYear = params.get(VIEW_PARAMS_YEAR);
    // Figure out what day today is
    final Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();
    mHasToday = false;
    mToday = -1;
    mCalendar.set(Calendar.MONTH, mMonth);
    mCalendar.set(Calendar.YEAR, mYear);
    mCalendar.set(Calendar.DAY_OF_MONTH, 1);
    mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);
    if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
        mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
    } else {
        mWeekStart = mCalendar.getFirstDayOfWeek();
    }
    mNumCells = Utils.getDaysInMonth(mMonth, mYear);
    for (int i = 0; i < mNumCells; i++) {
        final int day = i + 1;
        if (sameDay(day, today)) {
            mHasToday = true;
            mToday = day;
        }
    }
    mNumRows = calculateNumRows();
    // Invalidate cached accessibility information.
    mTouchHelper.invalidateRoot();
}
Example 28
Project: transdroid-master  File: ApplicationSettings.java View source code
/**
	 * Stores the user settings for some specific app widget. Existing settings for the supplied app widget ID will be
	 * overridden.
	 * @param appWidgetId The unique ID of the app widget to store settings for, as supplied by the AppWidgetManager
	 * @param settings A widget configuration object, which may not be null
	 */
public void setWidgetConfig(int appWidgetId, ListWidgetConfig settings) {
    if (settings == null)
        throw new InvalidParameterException("The widget setting may not be null. Use removeWidgetConfig instead to remove existing settings for some app widget.");
    Editor edit = prefs.edit();
    edit.putInt("widget_server_" + appWidgetId, settings.getServerId());
    edit.putString("widget_status_" + appWidgetId, settings.getStatusType().name());
    edit.putString("widget_sortby_" + appWidgetId, settings.getSortBy().name());
    edit.putBoolean("widget_reverse_" + appWidgetId, settings.shouldReserveSort());
    edit.putBoolean("widget_showstatus_" + appWidgetId, settings.shouldShowStatusView());
    edit.putBoolean("widget_darktheme_" + appWidgetId, settings.shouldUseDarkTheme());
    edit.apply();
}
Example 29
Project: android-sdk-sources-for-api-level-23-master  File: AndroidKeyStoreCipherSpiBase.java View source code
private void init(int opmode, Key key, SecureRandom random) throws InvalidKeyException {
    switch(opmode) {
        case Cipher.ENCRYPT_MODE:
        case Cipher.WRAP_MODE:
            mEncrypting = true;
            break;
        case Cipher.DECRYPT_MODE:
        case Cipher.UNWRAP_MODE:
            mEncrypting = false;
            break;
        default:
            throw new InvalidParameterException("Unsupported opmode: " + opmode);
    }
    initKey(opmode, key);
    if (mKey == null) {
        throw new ProviderException("initKey did not initialize the key");
    }
    mRng = random;
}
Example 30
Project: HDP-2.2-Patched-master  File: OpenFileCtx.java View source code
/**
   * Check stream status to decide if it should be closed
   * @return true, remove stream; false, keep stream
   */
public synchronized boolean streamCleanup(long fileId, long streamTimeout) {
    if (streamTimeout < WriteManager.MINIMIUM_STREAM_TIMEOUT) {
        throw new InvalidParameterException("StreamTimeout" + streamTimeout + "ms is less than MINIMIUM_STREAM_TIMEOUT " + WriteManager.MINIMIUM_STREAM_TIMEOUT + "ms");
    }
    boolean flag = false;
    // Check the stream timeout
    if (checkStreamTimeout(streamTimeout)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("closing stream for fileId:" + fileId);
        }
        cleanup();
        flag = true;
    }
    return flag;
}