Example usage for java.security InvalidParameterException InvalidParameterException

List of usage examples for java.security InvalidParameterException InvalidParameterException

Introduction

In this page you can find the example usage for java.security InvalidParameterException InvalidParameterException.

Prototype

public InvalidParameterException(String msg) 

Source Link

Document

Constructs an InvalidParameterException with the specified detail message.

Usage

From source file:org.eurekastreams.server.service.actions.strategies.links.ConnectionFacade.java

/**
 * @param inConnectionTimeOut/*from w  w w.j  a  v a  2  s .c o m*/
 *            the connectionTimeOut to set
 */
public final void setConnectionTimeOut(final int inConnectionTimeOut) {
    // the following takes care of input validation
    if (inConnectionTimeOut < MIN_TIMEOUT || inConnectionTimeOut > MAX_TIMEOUT) {
        throw new InvalidParameterException(
                "Connection timeout must be between " + MIN_TIMEOUT + " and " + MAX_TIMEOUT);
    }
    connectionTimeOut = inConnectionTimeOut;
}

From source file:eu.bittrade.libs.steemj.protocol.operations.AccountWitnessProxyOperation.java

@Override
public void validate(ValidationType validationType) {
    if (!ValidationType.SKIP_VALIDATION.equals(validationType)
            && (this.getProxy() != null && this.getProxy().equals(account))) {
        throw new InvalidParameterException("You can't proxy yourself.");
    }//  ww  w.  j av  a 2 s  .  c o  m
}

From source file:org.zaproxy.zap.extension.callgraph.CallGraphFrame.java

/**
 * sets up the graph by retrieving the nodes and edges from the history table in the database
 *
 * @param urlPattern//  w w w  .  j  ava  2s  .c  o  m
 * @throws SQLException
 */
private void setupGraph(Pattern urlPattern) throws SQLException {
    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    Map<String, String> schemaAuthorityToColor = new HashMap<String, String>();
    // use some web safe colours. Currently, there are 24 colours.
    String[] colors = { "#FFFF00", "#FFCC00", "#FF9900", "#FF6600", "#FF3300", "#CCFF00", "#CCCC00", "#CC9900",
            "#CC6600", "#99FF00", "#999900", "#996600", "#CCFFCC", "#CCCCCC", "#99CCCC", "#9999CC", "#9966CC",
            "#66FFCC", "#6699CC", "#6666CC", "#33FFCC", "#33CCCC", "#3399CC", "#00FFCC" };
    int colorsUsed = 0;
    try {
        // Create a pattern for the specified

        // get a new connection to the database to query it, since the existing database classes
        // do not cater for
        // ad-hoc queries on the table
        /*
         * TODO Add-ons should NOT make their own connections to the db any more - the db layer is plugable
         * so could be implemented in a completely different way
         * TODO: how? There is currently no API to do this.
         */
        // Note: the db is a singleton instance, so do *not* close it!!
        Database db = Model.getSingleton().getDb();
        if (!(db instanceof ParosDatabase)) {
            throw new InvalidParameterException(db.getClass().getCanonicalName());
        }

        conn = ((ParosDatabaseServer) db.getDatabaseServer()).getNewConnection();

        // we begin adding stuff to the graph, so begin a "transaction" on it.
        // we will close this after we add all the vertexes and edges to the graph
        graph.getModel().beginUpdate();

        // prepare to add the vertices to the graph
        // this must include all URLs references as vertices, even if those URLs did not feature
        // in the history table in their own right

        // include entries of type 1 (proxied), 2 (spidered), 10 (Ajax spidered) from the
        // history
        st = conn.createStatement();
        rs = st.executeQuery(
                "select distinct URI from HISTORY where histtype in (1,2,10) union distinct select distinct  RIGHT(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+') , LENGTH(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+'))-LENGTH('Referer: ')) from HISTORY where REQHEADER like '%Referer%' and histtype in (1,2,10) order by 1");
        for (; rs.next();) {
            String url = rs.getString(1);

            // remove urls that do not match the pattern specified (all sites / one site)
            Matcher urlmatcher = urlPattern.matcher(url);
            if (urlmatcher.find()) {
                // addVertex(url , url);
                try {
                    URI uri = new URI(url, false);
                    String schemaAuthority = uri.getScheme() + "://" + uri.getAuthority();
                    String path = uri.getPathQuery();
                    if (path == null)
                        path = "/";
                    String color = schemaAuthorityToColor.get(schemaAuthority);
                    if (color == null) {
                        // not found already.. so assign this scheme and authority a color.
                        if (colorsUsed >= colors.length) {
                            throw new Exception("Too many scheme/authority combinations. Ne need more colours");
                        }
                        color = colors[colorsUsed++];
                        schemaAuthorityToColor.put(schemaAuthority, color);
                    }
                    addVertex(path, url, "fillColor=" + color);
                } catch (Exception e) {
                    log.error("Error graphing node for URL " + url, e);
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug("URL " + url + " does not match the specified pattern " + urlPattern
                            + ", so not adding it as a vertex");
            }
        }
        // close the resultset and statement
        rs.close();
        st.close();

        // set up the edges in the graph
        st = conn.createStatement();
        rs = st.executeQuery(
                "select distinct RIGHT(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+') , LENGTH(REGEXP_SUBSTRING (REQHEADER, 'Referer:.+'))-LENGTH('Referer: ')), URI from HISTORY where REQHEADER like '%Referer%' and histtype in (1,2,10) order by 2");

        mxGraphModel graphmodel = (mxGraphModel) graph.getModel();
        for (; rs.next();) {
            String predecessor = rs.getString(1);
            String url = rs.getString(2);

            // now trim back all urls from the base url
            // Matcher predecessorurlmatcher = urlpattern.matcher(predecessor);
            // if (predecessorurlmatcher.find()) {
            //   predecessor =  predecessorurlmatcher.group(1);
            //   }
            // Matcher urlmatcher = urlpattern.matcher(url);
            // if (urlmatcher.find()) {
            //   url =  urlmatcher.group(1);
            //   }

            // remove urls that do not match the pattern specified (all sites / one site)
            Matcher urlmatcher1 = urlPattern.matcher(predecessor);
            if (!urlmatcher1.find()) {
                if (log.isDebugEnabled())
                    log.debug("Predecessor URL " + predecessor + " does not match the specified pattern "
                            + urlPattern + ", so not adding it as a vertex");
                continue; // to the next iteration
            }
            Matcher urlmatcher2 = urlPattern.matcher(url);
            if (!urlmatcher2.find()) {
                if (log.isDebugEnabled())
                    log.debug("URL " + url + " does not match the specified pattern " + urlPattern
                            + ", so not adding it as a vertex");
                continue; // to the next iteration
            }

            // check that we have added the url as a vertex in its own right.. definitely should
            // have happened..
            mxCell predecessorVertex = (mxCell) graphmodel.getCell(predecessor);
            mxCell postdecessorVertex = (mxCell) graphmodel.getCell(url);
            if (predecessorVertex == null || postdecessorVertex == null) {
                log.warn("Could not find graph node for " + predecessor + " or for " + url + ". Ignoring it.");
                continue;
            }
            // add the edge (ie, add the dependency between 2 URLs)
            graph.insertEdge(parent, predecessorVertex.getId() + "-->" + postdecessorVertex.getId(), null,
                    predecessorVertex, postdecessorVertex);
        }

        // once all the vertices and edges are drawn, look for root nodes (nodes with no
        // incoming edges)
        // we will display the full URl for these, rather than just the path, to aid viewing the
        // graph
        Object[] vertices = graph.getChildVertices(graph.getDefaultParent());
        for (Object vertex : vertices) {
            Object[] incomingEdgesForVertex = graph.getIncomingEdges(vertex);
            if (incomingEdgesForVertex == null
                    || (incomingEdgesForVertex != null && incomingEdgesForVertex.length == 0)) {
                // it's a root node. Set it's value (displayed label) to the same as it's id
                // (the full URL)
                mxCell vertextCasted = (mxCell) vertex;
                vertextCasted.setValue(vertextCasted.getId());

                // now sort out the text metrics for the vertex, since the size of the displayed
                // text has been changed
                Dimension textsize = this.getTextDimension((String) vertextCasted.getValue(), this.fontmetrics);
                mxGeometry cellGeometry = vertextCasted.getGeometry();
                cellGeometry.setHeight(textsize.getHeight());
                cellGeometry.setWidth(textsize.getWidth());
                vertextCasted.setGeometry(cellGeometry);
            }
        }
    } catch (SQLException e) {
        log.error("Error trying to setup the graph", e);
        throw e;
    } finally {

        if (rs != null && !rs.isClosed())
            rs.close();
        if (st != null && !st.isClosed())
            st.close();
        if (conn != null && !conn.isClosed())
            conn.close();
        // mark the "transaction" on the graph as complete
        graph.getModel().endUpdate();
    }
}

From source file:org.alfresco.rm.rest.api.impl.RMNodesImpl.java

@Override
public Node getFolderOrDocument(final NodeRef nodeRef, NodeRef parentNodeRef, QName nodeTypeQName,
        List<String> includeParam, Map<String, UserInfo> mapUserInfo) {
    Node originalNode = super.getFolderOrDocument(nodeRef, parentNodeRef, nodeTypeQName, includeParam,
            mapUserInfo);/*from   w ww. java2s .  co m*/

    if (nodeTypeQName == null) {
        nodeTypeQName = nodeService.getType(nodeRef);
    }

    RMNodeType type = getType(nodeTypeQName, nodeRef);
    FileplanComponentNode node = null;
    if (mapUserInfo == null) {
        mapUserInfo = new HashMap<>(2);
    }

    if (type == null) {
        if (filePlanService.isFilePlanComponent(nodeRef)) {
            node = new FileplanComponentNode(originalNode);
        } else {
            throw new InvalidParameterException("The provided node is not a fileplan component");
        }
    } else {
        switch (type) {
        case CATEGORY:
            RecordCategoryNode categoryNode = new RecordCategoryNode(originalNode);
            if (includeParam.contains(PARAM_INCLUDE_HAS_RETENTION_SCHEDULE)) {
                DispositionSchedule ds = dispositionService.getDispositionSchedule(nodeRef);
                categoryNode.setHasRetentionSchedule(ds != null ? true : false);
            }
            node = categoryNode;
            break;
        case RECORD_FOLDER:
            RecordFolderNode rfNode = new RecordFolderNode(originalNode);
            if (includeParam.contains(PARAM_INCLUDE_IS_CLOSED)) {
                rfNode.setIsClosed(
                        (Boolean) nodeService.getProperty(nodeRef, RecordsManagementModel.PROP_IS_CLOSED));
            }
            node = rfNode;
            break;
        case FILE:
            RecordNode rNode = new RecordNode(originalNode);
            if (includeParam.contains(PARAM_INCLUDE_IS_COMPLETED)) {
                rNode.setIsCompleted(
                        nodeService.hasAspect(nodeRef, RecordsManagementModel.ASPECT_DECLARED_RECORD));
            }
            node = rNode;
            break;
        }
    }

    if (includeParam.contains(PARAM_INCLUDE_ALLOWABLEOPERATIONS)) {
        // If the user does not have any of the mapped permissions then "allowableOperations" is not returned (rather than an empty array)
        List<String> allowableOperations = getAllowableOperations(nodeRef, type);
        node.setAllowableOperations((allowableOperations.size() > 0) ? allowableOperations : null);
    }

    return node;
}

From source file:eu.bittrade.libs.steemj.protocol.operations.SetResetAccountOperation.java

/**
 * Set the new reset account for the {@link #getAccount() account}.
 * /*  w  w  w  .  j  av  a  2 s  . co m*/
 * @param resetAccount
 *            The new reset account which has been set with this operation.
 * @throws InvalidParameterException
 *             If no reset account has been provided or if the
 *             <code>resetAccount</code> is set to the same value than the
 *             {@link #getCurrentResetAccount()}.
 */
public void setResetAccount(AccountName resetAccount) {
    if (resetAccount == null) {
        throw new InvalidParameterException("The reset account can't be null.");
    } else if (resetAccount.equals(this.getCurrentResetAccount())) {
        throw new InvalidParameterException(
                "The new reset account can't be the same as the current reset account.");
    }

    this.resetAccount = resetAccount;
}

From source file:org.flite.cach3.aop.InvalidateSingleCacheAdvice.java

static AnnotationInfo getAnnotationInfo(final InvalidateSingleCache annotation,
        final String targetMethodName) {
    final AnnotationInfo result = new AnnotationInfo();

    if (annotation == null) {
        throw new InvalidParameterException(
                String.format("No annotation of type [%s] found.", InvalidateSingleCache.class.getName()));
    }//from w  w w . j a v  a 2s.  c o  m

    final String namespace = annotation.namespace();
    if (AnnotationConstants.DEFAULT_STRING.equals(namespace) || namespace == null || namespace.length() < 1) {
        throw new InvalidParameterException(
                String.format("Namespace for annotation [%s] must be defined on [%s]",
                        InvalidateSingleCache.class.getName(), targetMethodName));
    }
    result.add(new AType.Namespace(namespace));

    final String keyPrefix = annotation.keyPrefix();
    if (!AnnotationConstants.DEFAULT_STRING.equals(keyPrefix)) {
        if (StringUtils.isBlank(keyPrefix)) {
            throw new InvalidParameterException(String.format(
                    "KeyPrefix for annotation [%s] must not be defined as an empty string on [%s]",
                    InvalidateSingleCache.class.getName(), targetMethodName));
        }
        result.add(new AType.KeyPrefix(keyPrefix));
    }

    final Integer keyIndex = annotation.keyIndex();
    if (keyIndex != AnnotationConstants.DEFAULT_KEY_INDEX && keyIndex < -1) {
        throw new InvalidParameterException(
                String.format("KeyIndex for annotation [%s] must be -1 or greater on [%s]",
                        InvalidateSingleCache.class.getName(), targetMethodName));
    }
    final boolean keyIndexDefined = keyIndex >= -1;

    final String keyTemplate = annotation.keyTemplate();
    if (StringUtils.isBlank(keyTemplate)) {
        throw new InvalidParameterException(
                String.format("KeyTemplate for annotation [%s] must not be defined as an empty string on [%s]",
                        InvalidateSingleCache.class.getName(), targetMethodName));
    }
    final boolean keyTemplateDefined = !AnnotationConstants.DEFAULT_STRING.equals(keyTemplate);

    if (keyIndexDefined == keyTemplateDefined) {
        throw new InvalidParameterException(String.format(
                "Exactly one of [keyIndex,keyTemplate] must be defined for annotation [%s] on [%s]",
                InvalidateSingleCache.class.getName(), targetMethodName));
    }

    if (keyIndexDefined) {
        result.add(new AType.KeyIndex(keyIndex));
    }

    if (keyTemplateDefined) {
        result.add(new AType.KeyTemplate(keyTemplate));
    }

    return result;
}

From source file:fr.paris.lutece.plugins.sponsoredlinks.service.search.SponsoredLinksIndexer.java

/**
 * {@inheritDoc}/* w  ww .  ja va 2  s. co m*/
 */
public List<Document> getDocuments(String strId)
        throws IOException, InterruptedException, SiteMessageException {
    ArrayList<org.apache.lucene.document.Document> listDocuments = new ArrayList<Document>();
    Plugin plugin = PluginService.getPlugin(SponsoredLinksPlugin.PLUGIN_NAME);

    Matcher matcher = _pattern.matcher(strId);

    if (!matcher.matches()) {
        AppLogService
                .error(new InvalidParameterException(strId + "is not a valid id for sponsoredlinks document"));

        return listDocuments;
    }

    int nSetId = Integer.valueOf(matcher.group(1));
    int nLinkOrder = Integer.valueOf(matcher.group(2));

    SponsoredLinkSet set = SponsoredLinkSetHome.findByPrimaryKey(nSetId, plugin);

    if (set == null) {
        AppLogService.error(new InvalidParameterException("Can't find set with id :" + nLinkOrder));

        return listDocuments;
    }

    SponsoredLink link = null;

    for (SponsoredLink currentLink : set.getSponsoredLinkList()) {
        if (currentLink.getOrder() == nLinkOrder) {
            link = currentLink;

            break;
        }
    }

    if (link == null) {
        AppLogService.error(new InvalidParameterException("Can't find link at order :" + nLinkOrder));

        return listDocuments;
    }

    SponsoredLinkGroup group = SponsoredLinkGroupHome.findByPrimaryKey(set.getGroupId(), plugin);
    SponsoredLinkTemplate template = SponsoredLinkTemplateHome.findByPrimaryKey(nLinkOrder, plugin);

    org.apache.lucene.document.Document docGroup = getDocument(group, link, set, template);
    listDocuments.add(docGroup);

    return listDocuments;
}

From source file:org.flite.cach3.aop.InvalidateMultiCacheAdvice.java

static AnnotationInfo getAnnotationInfo(final InvalidateMultiCache annotation,
        final String targetMethodName) {
    final AnnotationInfo result = new AnnotationInfo();

    if (annotation == null) {
        throw new InvalidParameterException(
                String.format("No annotation of type [%s] found.", InvalidateMultiCache.class.getName()));
    }/*from www.  j av a 2s . c  o m*/

    final String namespace = annotation.namespace();
    if (AnnotationConstants.DEFAULT_STRING.equals(namespace) || namespace == null || namespace.length() < 1) {
        throw new InvalidParameterException(
                String.format("Namespace for annotation [%s] must be defined on [%s]",
                        InvalidateMultiCache.class.getName(), targetMethodName));
    }
    result.add(new AType.Namespace(namespace));

    final String keyPrefix = annotation.keyPrefix();
    if (!AnnotationConstants.DEFAULT_STRING.equals(keyPrefix)) {
        if (StringUtils.isBlank(keyPrefix)) {
            throw new InvalidParameterException(String.format(
                    "KeyPrefix for annotation [%s] must not be defined as an empty string on [%s]",
                    InvalidateMultiCache.class.getName(), targetMethodName));
        }
        result.add(new AType.KeyPrefix(keyPrefix));
    }

    final Integer keyIndex = annotation.keyIndex();
    if (keyIndex < -1) {
        throw new InvalidParameterException(
                String.format("KeyIndex for annotation [%s] must be -1 or greater on [%s]",
                        InvalidateMultiCache.class.getName(), targetMethodName));
    }
    result.add(new AType.KeyIndex(keyIndex));

    final String keyTemplate = annotation.keyTemplate();
    if (!AnnotationConstants.DEFAULT_STRING.equals(keyTemplate)) {
        if (StringUtils.isBlank(keyTemplate)) {
            throw new InvalidParameterException(String.format(
                    "KeyTemplate for annotation [%s] must not be defined as an empty string on [%s]",
                    InvalidateMultiCache.class.getName(), targetMethodName));
        }
        result.add(new AType.KeyTemplate(keyTemplate));
    }

    return result;
}

From source file:eu.bittrade.libs.steemj.protocol.operations.TransferToVestingOperation.java

@Override
public void validate(ValidationType validationType) {
    if (!ValidationType.SKIP_VALIDATION.equals(validationType)
            && !ValidationType.SKIP_ASSET_VALIDATION.equals(validationType)
            && (!amount.getSymbol().equals(SteemJConfig.getInstance().getTokenSymbol()))) {
        throw new InvalidParameterException("The amount must be of type STEEM.");
    }/*  ww w .  ja  va 2  s  .  c o m*/
}

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Extract sample data as defined in an uploaded RAML file
 * <p>//from   ww  w .j  a  v  a 2  s .co  m
 * @param uploadedInputStream the file content associated with the RAML file upload
 * @param fileDetail the file details associated with the RAML file upload
 * @return HTTP response containing sample data extracted from the uploaded RAML file, in JSON format
 */
@POST
@Path("sampleData")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response getSampleData(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail) {

    log.info("POST raml/sampleData");

    Response response = null;
    File uploadedFile = null;
    File ramlFile = null;
    FileInputStream ramlFileStream = null;

    try {

        if (fileDetail == null || fileDetail.getFileName() == null || fileDetail.getName() == null) {
            throw new InvalidParameterException("file");
        }

        uploadedFile = FileUtil.getUploadedFile(uploadedInputStream, fileDetail);

        if (uploadedFile.isDirectory()) { // find RAML file in directory

            // First, look for a raml file that has the same base name as the uploaded file
            String targetName = Files.getNameWithoutExtension(fileDetail.getFileName()) + ".raml";

            ramlFile = FileUtil.selectRamlFile(uploadedFile, targetName);

        } else {

            ramlFile = uploadedFile;

        }

        List<ValidationResult> results = null;

        try {

            results = RamlUtil.validateRaml(ramlFile);

        } catch (IOException e) {

            String msg = String.format("RAML validation failed catastrophically for %s", ramlFile.getName());
            log.error(msg, e.getCause());
            throw new Exception(msg, e.getCause());
        }

        // If the RAML file is valid, get to work...
        if (ValidationResult.areValid(results)) {

            try {

                ramlFileStream = new FileInputStream(ramlFile.getAbsolutePath());

            } catch (FileNotFoundException e) {

                String msg = String.format("Failed to open input stream from %s", ramlFile.getAbsolutePath());

                throw new Exception(msg, e.getCause());

            }

            FileResourceLoader resourceLoader = new FileResourceLoader(ramlFile.getParentFile());
            RamlDocumentBuilder rdb = new RamlDocumentBuilder(resourceLoader);
            Raml raml = rdb.build(ramlFileStream, ramlFile.getAbsolutePath());

            ramlFileStream.close();
            ramlFileStream = null;

            //String schemaJson = RamlUtil.getSchemaJson(raml, ramlFile.getParentFile());
            String sampleData = RamlUtil.getSampleJson(raml, ramlFile.getParentFile());

            response = Response.status(Status.OK).entity(sampleData).build();

        } else { // RAML file failed validation

            response = Response.status(Status.BAD_REQUEST).entity(RamlUtil.validationMessages(results)).build();

        }

    } catch (Exception ex) {

        ex.printStackTrace();

        String msg = ex.getMessage();

        log.error(msg, ex);

        if (ex instanceof JsonSyntaxException) {

            response = Response.status(Status.BAD_REQUEST).entity(msg).build();

        } else if (ex instanceof InvalidParameterException) {

            response = Response.status(Status.BAD_REQUEST)
                    .entity(String.format("Invalid form parameter - %s", ex.getMessage())).build();

        } else {

            response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build();

        }

        return response;

    } finally {

        if (null != ramlFileStream) {

            try {

                ramlFileStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        if (null != uploadedFile) {

            if (uploadedFile.isDirectory()) {

                try {

                    System.gc(); // To help release files that snakeyaml abandoned open streams on -- otherwise, some files may not delete

                    // Wait a bit for the system to close abandoned streams
                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    FileUtils.deleteDirectory(uploadedFile);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                uploadedFile.delete();
            }

        }
    }

    return response;
}