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: cistern-master  File: HmmTrainerFactory.java View source code
public static HmmTrainer getTrainer(Properties props) {
    String trainer_name = props.getHmmTrainer().toLowerCase();
    double delta_t = 1e-4;
    double delta_e = 1e-8;
    if (trainer_name.equalsIgnoreCase("simplehmmtrainer")) {
        return new SimpleHmmTrainer(delta_t, delta_e);
    } else if (trainer_name.equalsIgnoreCase("signaturehmmtrainer")) {
        return new SignatureHmmTrainer(delta_t, delta_e);
    } else {
        throw new InvalidParameterException("Unknown trainer name: " + trainer_name);
    }
}
Example 2
Project: ProcessPuzzleFramework-master  File: SaveCommentCommand.java View source code
public void init(CommandDispatcher dispatcher) {
    super.init(dispatcher);
    boolean ccerror = false;
    try {
        commentList = (CommentList) subjectArtifact;
    } catch (ClassCastException e) {
        ccerror = true;
    }
    if (ccerror || commentList == null)
        throw new InvalidParameterException("SaveComment: Wrong ID!");
    setUpResponse(dispatcher.getResponse());
}
Example 3
Project: stubgen-master  File: CharacterInstantiator.java View source code
@Override
public <T> T newInstance(Class<?> T) throws MockGenException {
    try {
        if (!T.isAssignableFrom(Character.class)) {
            throw new InvalidParameterException("The parameter must be of type " + Character.class.getName() + " or one of its subclasses");
        }
        @SuppressWarnings("unchecked") T casted = (T) new Character('a');
        return casted;
    } catch (Throwable t) {
        throw new MockGenException(t);
    }
}
Example 4
Project: Tstream-master  File: ThriftClient.java View source code
protected void flushClient(Map storm_conf, Integer timeout) throws Exception {
    try {
        flushHost();
        String[] host_port = masterHost.split(":");
        if (host_port.length != 2) {
            throw new InvalidParameterException("Host format error: " + masterHost);
        }
        String host = host_port[0];
        int port = Integer.parseInt(host_port[1]);
        LOG.info("Begin to connect " + host + ":" + port);
        // locate login configuration
        Configuration login_conf = AuthUtils.GetConfiguration(storm_conf);
        // construct a transport plugin
        ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(storm_conf, login_conf);
        // create a socket with server
        if (host == null) {
            throw new IllegalArgumentException("host is not set");
        }
        if (port <= 0) {
            throw new IllegalArgumentException("invalid port: " + port);
        }
        //			/***************only test for daily *************/
        //			if (host.endsWith("bja")) {
        //				host += ".tbsite.net";
        //			}
        //			/***************only test for daily *************/
        TSocket socket = new TSocket(host, port);
        if (timeout != null) {
            socket.setTimeout(timeout);
        }
        final TTransport underlyingTransport = socket;
        // establish client-server transport via plugin
        _transport = transportPlugin.connect(underlyingTransport, host);
    } catch (IOException ex) {
        throw new RuntimeException("Create transport error");
    }
    _protocol = null;
    if (_transport != null)
        _protocol = new TBinaryProtocol(_transport);
}
Example 5
Project: opennms_dashboard-master  File: SnmpIPAddress.java View source code
/**
     * <p>
     * Sets the internal string array so that it is identical to the passed
     * array. The array is actually copied so that changes to data after the
     * construction of the object are not reflected in the SnmpOctetString
     * Object.
     * </p>
     * 
     * <p>
     * If the buffer is not valid according to the SNMP SMI then an exception is
     * thrown and the object is not modified.
     * </p>
     * 
     * @param data
     *            The new octet string data.
     * 
     * @throws java.security.InvalidParameterException
     *             Thrown if the passed buffer is not valid against the SMI
     *             definition.
     */
public void setString(byte[] data) {
    if (data == null || data.length < 4)
        throw new java.security.InvalidParameterException("Buffer underflow error converting IP address");
    else if (data.length > 4)
        throw new java.security.InvalidParameterException("Buffer overflow error converting IP address");
    // use setString instead of assumeString to ensure
    // that a duplicate copy of the buffer is made.
    //
    super.setString(data);
}
Example 6
Project: jstorm-master  File: restart.java View source code
public static void main(String[] args) {
    if (args == null || args.length == 0) {
        throw new InvalidParameterException("Should input topology name");
    }
    String topologyName = args[0];
    NimbusClient client = null;
    try {
        Map conf = Utils.readStormConfig();
        client = NimbusClient.getConfiguredClient(conf);
        System.out.println("It will take 15 ~ 100 seconds to restart, please wait patiently\n");
        if (args.length == 1) {
            client.getClient().restart(topologyName, null);
        } else {
            Map loadConf = Utils.loadConf(args[1]);
            String jsonConf = Utils.to_json(loadConf);
            System.out.println("New configuration:\n" + jsonConf);
            client.getClient().restart(topologyName, jsonConf);
        }
        System.out.println("Successfully submit command restart " + topologyName);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
Example 7
Project: kalendra-java-utils-master  File: MatrixSumMatrixMatrix.java View source code
public Matrix sum(Matrix x, Matrix y, Matrix z) {
    //check dimensions
    if (x.getDimensionRows() != y.getDimensionRows()) {
        throw new InvalidParameterException("Row Dimensions don't match");
    }
    if (x.getDimensionCols() != y.getDimensionCols()) {
        throw new InvalidParameterException("Col Dimensions don't match");
    }
    //set the dimensions of z
    z.setDimensions(x.getDimensionRows(), x.getDimensionCols());
    //push the data into z
    for (int i = 0; i < x.getDimensionRows(); i++) {
        for (int j = 0; j < x.getDimensionCols(); j++) {
            z.setValue(i, j, x.getValue(i, j) + y.getValue(i, j));
        }
    }
    return z;
}
Example 8
Project: mWater-Android-App-master  File: Results.java View source code
public static Results getResults(TestType testType, String results) throws InvalidParameterException {
    switch(testType) {
        case PETRIFILM:
            return new PetrifilmResults(results);
        case TEN_ML_COLILERT:
            return new TenMLColilertResults(results);
        case HUNDRED_ML_ECOLI:
            return new HundredMLEColiResults(results);
        case CHLORINE:
            return new ChlorineResults(results);
        default:
            throw new InvalidParameterException("Test type unknown");
    }
}
Example 9
Project: TiM-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 10
Project: Timber-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 11
Project: TimelyTextView-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 12
Project: u2020-mvp-master  File: ActivityScreenSwitcher.java View source code
@Override
public void open(Screen screen) {
    final Activity activity = getAttachedObject();
    if (activity == null) {
        return;
    }
    if (screen instanceof ActivityScreen) {
        ActivityScreen activityScreen = ((ActivityScreen) screen);
        Intent intent = activityScreen.intent(activity);
        ActivityCompat.startActivity(activity, intent, activityScreen.activityOptions(activity));
    } else {
        throw new InvalidParameterException("Only ActivityScreen objects allowed");
    }
}
Example 13
Project: ulti-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 14
Project: UltimateAndroid-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 15
Project: Yhb-2.0-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 16
Project: ApkDownloader-master  File: RequestInterface.java View source code
/**
     * Get a parameter for a given index and do some type checking
     * 
     * @param params
     * @param i
     * @param c
     * @return
     */
protected Object getParam(Object[] params, int i, Class<?> c) {
    if (params.length < i + 1) {
        throw new InvalidParameterException("Not enough arguments");
    }
    Object o = params[i];
    if (!o.getClass().equals(c)) {
        throw new InvalidParameterException(String.format("Expected argument of type %s but got %s", o.getClass(), c));
    }
    return o;
}
Example 17
Project: iis-master  File: EmptyDatastoreVerifierProcess.java View source code
@Override
public void run(PortBindings portBindings, Configuration conf, Map<String, String> parameters) throws Exception {
    if (!portBindings.getInput().containsKey(INPUT_PORT_NAME)) {
        throw new InvalidParameterException("missing input port!");
    }
    try (CloseableIterator<?> closeableIt = getIterator(conf, portBindings.getInput().get(INPUT_PORT_NAME))) {
        File file = new File(System.getProperty(OOZIE_ACTION_OUTPUT_FILENAME));
        Properties props = new Properties();
        props.setProperty(OUTPUT_PROPERTY_IS_EMPTY, Boolean.toString(!closeableIt.hasNext()));
        try (OutputStream os = new FileOutputStream(file)) {
            props.store(os, "");
        }
    }
}
Example 18
Project: kodex-master  File: Padding.java View source code
@JsonCreator
public static Padding fromString(String padding) {
    if (padding.equals(CipherConstants.NO_PADDING)) {
        return NONE;
    } else if (padding.equals(CipherConstants.PKCS5_PADDING)) {
        return PKCS5;
    } else if (padding.equals(CipherConstants.OAEPWithSHA1AndMGF1Padding)) {
        return OAEPWithSHA1AndMGF1Padding;
    } else if (padding.equals(CipherConstants.OAEPWithSHA256AndMGF1Padding)) {
        return OAEPWithSHA256AndMGF1Padding;
    }
    throw new InvalidParameterException("Invalid padding: " + padding);
}
Example 19
Project: simple-spring-memcached-master  File: NamespaceBuilderTest.java View source code
@Test(expected = InvalidParameterException.class)
public void shouldThrowExceptionIfNamespaceIsNotProvided() throws Exception {
    final String method = "populateNamespace01";
    final Method targetMethod = new Mirror().on(AnnotationDataDummy.class).reflect().method(method).withArgs(String.class);
    final Annotation annotation = new Mirror().on(AnnotationDataDummy.class).reflect().annotation(expected).atMethod(method).withArgs(String.class);
    builder.populate(data, annotation, expected, targetMethod);
}
Example 20
Project: jnode-master  File: DIMMDriver.java View source code
protected void startDevice() throws org.jnode.driver.DriverException {
    dimmDevice = (DIMM) getDevice();
    // now read the SPD table
    try {
        if (!DIMMDriver.canExist(bus, address))
            throw new DriverException("Device doesn't exist");
        log.debug("Getting SPD Table from " + dimmDevice.getId() + ':');
        spdTableLength = (bus.readByte(address, (byte) 0)) & 0xff;
        log.debug(" length=" + spdTableLength);
        spdTable = new byte[spdTableLength];
        spdTable[0] = (byte) spdTableLength;
        for (int i = 1; i < spdTableLength; i++) spdTable[i] = bus.readByte(address, (byte) i);
        dimmDevice.setSPDTable(spdTable);
    } catch (UnsupportedOperationException ex) {
    } catch (IOException ex) {
    } catch (InvalidParameterException ex) {
    }
}
Example 21
Project: active-directory-android-master  File: LongSerializer.java View source code
/**
	 * Serializes a Long instance to a JsonElement, verifying the maximum and
	 * minimum allowed values
	 */
@Override
public JsonElement serialize(Long element, Type type, JsonSerializationContext ctx) {
    Long maxAllowedValue = 0x0020000000000000L;
    Long minAllowedValue = Long.valueOf(0xFFE0000000000000L);
    if (element != null) {
        if (element > maxAllowedValue || element < minAllowedValue) {
            throw new InvalidParameterException("Long value must be between " + minAllowedValue + " and " + maxAllowedValue);
        } else {
            return new JsonPrimitive(element);
        }
    } else {
        return JsonNull.INSTANCE;
    }
}
Example 22
Project: android-money-manager-ex-master  File: Recurrence.java View source code
public static Recurrence valueOf(int value) {
    // set auto execute without user acknowledgement
    if (value >= 200) {
        value = value - 200;
    }
    // set auto execute on the next occurrence
    if (value >= 100) {
        value = value - 100;
    }
    for (Recurrence item : Recurrence.values()) {
        if (item.getValue() == value) {
            return item;
        }
    }
    //        return null;
    throw new InvalidParameterException();
}
Example 23
Project: android-runtime-master  File: Generator.java View source code
/**
     * @param args
     */
public static void main(String[] args) throws Exception {
    String outName = "bin";
    String[] params = null;
    if (args != null && args.length > 0) {
        outName = args[0];
        File out = new File(outName);
        if (!out.exists()) {
            out.mkdir();
            System.out.println(String.format("We didn't find the folder you specified ( %s ), so it's going to be created!", out.getAbsolutePath()));
        }
    } else {
        throw new InvalidParameterException("You need to pass an output directory!");
    }
    if (args != null && args.length > 1) {
        params = new String[args.length - 1];
        for (int i = 1; i < args.length; i++) {
            params[i - 1] = args[i];
        }
    }
    if (params == null) {
        throw new InvalidParameterException("You need to pass a list of jar paths, so metadata can be generated for them!");
    }
    TreeNode root = Builder.build(params);
    FileOutputStream ovs = new FileOutputStream(new File(outName, "treeValueStream.dat"));
    FileStreamWriter outValueStream = new FileStreamWriter(ovs);
    FileOutputStream ons = new FileOutputStream(new File(outName, "treeNodeStream.dat"));
    FileStreamWriter outNodeStream = new FileStreamWriter(ons);
    FileOutputStream oss = new FileOutputStream(new File(outName, "treeStringsStream.dat"));
    FileStreamWriter outStringsStream = new FileStreamWriter(oss);
    new Writer(outNodeStream, outValueStream, outStringsStream).writeTree(root);
}
Example 24
Project: athere-android-master  File: TableLiteCanonicalizer.java View source code
/**
     * Constructs a canonicalized string for signing a request.
     * 
     * @param conn
     *            the HttpURLConnection to canonicalize
     * @param accountName
     *            the account name associated with the request
     * @param contentLength
     *            the length of the content written to the outputstream in bytes, -1 if unknown
     * @return a canonicalized string.
     * @throws StorageException
     */
@Override
protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength) throws StorageException {
    if (contentLength < -1) {
        throw new InvalidParameterException(SR.INVALID_CONTENT_LENGTH);
    }
    final String dateString = Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.DATE);
    if (Utility.isNullOrEmpty(dateString)) {
        throw new IllegalArgumentException(SR.MISSING_MANDATORY_DATE_HEADER);
    }
    final StringBuilder canonicalizedString = new StringBuilder(ExpectedTableLiteCanonicalizedStringLength);
    canonicalizedString.append(dateString);
    appendCanonicalizedElement(canonicalizedString, getCanonicalizedResourceLite(conn.getURL(), accountName));
    return canonicalizedString.toString();
}
Example 25
Project: azure-storage-android-master  File: TableCanonicalizer.java View source code
/**
     * Constructs a canonicalized string for signing a request.
     * 
     * @param conn
     *            the HttpURLConnection to canonicalize
     * @param accountName
     *            the account name associated with the request
     * @param contentLength
     *            the length of the content written to the outputstream in bytes, -1 if unknown
     * @return a canonicalized string.
     * @throws StorageException
     */
@Override
protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength) throws StorageException {
    if (contentLength < -1) {
        throw new InvalidParameterException(SR.INVALID_CONTENT_LENGTH);
    }
    return canonicalizeTableHttpRequest(conn.getURL(), accountName, conn.getRequestMethod(), Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, conn);
}
Example 26
Project: azure-storage-java-master  File: TableCanonicalizer.java View source code
/**
     * Constructs a canonicalized string for signing a request.
     * 
     * @param conn
     *            the HttpURLConnection to canonicalize
     * @param accountName
     *            the account name associated with the request
     * @param contentLength
     *            the length of the content written to the outputstream in bytes, -1 if unknown
     * @return a canonicalized string.
     * @throws StorageException
     */
@Override
protected String canonicalize(final HttpURLConnection conn, final String accountName, final Long contentLength) throws StorageException {
    if (contentLength < -1) {
        throw new InvalidParameterException(SR.INVALID_CONTENT_LENGTH);
    }
    return canonicalizeTableHttpRequest(conn.getURL(), accountName, conn.getRequestMethod(), Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, conn);
}
Example 27
Project: bc-java-master  File: KeyPairGeneratorSpi.java View source code
public void initialize(int strength, SecureRandom random) {
    this.strength = strength;
    this.random = random;
    if (ecParams != null) {
        param = new ECKeyGenerationParameters(new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN()), random);
        engine.init(param);
        initialised = true;
    } else {
        throw new InvalidParameterException("unknown key size.");
    }
}
Example 28
Project: bugvm-master  File: OpenSSLECKeyPairGenerator.java View source code
@Override
public void initialize(int keysize, SecureRandom random) {
    final String name = SIZE_TO_CURVE_NAME.get(keysize);
    if (name == null) {
        throw new InvalidParameterException("unknown key size " + keysize);
    }
    /*
         * Store the group in a temporary variable until we know this is a valid
         * group.
         */
    final OpenSSLECGroupContext possibleGroup = OpenSSLECGroupContext.getCurveByName(name);
    if (possibleGroup == null) {
        throw new InvalidParameterException("unknown curve " + name);
    }
    group = possibleGroup;
}
Example 29
Project: cmestemp22-master  File: LuceneFieldBooster.java View source code
/**
     * Sets a field weight, creates the field if it doens't exist.
     *
     * @param inFormatString
     *            the format string.
     *
     * @param fieldName
     *            the field.
     * @param weight
     *            the weight.
     *
     * @return the formatted string.
     */
public String boostField(final String inFormatString, final String fieldName, final int weight) {
    if (!allowableBoostFields.contains(fieldName)) {
        throw new InvalidParameterException("The input field name is not in the list of allowed fields.");
    }
    String formatString = inFormatString;
    Pattern searchPattern = Pattern.compile(fieldName + ":\\(%1\\$s\\)(\\^[0-9]+)?");
    Matcher patternMatcher = searchPattern.matcher(formatString);
    if (patternMatcher.find()) {
        formatString = patternMatcher.replaceFirst(fieldName + ":(%1\\$s)^" + weight);
    } else {
        formatString += " " + fieldName + ":(%1$s)^" + weight;
    }
    return formatString;
}
Example 30
Project: contrail-vcenter-plugin-master  File: TaskWatchDogHttpHandler.java View source code
@Override
public void handle(HttpExchange t) throws IOException {
    OutputStream os = t.getResponseBody();
    String uri = t.getRequestURI().toString();
    ContentType contentType = ContentType.getContentType(uri);
    TaskWatchDogReq req = null;
    try {
        req = new TaskWatchDogReq(t.getRequestURI());
    } catch (InvalidParameterException e) {
    }
    if (req == null || !uri.startsWith("/") || contentType != ContentType.REQUEST) {
        // suspecting path traversal attack
        Headers h = t.getResponseHeaders();
        h.set("Content-Type", ContentType.HTML.toString());
        String response = "403 (Forbidden)\n";
        t.sendResponseHeaders(403, response.getBytes().length);
        os.close();
        return;
    }
    // Presentation layer
    // Accept with response code 200.
    t.sendResponseHeaders(200, 0);
    Headers h = t.getResponseHeaders();
    h.set("Content-Type", contentType.toString());
    TaskWatchDogResp resp = new TaskWatchDogResp(req);
    // serialize the actual response object in XML
    StringBuilder s = new StringBuilder().append("<?xml-stylesheet type=\"").append(ContentType.XSL).append("\" href=\"").append(styleSheet).append("\"?>");
    resp.writeObject(s);
    os.write(s.toString().getBytes());
    os.close();
}
Example 31
Project: dbpool-master  File: FlatfileProvider.java View source code
@Override
public DataSource getDataSource(String instance, int access, String pattern) {
    if (!instance.isEmpty() && !pattern.isEmpty()) {
        throw new InvalidParameterException("FlatfileProvider support only empty instance name and pattern name.");
    }
    if (access == DBPool.READ_ACCESS) {
        return source.getDataSource(read);
    } else if (access == DBPool.WRITE_ACCESS) {
        return source.getDataSource(write);
    } else {
        logger.error("FlatfileProvider is outdated with DBPool");
        throw new InvalidParameterException("FlatfileProvider is outdated. This should never happen.");
    }
}
Example 32
Project: Desktop-master  File: Account.java View source code
public void enableButton(final String buttonText, final String buttonAction) {
    if (buttonText == null)
        throw new InvalidParameterException("First parameter cannot be NULL!");
    if (buttonAction == null)
        throw new InvalidParameterException("Second parameter cannot be NULL!");
    this.buttonText = buttonText;
    this.buttonAction = buttonAction;
}
Example 33
Project: Docear-master  File: Account.java View source code
public void enableButton(final String buttonText, final String buttonAction) {
    if (buttonText == null)
        throw new InvalidParameterException("First parameter cannot be NULL!");
    if (buttonAction == null)
        throw new InvalidParameterException("Second parameter cannot be NULL!");
    this.buttonText = buttonText;
    this.buttonAction = buttonAction;
}
Example 34
Project: EasySOA-Incubation-master  File: OperationInformation.java View source code
public void mergeWith(OperationInformation operation) throws InvalidParameterException {
    if (!operation.name.equals(this.name)) {
        throw new InvalidParameterException("Can't merge operations whose names don't match");
    }
    if (operation.parameters != null) {
        this.parameters = operation.parameters;
    }
    if (operation.returnParameters != null) {
        this.returnParameters = operation.returnParameters;
    }
    if (operation.documentation != null && operation.documentation.length() != 0) {
        if (this.documentation != null && this.documentation.length() != 0) {
            this.documentation += "\n\nAdditional documentation:\n" + // TODO i18n
            operation.documentation;
        } else {
            this.documentation = operation.documentation;
        }
    }
    if (operation.inContentType != null) {
        this.inContentType = operation.inContentType;
    }
    if (operation.outContentType != null) {
        this.outContentType = operation.outContentType;
    }
}
Example 35
Project: eurekastreams-master  File: LuceneFieldBooster.java View source code
/**
     * Sets a field weight, creates the field if it doens't exist.
     *
     * @param inFormatString
     *            the format string.
     *
     * @param fieldName
     *            the field.
     * @param weight
     *            the weight.
     *
     * @return the formatted string.
     */
public String boostField(final String inFormatString, final String fieldName, final int weight) {
    if (!allowableBoostFields.contains(fieldName)) {
        throw new InvalidParameterException("The input field name is not in the list of allowed fields.");
    }
    String formatString = inFormatString;
    Pattern searchPattern = Pattern.compile(fieldName + ":\\(%1\\$s\\)(\\^[0-9]+)?");
    Matcher patternMatcher = searchPattern.matcher(formatString);
    if (patternMatcher.find()) {
        formatString = patternMatcher.replaceFirst(fieldName + ":(%1\\$s)^" + weight);
    } else {
        formatString += " " + fieldName + ":(%1$s)^" + weight;
    }
    return formatString;
}
Example 36
Project: irma_future_id-master  File: KeyPairGeneratorSpi.java View source code
public void initialize(int strength, SecureRandom random) {
    this.strength = strength;
    this.random = random;
    if (ecParams != null) {
        param = new ECKeyGenerationParameters(new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN()), random);
        engine.init(param);
        initialised = true;
    } else {
        throw new InvalidParameterException("unknown key size.");
    }
}
Example 37
Project: jst-master  File: restart.java View source code
public static void main(String[] args) {
    if (args == null || args.length == 0) {
        throw new InvalidParameterException("Please input topology name!");
    }
    String topologyName = args[0];
    NimbusClient client = null;
    try {
        Map conf = Utils.readStormConfig();
        client = NimbusClient.getConfiguredClient(conf);
        System.out.println("It will take 15 ~ 100 seconds to restart, please wait patiently\n");
        if (args.length == 1) {
            client.getClient().restart(topologyName, null);
        } else {
            Map loadConf = Utils.loadConf(args[1]);
            String jsonConf = Utils.to_json(loadConf);
            System.out.println("New configuration:\n" + jsonConf);
            client.getClient().restart(topologyName, jsonConf);
        }
        System.out.println("Successfully submit command restart " + topologyName);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}
Example 38
Project: LeetCode-Sol-Res-master  File: Utils.java View source code
public static TreeNode buildBinaryTree(Integer[] values) {
    if (values == null || values.length == 0) {
        throw new InvalidParameterException("values should not be null or empty");
    }
    TreeNode root = new TreeNode(values[0]);
    Queue<TreeNode> queue = new ArrayDeque<>();
    queue.offer(root);
    int i = 1;
    while (!queue.isEmpty() && i < values.length) {
        TreeNode node = queue.poll();
        if (i < values.length && values[i] != null) {
            node.left = new TreeNode(values[i]);
            queue.offer(node.left);
        }
        if (i + 1 < values.length && values[i + 1] != null) {
            node.right = new TreeNode(values[i + 1]);
            queue.offer(node.right);
        }
        i += 2;
    }
    return root;
}
Example 39
Project: ListenerMusicPlayer-master  File: NumberUtils.java View source code
public static float[][] getControlPointsFor(int start) {
    switch(start) {
        case (-1):
            return Null.getInstance().getControlPoints();
        case 0:
            return Zero.getInstance().getControlPoints();
        case 1:
            return One.getInstance().getControlPoints();
        case 2:
            return Two.getInstance().getControlPoints();
        case 3:
            return Three.getInstance().getControlPoints();
        case 4:
            return Four.getInstance().getControlPoints();
        case 5:
            return Five.getInstance().getControlPoints();
        case 6:
            return Six.getInstance().getControlPoints();
        case 7:
            return Seven.getInstance().getControlPoints();
        case 8:
            return Eight.getInstance().getControlPoints();
        case 9:
            return Nine.getInstance().getControlPoints();
        default:
            throw new InvalidParameterException("Unsupported number requested");
    }
}
Example 40
Project: nikeplus-fuelband-se-reversed-master  File: CopperheadCRC32.java View source code
public void update(byte[] array) throws InvalidParameterException {
    if (array.length % 4 != 0) {
        throw new InvalidParameterException("Length of data must be a multiple of 4");
    }
    for (int i = 0; i < array.length; ++i) {
        this.mValue ^= array[i ^ 0x3] << 24;
        for (int j = 0; j < 8; ++j) {
            if ((Integer.MIN_VALUE & this.mValue) != 0x0) {
                this.mValue = (0x4C11DB7 ^ this.mValue << 1);
            } else {
                this.mValue <<= 1;
            }
        }
    }
}
Example 41
Project: openjdk-master  File: TestDH2048.java View source code
@Override
public void main(Provider p) throws Exception {
    if (p.getService("KeyPairGenerator", "DH") == null) {
        System.out.println("KPG for DH not supported, skipping");
        return;
    }
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH", p);
    kpg.initialize(512);
    KeyPair kp1 = kpg.generateKeyPair();
    kpg.initialize(768);
    kp1 = kpg.generateKeyPair();
    kpg.initialize(1024);
    kp1 = kpg.generateKeyPair();
    kpg.initialize(1536);
    kp1 = kpg.generateKeyPair();
    kpg.initialize(2048);
    kp1 = kpg.generateKeyPair();
    try {
        kpg.initialize(3072);
        kp1 = kpg.generateKeyPair();
        kpg.initialize(4096);
        kp1 = kpg.generateKeyPair();
        kpg.initialize(6144);
        kp1 = kpg.generateKeyPair();
        kpg.initialize(8192);
        kp1 = kpg.generateKeyPair();
    } catch (InvalidParameterException ipe) {
        System.out.println("4096-bit DH key pair generation: " + ipe);
        if (!p.getName().equals("SunPKCS11-NSS")) {
            throw ipe;
        }
    }
    // key size must be multiples of 64 though
    checkUnsupportedKeySize(kpg, 2048 + 63);
    checkUnsupportedKeySize(kpg, 3072 + 32);
}
Example 42
Project: RipplePower-master  File: BaseKeyGenerator.java View source code
protected void engineInit(int keySize, SecureRandom random) {
    try {
        if (random == null) {
            random = new SecureRandom();
        }
        engine.init(new KeyGenerationParameters(random, keySize));
        uninitialised = false;
    } catch (IllegalArgumentException e) {
        throw new InvalidParameterException(e.getMessage());
    }
}
Example 43
Project: robovm-master  File: DSAKeyPairGeneratorTest.java View source code
/**
     * java.security.interfaces.DSAKeyPairGenerator
     * #initialize(DSAParams params, SecureRandom random)
     */
public void test_DSAKeyPairGenerator01() {
    DSAParams dsaParams = new DSAParameterSpec(p, q, g);
    SecureRandom random = null;
    MyDSA dsa = new MyDSA(dsaParams);
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (Exception e) {
        fail("Unexpected exception for SecureRandom: " + e);
    }
    try {
        dsa.initialize(dsaParams, random);
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    }
    try {
        dsa.initialize(dsaParams, null);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
    try {
        dsa.initialize(null, random);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
}
Example 44
Project: rsine-master  File: CmdParams.java View source code
private void checkParams() {
    boolean incompleteParams = false;
    if (managedStoreSparqlEndpoint == null) {
        logger.error("No SPARQL endpoint of the managed triple store provided");
        incompleteParams = true;
    }
    if (port == null) {
        logger.error("No change listening port provided");
        incompleteParams = true;
    }
    if (incompleteParams) {
        throw new InvalidParameterException("Provide missing parameters either on command line or in the configuration file " + Rsine.propertiesFileName);
    }
}
Example 45
Project: RxCache-master  File: RxCache.java View source code
/**
     * Sets the File cache system and the implementation of [email protected] JolyglotGenerics} to serialise
     * and deserialize objects
     *
     * @param cacheDirectory The File system used by the persistence implementation of Disk
     * @param jolyglot A concrete implementation of [email protected] JolyglotGenerics}
     */
public RxCache persistence(File cacheDirectory, JolyglotGenerics jolyglot) {
    if (cacheDirectory == null) {
        throw new InvalidParameterException(io.rx_cache2.internal.Locale.REPOSITORY_DISK_ADAPTER_CAN_NOT_BE_NULL);
    }
    if (!cacheDirectory.exists()) {
        throw new InvalidParameterException(io.rx_cache2.internal.Locale.REPOSITORY_DISK_ADAPTER_DOES_NOT_EXIST);
    }
    if (!cacheDirectory.canWrite()) {
        throw new InvalidParameterException(io.rx_cache2.internal.Locale.REPOSITORY_DISK_ADAPTER_IS_NOT_WRITABLE);
    }
    if (jolyglot == null) {
        throw new InvalidParameterException(io.rx_cache2.internal.Locale.JSON_CONVERTER_CAN_NOT_BE_NULL);
    }
    this.cacheDirectory = cacheDirectory;
    this.jolyglot = jolyglot;
    return new RxCache(this);
}
Example 46
Project: sakuli-master  File: ScreenBasedSettings.java View source code
@PostConstruct
public void setDefaults() {
    setMinSimilarity(currentSimilarity);
    WaitScanRate = 10f;
    ObserveScanRate = 10f;
    ClickDelay = props.getClickDelay();
    RobotDesktop.stdAutoDelay = props.getTypeDelayMs();
    //if stdAutoDelay is set TypeDelay is no longer needed!
    TypeDelay = 0;
    OcrDataPath = sakuliProps.getTessDataLibFolder().toAbsolutePath().toString();
    OcrTextSearch = true;
    OcrTextRead = true;
    Highlight = props.isAutoHighlightEnabled();
    if (props.getDefaultHighlightSeconds() < 1) {
        /**
             * because of the mehtode [email protected] org.sikuli.script.ScreenHighlighter#closeAfter(float)}
             * */
        throw new InvalidParameterException("the property '" + ActionProperties.DEFAULT_HIGHLIGHT_SEC + "' has to be greater as 1, but was " + props.getDefaultHighlightSeconds());
    }
    DefaultHighlightTime = props.getDefaultHighlightSeconds();
    WaitAfterHighlight = 0.1f;
    /***
         * Logging for sikuliX => [email protected] SysOutOverSLF4J} will send the logs to SLF4J
         */
    Logger sikuliLogger = LoggerFactory.getLogger(Debug.class);
    if (sikuliLogger.isInfoEnabled()) {
        LOGGER.debug("sikuli log level INFO enabled");
        ActionLogs = true;
        InfoLogs = true;
        ProfileLogs = true;
    }
    if (sikuliLogger.isDebugEnabled()) {
        LOGGER.debug("sikuli log level DEBUG enabled");
        DebugLogs = true;
    }
}
Example 47
Project: scoop-master  File: Keyboard.java View source code
private static Window getWindow(Context context) {
    if (context instanceof Activity) {
        Activity activity = (Activity) context;
        return activity.getWindow();
    } else if (context instanceof ContextWrapper) {
        ContextWrapper contextWrapper = (ContextWrapper) context;
        return getWindow(contextWrapper.getBaseContext());
    } else {
        throw new InvalidParameterException("Cannot find activity context");
    }
}
Example 48
Project: SEEPng-master  File: RouterFactory.java View source code
@Deprecated
public static Router buildRouterFor(List<DownstreamConnection> cons) {
    if (cons.size() < 1) {
        throw new InvalidParameterException("Tried to build router with less than 1 connection");
    }
    boolean stateful = cons.get(0).getDownstreamOperator().isStateful();
    Router rs = null;
    List<Integer> opIds = getListOpId(cons);
    if (stateful) {
        LOG.info("Building ConsistentHashingRoutingState Router");
        rs = new ConsistentHashingRoutingState(opIds);
    } else {
        LOG.info("Building RoundRobinRoutingState Router");
        rs = new RoundRobinRoutingState(opIds);
    }
    return rs;
}
Example 49
Project: siren-master  File: RandomSirenCodec.java View source code
private PostingsFormat newSiren10PostingsFormat() {
    final int blockSize = this.newRandomBlockSize();
    final int i = random.nextInt(2);
    switch(i) {
        case 0:
            return new Siren10VIntPostingsFormat(blockSize);
        case 1:
            return new Siren10AForPostingsFormat(blockSize);
        default:
            throw new InvalidParameterException();
    }
}
Example 50
Project: tracecompass-master  File: TraceEnablement.java View source code
/**
     * @param name
     *            name of the desired enum
     * @return the corresponding [email protected] TraceEnablement} matching name
     */
public static TraceEnablement valueOfString(String name) {
    if (name == null) {
        throw new InvalidParameterException();
    }
    for (TraceEnablement enablementType : TraceEnablement.values()) {
        boolean exist = enablementType.fInName.equalsIgnoreCase(name) || enablementType.fInMiName.equalsIgnoreCase(name);
        if (exist) {
            return enablementType;
        }
    }
    return DISABLED;
}
Example 51
Project: all-inhonmodman-master  File: DownloadThread.java View source code
public DownloadThread call() throws UpdateModException {
    try {
        Thread.currentThread().setName("Download - " + modName);
        if (url != null) {
            URL urls = new URL(this.url);
            URLConnection connection = urls.openConnection();
            connection.setConnectTimeout(7500);
            InputStream is = urls.openStream();
            String filename = null;
            if (path == null || path.isEmpty()) {
                String pattern = "[^a-z,A-Z,0-9, ,.]";
                filename = this.url.substring(this.url.lastIndexOf("/") + 1).replace("%20", " ");
                filename = filename.replaceAll(pattern, "");
            } else {
                filename = path;
            }
            FileOutputStream fos = null;
            file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename);
            fos = new FileOutputStream(file, false);
            FileUtils.copyInputStream(is, fos);
            is.close();
            fos.flush();
            fos.close();
        }
    } catch (MalformedURLException ex) {
        System.out.println(ex);
        file = null;
        throw new UpdateModException(null, ex);
    } catch (ConnectException ex) {
        System.out.println(ex);
        file = null;
        throw new UpdateModException(null, ex);
    } catch (NullPointerException ex) {
        System.out.println(ex);
        file = null;
        throw new UpdateModException(null, ex);
    } catch (InvalidParameterException ex) {
        System.out.println(ex);
        file = null;
        throw new UpdateModException(null, ex);
    } catch (FileNotFoundException ex) {
        System.out.println(ex);
        file = null;
        throw new UpdateModException(null, ex);
    } catch (IOException ex) {
        System.out.println(ex);
        file = null;
        throw new UpdateModException(null, ex);
    }
    return this;
}
Example 52
Project: android-15-master  File: DSAKeyPairGeneratorImpl.java View source code
public void initialize(int modlen, boolean genParams, SecureRandom random) throws InvalidParameterException {
    int len = 512;
    while (len <= 1024) {
        if (len == modlen) {
            lengthModulus = modlen;
            break;
        } else {
            len = len + 8;
            if (len == 1032) {
                throw new InvalidParameterException("Incorrect modlen");
            }
        }
    }
    if (modlen < 512 || modlen > 1024) {
        throw new InvalidParameterException("Incorrect modlen");
    }
    if (random == null) {
        throw new InvalidParameterException("Incorrect random");
    }
    if (genParams == false && dsaParams == null) {
        throw new InvalidParameterException("there are not precomputed parameters");
    }
    secureRandom = random;
}
Example 53
Project: android-libcore64-master  File: DSAKeyPairGeneratorTest.java View source code
/**
     * java.security.interfaces.DSAKeyPairGenerator
     * #initialize(DSAParams params, SecureRandom random)
     */
public void test_DSAKeyPairGenerator01() {
    DSAParams dsaParams = new DSAParameterSpec(p, q, g);
    SecureRandom random = null;
    MyDSA dsa = new MyDSA(dsaParams);
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (Exception e) {
        fail("Unexpected exception for SecureRandom: " + e);
    }
    try {
        dsa.initialize(dsaParams, random);
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    }
    try {
        dsa.initialize(dsaParams, null);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
    try {
        dsa.initialize(null, random);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
}
Example 54
Project: android-sdk-sources-for-api-level-23-master  File: DSAKeyPairGeneratorImpl.java View source code
public void initialize(int modlen, boolean genParams, SecureRandom random) throws InvalidParameterException {
    int len = 512;
    while (len <= 1024) {
        if (len == modlen) {
            lengthModulus = modlen;
            break;
        } else {
            len = len + 8;
            if (len == 1032) {
                throw new InvalidParameterException("Incorrect modlen");
            }
        }
    }
    if (modlen < 512 || modlen > 1024) {
        throw new InvalidParameterException("Incorrect modlen");
    }
    if (random == null) {
        throw new InvalidParameterException("Incorrect random");
    }
    if (genParams == false && dsaParams == null) {
        throw new InvalidParameterException("there are not precomputed parameters");
    }
    secureRandom = random;
}
Example 55
Project: android_libcore-master  File: KeyPairGeneratorSpiTest.java View source code
/**
     * Test for <code>KeyPairGeneratorSpi</code> constructor 
     * Assertion: constructs KeyPairGeneratorSpi
     */
@TestTargets({ @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "KeyPairGeneratorSpi", args = {}), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "generateKeyPair", args = {}), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "initialize", args = { java.security.spec.AlgorithmParameterSpec.class, java.security.SecureRandom.class }), @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "initialize", args = { int.class, java.security.SecureRandom.class }) })
public void testKeyPairGeneratorSpi01() throws InvalidAlgorithmParameterException, InvalidParameterException {
    KeyPairGeneratorSpi keyPairGen = new MyKeyPairGeneratorSpi();
    AlgorithmParameterSpec pp = null;
    try {
        keyPairGen.initialize(pp, null);
        fail("UnsupportedOperationException must be thrown");
    } catch (UnsupportedOperationException e) {
    }
    keyPairGen.initialize(pp, new SecureRandom());
    keyPairGen.initialize(1024, new SecureRandom());
    try {
        keyPairGen.initialize(-1024, new SecureRandom());
        fail("IllegalArgumentException must be thrown for incorrect keysize");
    } catch (IllegalArgumentException e) {
    }
    try {
        keyPairGen.initialize(1024, null);
        fail("IllegalArgumentException must be thrown");
    } catch (IllegalArgumentException e) {
        assertEquals("Incorrect exception", e.getMessage(), "Invalid random");
    }
    KeyPair kp = keyPairGen.generateKeyPair();
    assertNull("Not null KeyPair", kp);
}
Example 56
Project: android_platform_libcore-master  File: DSAKeyPairGeneratorTest.java View source code
/**
     * java.security.interfaces.DSAKeyPairGenerator
     * #initialize(DSAParams params, SecureRandom random)
     */
public void test_DSAKeyPairGenerator01() {
    DSAParams dsaParams = new DSAParameterSpec(p, q, g);
    SecureRandom random = null;
    MyDSA dsa = new MyDSA(dsaParams);
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (Exception e) {
        fail("Unexpected exception for SecureRandom: " + e);
    }
    try {
        dsa.initialize(dsaParams, random);
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    }
    try {
        dsa.initialize(dsaParams, null);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
    try {
        dsa.initialize(null, random);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
}
Example 57
Project: ARTPart-master  File: DSAKeyPairGeneratorTest.java View source code
/**
     * java.security.interfaces.DSAKeyPairGenerator
     * #initialize(DSAParams params, SecureRandom random)
     */
public void test_DSAKeyPairGenerator01() {
    DSAParams dsaParams = new DSAParameterSpec(p, q, g);
    SecureRandom random = null;
    MyDSA dsa = new MyDSA(dsaParams);
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (Exception e) {
        fail("Unexpected exception for SecureRandom: " + e);
    }
    try {
        dsa.initialize(dsaParams, random);
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    }
    try {
        dsa.initialize(dsaParams, null);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
    try {
        dsa.initialize(null, random);
        fail("InvalidParameterException was not thrown");
    } catch (InvalidParameterException ipe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of InvalidParameterException");
    }
}
Example 58
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 59
Project: i2p.i2p-master  File: KeyPairGenerator.java View source code
/**
     *  @param strength must be 2048
     *  @param random ignored
     */
public void initialize(int strength, SecureRandom random) {
    if (strength != DEFAULT_STRENGTH)
        throw new InvalidParameterException("unknown key type.");
    elgParams = I2P_ELGAMAL_2048_SPEC;
    try {
        initialize(elgParams, random);
    } catch (InvalidAlgorithmParameterException e) {
        throw new InvalidParameterException("key type not configurable.");
    }
}
Example 60
Project: j2objc-master  File: KeyPairGeneratorSpiTest.java View source code
/**
     * Test for <code>KeyPairGeneratorSpi</code> constructor
     * Assertion: constructs KeyPairGeneratorSpi
     */
public void testKeyPairGeneratorSpi01() throws InvalidAlgorithmParameterException, InvalidParameterException {
    KeyPairGeneratorSpi keyPairGen = new MyKeyPairGeneratorSpi();
    AlgorithmParameterSpec pp = null;
    try {
        keyPairGen.initialize(pp, null);
        fail("UnsupportedOperationException must be thrown");
    } catch (UnsupportedOperationException e) {
    }
    keyPairGen.initialize(pp, new SecureRandom());
    keyPairGen.initialize(1024, new SecureRandom());
    try {
        keyPairGen.initialize(-1024, new SecureRandom());
        fail("IllegalArgumentException must be thrown for incorrect keysize");
    } catch (IllegalArgumentException e) {
    }
    try {
        keyPairGen.initialize(1024, null);
        fail("IllegalArgumentException must be thrown");
    } catch (IllegalArgumentException e) {
        assertEquals("Incorrect exception", e.getMessage(), "Invalid random");
    }
    KeyPair kp = keyPairGen.generateKeyPair();
    assertNull("Not null KeyPair", kp);
}
Example 61
Project: Java-HandlerSocket-Connection-master  File: HSOpenIndexQuery.java View source code
@Override
public void encode(SafeByteStream output) {
    if (null == indexDescriptor) {
        throw new InvalidParameterException("indexDescriptor can't be null");
    }
    output.writeBytes(HSProto.OPERATOR_OPEN_INDEX, false);
    output.writeBytes(HSProto.TOKEN_DELIMITER_AS_BYTES, false);
    output.writeString(indexDescriptor.getIndexId(), false);
    output.writeBytes(HSProto.TOKEN_DELIMITER_AS_BYTES, false);
    output.writeString(indexDescriptor.getDbName(), true);
    output.writeBytes(HSProto.TOKEN_DELIMITER_AS_BYTES, false);
    output.writeString(indexDescriptor.getTableName(), true);
    output.writeBytes(HSProto.TOKEN_DELIMITER_AS_BYTES, false);
    output.writeString(indexDescriptor.getIndexName(), true);
    output.writeBytes(HSProto.TOKEN_DELIMITER_AS_BYTES, false);
    output.writeStrings(indexDescriptor.getColumns(), new byte[] { ',' }, true);
    if (indexDescriptor.hasFilterColumns()) {
        output.writeBytes(HSProto.TOKEN_DELIMITER_AS_BYTES, false);
        output.writeStrings(indexDescriptor.getFilterColumns(), COMMA_DELIMITER, true);
    }
    output.writeBytes(HSProto.PACKET_DELIMITER_AS_BYTES, false);
}
Example 62
Project: jdkernel-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 63
Project: nuxeo-master  File: BareElasticSearchFeature.java View source code
@Override
public void start(FeaturesRunner runner) throws Exception {
    File home = Framework.getRuntime().getHome();
    File esDirectory = new File(home, "elasticsearch");
    if (!esDirectory.exists() && !esDirectory.mkdir()) {
        throw new InvalidParameterException("Can not create directory: " + esDirectory.getAbsolutePath());
    }
    Settings settings = Settings.settingsBuilder().put("node.http.enabled", true).put("path.home", esDirectory.getPath()).put("path.logs", esDirectory.getPath() + "/logs").put("path.data", esDirectory.getPath() + "/data").put("index.store.type", "mmapfs").put("index.number_of_shards", 1).put("index.number_of_replicas", 1).build();
    node = NodeBuilder.nodeBuilder().local(true).settings(settings).node();
    client = node.client();
    super.start(runner);
}
Example 64
Project: OEUpdater-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 65
Project: onexus-master  File: ZipProjectProvider.java View source code
@Override
protected void importProject() {
    try {
        byte[] buffer = new byte[1024];
        URL url = new URL(getProjectUrl());
        ZipInputStream zis = new ZipInputStream(url.openStream());
        ZipEntry ze = zis.getNextEntry();
        File projectFolder = getProjectFolder();
        if (!projectFolder.exists()) {
            projectFolder.mkdir();
        } else {
            FileUtils.cleanDirectory(projectFolder);
        }
        while (ze != null) {
            String fileName = ze.getName();
            File newFile = new File(projectFolder, fileName);
            if (ze.isDirectory()) {
                newFile.mkdir();
            } else {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            ze = zis.getNextEntry();
        }
        zis.close();
    } catch (Exception e) {
        LOGGER.error("Importing project '" + getProjectUrl() + "'", e);
        throw new InvalidParameterException("Invalid Onexus URL project");
    }
//To change body of implemented methods use File | Settings | File Templates.
}
Example 66
Project: poetry-master  File: QueryUtils.java View source code
/**
     * Convert an Object to a String so that it can be used as a query parameter.
     * This method supports objects instantiated or derived from:
     * Integer, Long, Float, Double, Boolean, Short, Byte, CharSequence and Date
     *
     * @param object the object to convert
     * @return the String representing the input object
     * @throws InvalidParameterException when the input object is not supported
     */
public static String parseAttribute(Object object) throws InvalidParameterException {
    if (Integer.class.isAssignableFrom(object.getClass())) {
        return Integer.toString((Integer) object);
    } else if (Long.class.isAssignableFrom(object.getClass())) {
        return Long.toString((Long) object);
    } else if (Float.class.isAssignableFrom(object.getClass())) {
        return Float.toString((Float) object);
    } else if (Double.class.isAssignableFrom(object.getClass())) {
        return Double.toString((Double) object);
    } else if (Boolean.class.isAssignableFrom(object.getClass())) {
        return Boolean.toString((Boolean) object);
    } else if (Short.class.isAssignableFrom(object.getClass())) {
        return Short.toString((Short) object);
    } else if (Byte.class.isAssignableFrom(object.getClass())) {
        return Byte.toString((Byte) object);
    } else if (CharSequence.class.isAssignableFrom(object.getClass()) || Date.class.isAssignableFrom(object.getClass())) {
        return object.toString();
    } else {
        throw new InvalidParameterException("parameter type not supported: " + object.getClass().getName());
    }
}
Example 67
Project: property-db-master  File: DSAKeyPairGeneratorImpl.java View source code
public void initialize(int modlen, boolean genParams, SecureRandom random) throws InvalidParameterException {
    int len = 512;
    while (len <= 1024) {
        if (len == modlen) {
            lengthModulus = modlen;
            break;
        } else {
            len = len + 8;
            if (len == 1032) {
                throw new InvalidParameterException("Incorrect modlen");
            }
        }
    }
    if (modlen < 512 || modlen > 1024) {
        throw new InvalidParameterException("Incorrect modlen");
    }
    if (random == null) {
        throw new InvalidParameterException("Incorrect random");
    }
    if (genParams == false && dsaParams == null) {
        throw new InvalidParameterException("there are not precomputed parameters");
    }
    secureRandom = random;
}
Example 68
Project: revolance-ui-monitoring-master  File: ContentComparator.java View source code
@Override
public Collection<ElementComparison> compare(Collection<ElementBean> content, Collection<ElementBean> reference) {
    List<ElementComparison> comparisons = new ArrayList();
    List<ElementBean> addedElements = new ArrayList(content);
    for (ElementBean element : content) {
        ElementComparison comparison = null;
        try {
            Collection<ElementMatch> matches = elementMatcher.findMatch(reference, element, ElementSearchMethod.VALUE, ElementSearchMethod.LOOK);
            ElementMatch match = elementMatcher.getBestMatch(matches);
            reference.remove(match.getReference());
            addedElements.remove(match.getMatch());
            Collection<ElementDifferency> differencies = elementComparator.compare(element, match.getReference());
            if (differencies.isEmpty()) {
                comparison = BaseComparison(match);
            } else {
                comparison = ChangedComparison(match);
                comparison.setElementDifferencies(differencies);
            }
        } catch (NoMatchFound noMatchFound) {
            comparison = new DeletedComparison(element).invoke();
        } catch (InvalidParameterException e) {
        }
        if (comparison != null) {
            addedElements.remove(element);
            comparisons.add(comparison);
        }
    }
    for (ElementBean element : addedElements) {
        comparisons.add(new DeletedComparison(element).invoke());
    }
    for (ElementBean element : reference) {
        new DeletedComparison(element);
        comparisons.add(new AddedComparison(element).invoke());
    }
    return comparisons;
}
Example 69
Project: service-proxy-master  File: SMSTokenProvider.java View source code
@Override
public void requestToken(Map<String, String> userAttributes) {
    String token = generateToken(userAttributes);
    String recipientNumber;
    synchronized (userAttributes) {
        recipientNumber = userAttributes.get("sms");
    }
    if (recipientNumber == null)
        throw new InvalidParameterException("User does not have the 'sms' attribute");
    recipientNumber = normalizeNumber(recipientNumber);
    String text = prefixText + token;
    if (simulate)
        log.error("Send SMS '" + text + "' to " + recipientNumber);
    else
        sendSMS(text, recipientNumber);
}
Example 70
Project: SMUpdater-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 71
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 72
Project: thingsboard-master  File: MsgTypeFilter.java View source code
@Override
public void init(MsgTypeFilterConfiguration configuration) {
    msgTypes = Arrays.stream(configuration.getMessageTypes()).map( type -> {
        switch(type) {
            case "GET_ATTRIBUTES":
                return MsgType.GET_ATTRIBUTES_REQUEST;
            case "POST_ATTRIBUTES":
                return MsgType.POST_ATTRIBUTES_REQUEST;
            case "POST_TELEMETRY":
                return MsgType.POST_TELEMETRY_REQUEST;
            case "RPC_REQUEST":
                return MsgType.TO_SERVER_RPC_REQUEST;
            default:
                throw new InvalidParameterException("Can't map " + type + " to " + MsgType.class.getName() + "!");
        }
    }).collect(Collectors.toList());
}
Example 73
Project: warmupdater-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 74
Project: bi-platform-v2-master  File: SimpleContentGenerator.java View source code
@Override
public void createContent() throws Exception {
    OutputStream out = null;
    if (outputHandler == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("SimpleContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER"));
        //$NON-NLS-1$
        throw new InvalidParameterException(Messages.getInstance().getString("SimpleContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER"));
    }
    IParameterProvider requestParams = parameterProviders.get(IParameterProvider.SCOPE_REQUEST);
    String solutionName = null;
    if (requestParams != null) {
        //$NON-NLS-1$
        solutionName = requestParams.getStringParameter("solution", null);
    }
    if (solutionName == null) {
        solutionName = "NONE";
    }
    if (instanceId == null) {
        setInstanceId(UUIDUtil.getUUIDAsString());
    }
    //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    IContentItem contentItem = outputHandler.getOutputContentItem("response", "content", solutionName, instanceId, getMimeType());
    if (contentItem == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("SimpleContentGenerator.ERROR_0002_NO_CONTENT_ITEM"));
        //$NON-NLS-1$
        throw new InvalidParameterException(Messages.getInstance().getString("SimpleContentGenerator.ERROR_0002_NO_CONTENT_ITEM"));
    }
    contentItem.setMimeType(getMimeType());
    out = contentItem.getOutputStream(itemName);
    if (out == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("SimpleContentGenerator.ERROR_0003_NO_OUTPUT_STREAM"));
        //$NON-NLS-1$
        throw new InvalidParameterException(Messages.getInstance().getString("SimpleContentGenerator.ERROR_0003_NO_OUTPUT_STREAM"));
    }
    createContent(out);
    try {
        // we created the output stream, let's be sure it's closed
        // do not leave it up to the implementations of SimpleContentGenerator
        // do do this or not
        out.flush();
        out.close();
    } catch (Exception ignored) {
    }
}
Example 75
Project: Breakbulk-master  File: OntologyElement.java View source code
/**
     * Validate that this Ontology element has all the proper values
     */
public void validate() {
    if (uri == null)
        throw new InvalidParameterException("OntologyElement uri must not be null.");
    if (javaPackage == null)
        throw new InvalidParameterException("OntologyElement javaPackage must not be null.");
    if (path == null)
        throw new InvalidParameterException("OntologyElement path must not be null.");
}
Example 76
Project: buddycloud-server-java-master  File: NodeViewAcl.java View source code
public boolean canViewNode(String node, Affiliations affilliation, Subscriptions subscription, AccessModels accessModel, boolean isLocalUser) {
    LOGGER.trace("Being asked for access to " + node + " with properties " + affilliation + " :: " + subscription + " :: " + accessModel + " :: local user (" + String.valueOf(isLocalUser) + ")");
    reasonForRefusal = null;
    if (Affiliations.outcast.equals(affilliation)) {
        reasonForRefusal = new NodeAclRefuseReason(PacketError.Type.auth, PacketError.Condition.forbidden, null);
        return false;
    }
    if (accessModel.equals(AccessModels.open)) {
        return openChannelAcl(node, subscription, affilliation);
    } else if (accessModel.equals(AccessModels.authorize)) {
        return privateChannelAcl(node, subscription, affilliation);
    } else if (accessModel.equals(AccessModels.whitelist)) {
        return whitelistAcl(node, subscription, affilliation);
    } else if (accessModel.equals(AccessModels.local)) {
        if (true == isLocalUser) {
            return openChannelAcl(node, subscription, affilliation);
        }
        return privateChannelAcl(node, subscription, affilliation);
    }
    throw new InvalidParameterException(INVALID_ACCESS_MODEL);
}
Example 77
Project: cgeo-master  File: ParametersTest.java View source code
public static void testException() {
    try {
        final Parameters params = new Parameters("aaa", "AAA", "bbb");
        // this will never be invoked, but suppresses warnings about unused objects
        params.clear();
        fail("Exception not raised");
    } catch (final InvalidParameterException e) {
    }
    try {
        final Parameters params = new Parameters("aaa", "AAA");
        params.put("bbb", "BBB", "ccc");
        fail("Exception not raised");
    } catch (final InvalidParameterException e) {
    }
}
Example 78
Project: CLAVIN-master  File: ListUtils.java View source code
/**
     * Splits a list into a set of sublists (preserving order) where
     * the size of each sublist is bound by a given max size, and
     * ensuring that no list has fewer than half the max size number
     * of elements.
     * 
     * In other words, you won't get a little rinky-dink sublist at the
     * end that only has one or two items from the original list.
     * 
     * Based on: http://www.chinhdo.com/20080515/chunking/
     * 
     * @param list          list to be chunkified
     * @param maxChunkSize  how big you want the chunks to be
     * @return              a chunkified list (i.e., list of sublists)
     */
public static <T> List<List<T>> chunkifyList(List<T> list, int maxChunkSize) {
    // sanity-check input param
    if (maxChunkSize < 1)
        throw new InvalidParameterException("maxChunkSize must be greater than zero");
    // initialize return object
    List<List<T>> chunkedLists = new ArrayList<List<T>>();
    // no need to break it up into chunks
    if (list.size() <= maxChunkSize) {
        chunkedLists.add(list);
        return chunkedLists;
    }
    // initialize counters
    int index = 0;
    int count;
    // up with tiny runt chunks at the end
    while (index < list.size() - (maxChunkSize * 2)) {
        count = Math.min(index + maxChunkSize, list.size());
        chunkedLists.add(list.subList(index, count));
        index += maxChunkSize;
    }
    // take whatever's left, split it into two relatively-equal
    // chunks, and add these to the return object
    count = index + ((list.size() - index) / 2);
    chunkedLists.add(list.subList(index, count));
    chunkedLists.add(list.subList(count, list.size()));
    return chunkedLists;
}
Example 79
Project: D-MARLA-master  File: ClientNetworkAdapterUseCase.java View source code
@Override
public void connectToServer(String hostname, int port, String clientName) throws HostUnreachableException, InvalidParameterException, TechnicalException {
    InetAddress address;
    Socket socket;
    NetworkAccessProtocol protocol;
    try {
        //try to open the control port
        address = InetAddress.getByName(hostname);
        socket = new Socket(address, port);
        protocol = new NetworkAccessProtocol(socket);
        // say hello and wait for ack
        protocol.writeMessage(new ClientJoinMessage(-1, clientName));
        NetworkMessage message = protocol.readMessage();
        //if that is successful establish control channel and try to open data connection
        if (message instanceof ClientAckMessage) {
            clientId = message.getClientId();
            controlChannel = new NetworkChannel<NetworkMessage>(protocol, this);
            if (currentClassLoader != null) {
                controlChannel.setContextClassLoader(currentClassLoader);
            }
            controlChannel.start();
            socket = new Socket(address, port + 1);
            protocol = new NetworkAccessProtocol(socket);
            // say hello and wait for ack
            protocol.writeMessage(new ClientJoinMessage(clientId, clientName));
            message = protocol.readMessage();
            //if that worked, too, we can establish the data connection and are done
            if (message instanceof ClientAckMessage) {
                dataChannel = new NetworkChannel<NetworkMessage>(protocol, this);
                if (currentClassLoader != null) {
                    dataChannel.setContextClassLoader(currentClassLoader);
                }
                dataChannel.start();
            } else {
                // abort (we were so close..) :(
                throw new HostUnreachableException();
            }
        } else {
            // else abort :(
            throw new HostUnreachableException();
        }
    } catch (UnknownHostException e) {
        throw new HostUnreachableException();
    } catch (IOException e) {
        throw new TechnicalException(ErrorMessages.get("networkError"));
    } catch (ConnectionLostException e) {
        throw new HostUnreachableException();
    }
    connected = true;
}
Example 80
Project: dashreports-master  File: StandardSymmetricUtil.java View source code
@Override
public String generateKey() throws EncryptionException {
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance(engine);
        keyGen.init(keySize);
        SecretKey key = keyGen.generateKey();
        return bytesToHex(key.getEncoded());
    } catch (NoSuchAlgorithmException nsae) {
        throw new EncryptionException(nsae);
    } catch (InvalidParameterException ipe) {
        throw new EncryptionException(ipe);
    }
}
Example 81
Project: Facility-Access-Manager-master  File: PrecheckUserInsertionController.java View source code
private boolean emailExists(JSONObject user) {
    boolean result = false;
    try {
        result = FamDaoProxy.userDao().getUsersWithEMail(user.getString("mail")).size() > 0;
    } catch (JSONException e) {
        FamLog.exception("error reading json", e, 201111020943l);
        result = true;
    } catch (InvalidParameterException e) {
        FamLog.exception("sql injection " + user.toString(), e, 201204260846l);
        result = true;
    }
    return result;
}
Example 82
Project: FontZip-master  File: Subsetter.java View source code
public void setCMaps(List<CMapTable.CMapId> paramList, int paramInt) {
    this.cmapIds = new ArrayList();
    CMapTable localCMapTable = (CMapTable) this.font.getTable(Tag.cmap);
    if (localCMapTable == null) {
        throw new InvalidParameterException("Font has no cmap table.");
    }
    Iterator localIterator = paramList.iterator();
    while (localIterator.hasNext()) {
        CMapTable.CMapId localCMapId = (CMapTable.CMapId) localIterator.next();
        CMap localCMap = localCMapTable.cmap(localCMapId);
        if (localCMap != null) {
            this.cmapIds.add(localCMap.cmapId());
            paramInt--;
            if (paramInt <= 0) {
                break;
            }
        }
    }
    if (this.cmapIds.size() == 0) {
        this.cmapIds = null;
        throw new InvalidParameterException("CMap Id settings would generate font with no cmap sub-table.");
    }
}
Example 83
Project: GenPlay-master  File: PASortFile.java View source code
@Override
protected Boolean processAction() throws Exception {
    File selectedFile = FileChooser.chooseFile(getRootPane(), FileChooser.OPEN_FILE_MODE, "Select File to Sort", Utils.getSortableFileFilters(), false);
    if (selectedFile != null) {
        if (!Utils.cancelBecauseFileExist(getRootPane(), ExternalSortAdapter.generateOutputFile(selectedFile))) {
            notifyActionStart("Sorting File", 1, false);
            try {
                ExternalSortAdapter.externalSortGenomicFile(selectedFile);
                return true;
            } catch (InvalidParameterException e) {
                WarningReportDialog.getInstance().addMessage(e.getMessage());
                WarningReportDialog.getInstance().showDialog(getRootPane());
            }
        }
    }
    return false;
}
Example 84
Project: groupbasedpolicy-master  File: LispUtil.java View source code
public static Ipv4 toIpv4(String ipStr) throws InvalidParameterException {
    String[] strArray = ipStr.split("/");
    if (strArray.length == 0 || strArray.length > 2) {
        throw new InvalidParameterException("Parameter " + ipStr + " is invalid for IPv4");
    }
    if (strArray.length == 2) {
        int mask = Integer.valueOf(strArray[1]);
        if (mask != 32) {
            throw new InvalidParameterException("Parameter " + ipStr + " is invalid for IPv4");
        }
    }
    return new Ipv4Builder().setIpv4(new Ipv4Address(strArray[0])).build();
}
Example 85
Project: ISAAC-master  File: ObjectChronologyType.java View source code
//~--- methods -------------------------------------------------------------
/**
    * Parses the.
    *
    * @param nameOrEnumId the name or enum id
    * @param exceptionOnParseFail the exception on parse fail
    * @return the object chronology type
    */
public static ObjectChronologyType parse(String nameOrEnumId, boolean exceptionOnParseFail) {
    if (nameOrEnumId == null) {
        return null;
    }
    final String clean = nameOrEnumId.toLowerCase(Locale.ENGLISH).trim();
    if (StringUtils.isBlank(clean)) {
        return null;
    }
    for (final ObjectChronologyType ct : values()) {
        if (ct.name().toLowerCase(Locale.ENGLISH).equals(clean) || ct.niceName.toLowerCase(Locale.ENGLISH).equals(clean) || (ct.ordinal() + "").equals(clean)) {
            return ct;
        }
    }
    if (exceptionOnParseFail) {
        throw new InvalidParameterException("Could not determine ObjectChronologyType from " + nameOrEnumId);
    }
    return UNKNOWN_NID;
}
Example 86
Project: jetty-bootstrap-master  File: ExplodedWarAppJettyHandler.java View source code
@Override
protected String getAppTempDirName() {
    try {
        if (webAppBase != null) {
            return Md5Util.hash(webAppBase);
        }
        if (webAppBaseFromClasspath != null) {
            return Md5Util.hash(webAppBaseFromClasspath);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Md5 Sum Error", e);
    }
    throw new InvalidParameterException("webAppBase or webAppBaseFromClasspath required");
}
Example 87
Project: kaa-master  File: CacheTemporaryMemorizer.java View source code
/**
   * Compute.
   *
   * @param key    the key
   * @param worker the worker
   * @return the v
   */
public V compute(final K key, final Computable<K, V> worker) {
    if (key == null) {
        throw new InvalidParameterException("Cache key can't be null");
    }
    while (true) {
        Future<V> future = cache.get(key);
        if (future == null) {
            Callable<V> eval = new Callable<V>() {

                public V call() throws InterruptedException {
                    return worker.compute(key);
                }
            };
            FutureTask<V> ft = new FutureTask<V>(eval);
            future = cache.putIfAbsent(key, ft);
            if (future == null) {
                future = ft;
                try {
                    ft.run();
                //the idea is not to cache permanently but only for the time of execution.
                //thus, technically, if time of calculation >> time of external
                // cache put -> we will run calculation maximum 2 times.
                } catch (Throwable ex) {
                    LOG.error("Exception catched: ", ex);
                    throw ex;
                } finally {
                    cache.remove(key, ft);
                }
            }
        }
        try {
            return future.get();
        } catch (CancellationException ex) {
            LOG.error("Exception catched: ", ex);
            cache.remove(key, future);
        } catch (ExecutionExceptionInterruptedException |  ex) {
            LOG.error("Exception catched: ", ex);
            throw launderThrowable(ex);
        }
    }
}
Example 88
Project: kasahorow-Keyboard-For-Android-master  File: HardKeyboardSequenceHandler.java View source code
public void addQwertyTranslation(String targetCharacters) {
    if (msQwerty.length != targetCharacters.length())
        throw new InvalidParameterException("'targetCharacters' should be the same length as the latin QWERTY keys strings: " + msQwerty);
    for (int qwertyIndex = 0; qwertyIndex < msQwerty.length; qwertyIndex++) {
        char latinCharacter = (char) msQwerty[qwertyIndex];
        char otherCharacter = targetCharacters.charAt(qwertyIndex);
        if (otherCharacter > 0) {
            this.addSequence(new int[] { latinCharacter }, otherCharacter);
            this.addSequence(new int[] { KeyCodes.SHIFT, latinCharacter }, Character.toUpperCase(otherCharacter));
        }
    }
}
Example 89
Project: openflexo-master  File: CreateViewPointPalette.java View source code
@Override
protected void doAction(Object context) throws DuplicateResourceException, NotImplementedException, InvalidParameterException {
    logger.info("Add calc palette");
    _newPalette = ViewPointPalette.newCalcPalette(getFocusedObject(), new File(getFocusedObject().getViewPointDirectory(), newPaletteName + ".palette"), graphicalRepresentation);
    _newPalette.setDescription(description);
    getFocusedObject().addToCalcPalettes(_newPalette);
    _newPalette.save();
}
Example 90
Project: pentaho-platform-master  File: SimpleContentGenerator.java View source code
@Override
public void createContent() throws Exception {
    OutputStream out = null;
    if (outputHandler == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("SimpleContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER"));
        throw new InvalidParameterException(Messages.getInstance().getString(//$NON-NLS-1$
        "SimpleContentGenerator.ERROR_0001_NO_OUTPUT_HANDLER"));
    }
    if (instanceId == null) {
        setInstanceId(UUIDUtil.getUUIDAsString());
    }
    //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    IContentItem contentItem = outputHandler.getOutputContentItem("response", "content", instanceId, getMimeType());
    if (contentItem == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("SimpleContentGenerator.ERROR_0002_NO_CONTENT_ITEM"));
        throw new InvalidParameterException(Messages.getInstance().getString(//$NON-NLS-1$
        "SimpleContentGenerator.ERROR_0002_NO_CONTENT_ITEM"));
    }
    contentItem.setMimeType(getMimeType());
    out = contentItem.getOutputStream(itemName);
    if (out == null) {
        //$NON-NLS-1$
        error(Messages.getInstance().getErrorString("SimpleContentGenerator.ERROR_0003_NO_OUTPUT_STREAM"));
        throw new InvalidParameterException(Messages.getInstance().getString(//$NON-NLS-1$
        "SimpleContentGenerator.ERROR_0003_NO_OUTPUT_STREAM"));
    }
    createContent(out);
    try {
        // we created the output stream, let's be sure it's closed
        // do not leave it up to the implementations of SimpleContentGenerator
        // do do this or not
        out.flush();
        out.close();
    } catch (Exception ignored) {
    }
}
Example 91
Project: qcadoo-incubator-master  File: Organizations.java View source code
public Response createTeam(String organization, String name, String permission, String... repo_names) {
    if (organization.equals("") || name.equals("") || permission.equals("") || repo_names.length == 0) {
        throw new InvalidParameterException("Missing information");
    }
    String post = "team[name]=" + encode(name) + "&team[permission]=" + encode(name);
    for (int i = 0; i < repo_names.length; i++) {
        post += "&team[repo_names][]=" + encode(repo_names[i]);
    }
    return HTTPPost("https://github.com/api/v2/json/organizations/" + encode(organization) + "/teams", post);
}
Example 92
Project: sejda-master  File: PdfPageTransition.java View source code
/**
     * Creates a new [email protected] PdfPageTransition} instance.
     * 
     * @param style
     * @param transitionDuration
     * @param displayDuration
     * @return the newly created instance.
     * @throws InvalidParameterException
     *             if the input transition or display duration is not positive. if the input style is null.
     */
public static PdfPageTransition newInstance(PdfPageTransitionStyle style, int transitionDuration, int displayDuration) {
    if (transitionDuration < 1) {
        throw new InvalidParameterException("Input transition duration must be positive.");
    }
    if (displayDuration < 1) {
        throw new InvalidParameterException("Input display duration must be positive.");
    }
    if (style == null) {
        throw new InvalidParameterException("Input style cannot be null.");
    }
    return new PdfPageTransition(style, transitionDuration, displayDuration);
}
Example 93
Project: texai-master  File: FileSystemUtils.java View source code
/** Deletes the supplied [email protected] File} - for directories,
   * recursively delete any nested directories or files as well.
   *
   * @param root the root <code>File</code> to delete
   * @return <code>true</code> if the <code>File</code> was deleted,
   * otherwise <code>false</code>
   */
public static boolean deleteRecursively(final File root) {
    //Preconditions
    if (root == null) {
        throw new InvalidParameterException("root must not be null");
    }
    if (root.exists()) {
        if (root.isDirectory()) {
            final File[] children = root.listFiles();
            if (children != null) {
                for (final File child : children) {
                    deleteRecursively(child);
                }
            }
        }
        return root.delete();
    }
    return false;
}
Example 94
Project: ts-android-master  File: FirstTabFragment.java View source code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_first_tab, container, false);
    mTranslator = AppContext.getTranslator();
    mLibrary = AppContext.getLibrary();
    Bundle args = getArguments();
    final String targetTranslationId = args.getString(AppContext.EXTRA_TARGET_TRANSLATION_ID, null);
    TargetTranslation targetTranslation = mTranslator.getTargetTranslation(targetTranslationId);
    if (targetTranslation == null) {
        throw new InvalidParameterException("a valid target translation id is required");
    }
    ImageButton newTabButton = (ImageButton) rootView.findViewById(R.id.newTabButton);
    LinearLayout secondaryNewTabButton = (LinearLayout) rootView.findViewById(R.id.secondaryNewTabButton);
    TextView translationTitle = (TextView) rootView.findViewById(R.id.source_translation_title);
    SourceLanguage sourceLanguage = mLibrary.getPreferredSourceLanguage(targetTranslation.getProjectId(), Locale.getDefault().getLanguage());
    translationTitle.setText(sourceLanguage.projectTitle + " - " + targetTranslation.getTargetLanguageName());
    View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            Fragment prev = getFragmentManager().findFragmentByTag("tabsDialog");
            if (prev != null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);
            ChooseSourceTranslationDialog dialog = new ChooseSourceTranslationDialog();
            Bundle args = new Bundle();
            args.putString(ChooseSourceTranslationDialog.ARG_TARGET_TRANSLATION_ID, targetTranslationId);
            dialog.setOnClickListener(FirstTabFragment.this);
            dialog.setArguments(args);
            dialog.show(ft, "tabsDialog");
        }
    };
    newTabButton.setOnClickListener(clickListener);
    secondaryNewTabButton.setOnClickListener(clickListener);
    // attach to tabs dialog
    if (savedInstanceState != null) {
        ChooseSourceTranslationDialog dialog = (ChooseSourceTranslationDialog) getFragmentManager().findFragmentByTag("tabsDialog");
        if (dialog != null) {
            dialog.setOnClickListener(this);
        }
    }
    return rootView;
}
Example 95
Project: uhabits-master  File: HabitViewActions.java View source code
@Override
public void perform(UiController uiController, View view) {
    if (view.getId() != R.id.checkmarkPanel)
        throw new InvalidParameterException("View must have id llButtons");
    LinearLayout llButtons = (LinearLayout) view;
    int count = llButtons.getChildCount();
    for (int i = 0; i < count; i++) {
        TextView tvButton = (TextView) llButtons.getChildAt(i);
        clickAction.perform(uiController, tvButton);
    }
}
Example 96
Project: wahlzeit-master  File: ImageStorage.java View source code
// write-methods ---------------------------------------------------------------------------------------------------
/**
	 * Writes the image to the storage, so you can access it via photoId and size again. An existing file with that
	 * parameter is overwritten.
	 *
	 * @methodtype command
	 * @methodproperty wrapper
	 */
public void writeImage(Serializable image, String photoIdAsString, int size) throws InvalidParameterException, IOException {
    assertImageNotNull(image);
    assertValidPhotoId(photoIdAsString);
    PhotoSize.assertIsValidPhotoSizeAsInt(size);
    log.config(LogBuilder.createSystemMessage().addAction("write image to storage").addParameter("image", image).addParameter("photo id", photoIdAsString).addParameter("size", size).toString());
    doWriteImage(image, photoIdAsString, size);
}
Example 97
Project: XobotOS-master  File: JCEKeyGenerator.java View source code
protected void engineInit(int keySize, SecureRandom random) {
    try {
        // BEGIN android-added
        if (random == null) {
            random = new SecureRandom();
        }
        // END android-added
        engine.init(new KeyGenerationParameters(random, keySize));
        uninitialised = false;
    } catch (IllegalArgumentException e) {
        throw new InvalidParameterException(e.getMessage());
    }
}
Example 98
Project: yamcs-master  File: PpTupleTranslator.java View source code
@Override
public Tuple buildTuple(TupleDefinition tdef, ClientMessage message) {
    Tuple t = null;
    try {
        ParameterData pd = (ParameterData) Protocol.decode(message, ParameterData.newBuilder());
        TupleDefinition tupleDef = tdef.copy();
        ArrayList<Object> columns = new ArrayList<Object>(4 + pd.getParameterCount());
        columns.add(message.getLongProperty(ParameterDataLinkInitialiser.PARAMETER_TUPLE_COL_GENTIME));
        columns.add(message.getStringProperty(ParameterDataLinkInitialiser.PARAMETER_TUPLE_COL_GROUP));
        columns.add(message.getIntProperty(ParameterDataLinkInitialiser.PARAMETER_TUPLE_COL_SEQ_NUM));
        columns.add(message.getLongProperty(ParameterDataLinkInitialiser.PARAMETER_TUPLE_COL_RECTIME));
        for (ParameterValue pv : pd.getParameterList()) {
            String processedParameterName = pv.getId().getName();
            if (processedParameterName == null || "".equals(processedParameterName)) {
                throw new InvalidParameterException("Processed Parameter must have a name.");
            }
            tupleDef.addColumn(processedParameterName, DataType.PARAMETER_VALUE);
            columns.add(org.yamcs.parameter.ParameterValue.fromGpb(processedParameterName, pv));
        }
        t = new Tuple(tupleDef, columns);
    } catch (YamcsApiException e) {
        throw new IllegalArgumentException(e.toString());
    }
    return t;
}
Example 99
Project: yibo-library-master  File: EncryptUtil.java View source code
public static String desEncrypt(String plain, byte[] keyBytes) {
    if (plain == null) {
        return null;
    }
    if (keyBytes == null || keyBytes.length != 8) {
        throw new InvalidParameterException("DES key must be 8 bytes ");
    }
    String encrypted = plain;
    if (DES_CYPHER != null) {
        try {
            SecretKey key = new SecretKeySpec(keyBytes, "DES");
            DES_CYPHER.init(Cipher.ENCRYPT_MODE, key);
            encrypted = new String(Base64.encodeBase64(DES_CYPHER.doFinal(plain.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return encrypted;
}
Example 100
Project: YiBo-master  File: EncryptUtil.java View source code
public static String desEncrypt(String plain, byte[] keyBytes) {
    if (plain == null) {
        return null;
    }
    if (keyBytes == null || keyBytes.length != 8) {
        throw new InvalidParameterException("DES key must be 8 bytes ");
    }
    String encrypted = plain;
    if (DES_CYPHER != null) {
        try {
            SecretKey key = new SecretKeySpec(keyBytes, "DES");
            DES_CYPHER.init(Cipher.ENCRYPT_MODE, key);
            encrypted = new String(Base64.encodeBase64(DES_CYPHER.doFinal(plain.getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return encrypted;
}
Example 101
Project: zaproxy-master  File: StructuralTableNode.java View source code
@Override
public StructuralNode getParent() throws DatabaseException {
    if (parent == null && !this.isRoot()) {
        RecordStructure prs = Model.getSingleton().getDb().getTableStructure().read(rs.getSessionId(), rs.getStructureId());
        if (prs == null) {
            throw new InvalidParameterException("Failed to find parent sessionId=" + rs.getSessionId() + " parentId=" + rs.getParentId());
        }
        parent = new StructuralTableNode(prs);
    }
    return parent;
}