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:net.blogracy.controller.MediaController.java

/***
 * A Media Item is removed from an album
 * /*from  w w  w. j a  v a2  s. com*/
 * @param userId
 * @param albumId
 * @param mediaId
 */
public synchronized void deletePhotoFromAlbum(String userId, String albumId, String mediaId) {
    if (mediaId == null)
        throw new InvalidParameterException("mediaId cannot be null");

    if (userId == null)
        throw new InvalidParameterException("userId cannot be null");

    if (albumId == null)
        throw new InvalidParameterException("albumId cannot be null");

    Album album = null;
    for (Album a : this.getAlbums(userId)) {
        if (a.getId().equals(albumId)) {
            album = a;
            break;
        }
    }

    if (album == null)
        throw new InvalidParameterException(
                "AlbumId " + albumId + " does not correspond to a valid album for the user " + userId);
    try {

        List<MediaItem> mediaItems = this.getMediaItems(userId, albumId);

        for (Iterator<MediaItem> iter = mediaItems.iterator(); iter.hasNext();) {
            MediaItem mediaItem = iter.next();
            if (mediaId.equals(mediaItem.getId()) && albumId.equals(mediaItem.getAlbumId()))
                iter.remove();
        }

        album.setMediaItemCount(mediaItems.size());

        final List<ActivityEntry> feed = activities.getFeed(userId);
        final ActivityEntry entry = new ActivityEntryImpl();
        entry.setVerb("remove");
        entry.setPublished(ISO_DATE_FORMAT.format(new Date()));
        entry.setContent(mediaId);

        ActivityObject mediaItemObject = new ActivityObjectImpl();
        mediaItemObject.setObjectType("image");
        mediaItemObject.setContent(mediaId);
        entry.setObject(mediaItemObject);

        ActivityObject mediaAlbumObject = new ActivityObjectImpl();
        mediaAlbumObject.setObjectType("collection");
        mediaAlbumObject.setContent(album.getTitle());
        mediaAlbumObject.setId(album.getId());
        entry.setTarget(mediaAlbumObject);

        feed.add(0, entry);
        String feedUri = activities.seedActivityStream(userId, feed);

        JSONObject recordDb = DistributedHashTable.getSingleton().getRecord(userId);

        if (recordDb == null)
            recordDb = new JSONObject();

        JSONArray albums = recordDb.optJSONArray("albums");

        // update albums
        if (albums != null) {
            for (int i = 0; i < albums.length(); ++i) {
                JSONObject singleAlbumObject = albums.getJSONObject(i);
                Album entry1 = (Album) CONVERTER.convertToObject(singleAlbumObject, Album.class);

                if (entry1.getId().equals(albumId)) {
                    albums.put(i, new JSONObject(CONVERTER.convertToString(album)));
                    break;
                }
            }
        }

        JSONArray list = new JSONArray();
        JSONArray mediaItemsArray = recordDb.optJSONArray("mediaItems");
        if (mediaItemsArray != null) {
            for (int i = 0; i < mediaItemsArray.length(); ++i) {
                JSONObject singleMediaItemObject = mediaItemsArray.getJSONObject(i);
                MediaItem entry1 = (MediaItem) CONVERTER.convertToObject(singleMediaItemObject,
                        MediaItem.class);
                if (!mediaId.equals(entry1.getId()) || !albumId.equals(entry1.getAlbumId()))
                    list.put(singleMediaItemObject);
            }
        }

        dht.store(userId, feedUri, entry.getPublished(), albums, list);

    } catch (Exception e) {
        e.printStackTrace();

    }
}

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

@Override
public void validate(ValidationType validationType) {
    if (!ValidationType.SKIP_VALIDATION.equals(validationType)) {
        if (!ValidationType.SKIP_ASSET_VALIDATION.equals(validationType)) {
            if (!maxAcceptedPayout.getSymbol().equals(SteemJConfig.getInstance().getDollarSymbol())) {
                throw new InvalidParameterException("The maximal accepted payout must be in SBD.");
            } else if (maxAcceptedPayout.getAmount() < 0) {
                throw new InvalidParameterException("Cannot accept less than 0 payout.");
            }/*from   w  w w .java  2s . c  o  m*/
        }

        if (percentSteemDollars > 10000) {
            throw new InvalidParameterException(
                    "The percent of steem dollars can't be higher than 10000 which is equivalent to 100%.");
        }

        if (extensions != null) {
            for (CommentOptionsExtension commentOptionsExtension : extensions) {
                commentOptionsExtension.validate(validationType);
            }
        }
    }
}

From source file:com.rightscale.provider.Dashboard.java

static protected String _getType(Uri uri) {
    List<String> path = uri.getPathSegments();

    String model;/*from   ww w  . ja  v a  2 s.  c om*/
    String mimePrefix, mimeType;

    if (path.size() % 2 == 1) {
        // Odd-sized paths (/deployments, /deployments/1/servers, ...)
        // represent a collection of resources.
        model = path.get(path.size() - 1);
        mimePrefix = "vnd.android.cursor.dir/";
    } else {
        // Even-sized paths (/deployments/1, /server_templates/1/executables/5)
        // represent an individual item.
        model = path.get(path.size() - 2);
        mimePrefix = "vnd.android.cursor.item/";
    }

    if (model.equals("accounts")) {
        mimeType = AccountsResource.MIME_TYPE;
    } else if (model.equals("deployments")) {
        mimeType = DeploymentsResource.MIME_TYPE;
    } else if (model.equals("servers")) {
        mimeType = ServersResource.MIME_TYPE;
    } else if (model.equals("server_settings")) {
        mimeType = ServerSettingsResource.MIME_TYPE;
    } else {
        throw new InvalidParameterException("Unknown URI: " + model);
    }

    return mimePrefix + mimeType;
}

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

/**
 * Produce a WADL file from an uploaded RAML file
 * <p>/*from  w  w  w.ja v  a2s  .c o  m*/
 * @param uploadedInputStream the file content associated with the RAML file upload
 * @param fileDetail the file details associated with the RAML file upload
 * @param baseUri the baseUri to use in the returned WADL file.  Optionally provided, this will override that which is defined in the uploaded RAML.
 * @return HTTP response containing the WADL transformation from the uploaded RAML file
 */
@POST
@Path("wadl")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
public Response genWadl(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri) {

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

    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");
        }

        if (!baseUri.isEmpty()) { // validate URI syntax
            try {

                new URI(baseUri);

            } catch (URISyntaxException uriEx) {

                throw new InvalidParameterException(String.format("baseUri - %s", uriEx.getMessage()));

            }
        }

        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());
            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;

            if (!baseUri.isEmpty()) {
                raml.setBaseUri(baseUri);
            }

            WADL wadl = new WADL(raml, ramlFile.getParentFile());
            Document doc = null;

            doc = wadl.getDocument();

            StringWriter stringWriter = new StringWriter();

            WADL.prettyPrint(doc, stringWriter);

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

        } else { // RAML file failed validation

            StringBuilder sb = new StringBuilder();

            for (ValidationResult result : results) {

                sb.append(result.getLevel());

                if (result.getLine() > 0) {

                    sb.append(String.format(" (line %d)", result.getLine()));

                }

                sb.append(String.format(" - %s\n", result.getMessage()));
            }

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

        }

    } catch (Exception ex) {

        ex.printStackTrace();

        String msg = ex.getMessage();

        log.error(msg, ex.getCause());

        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;
}

From source file:org.jessma.util.http.FileUploader.java

private Result parseFileItems(List<FileItem> items, FileNameGenerator fnGenerator, String absolutePath,
        String encoding, List<FileItemInfo> fiis) {
    for (FileItem item : items) {
        if (item.isFormField())
            parseFormField(item, encoding);
        else {/*from  w  w  w.j a  v a 2s .  com*/
            if (GeneralHelper.isStrEmpty(item.getName()))
                continue;

            Result result = parseFileField(item, absolutePath, fnGenerator, fiis);
            if (result != Result.SUCCESS) {
                reset();

                cause = new InvalidParameterException(String.format("file '%s' not accepted", item.getName()));
                return result;
            }
        }
    }

    return Result.SUCCESS;
}

From source file:org.zaproxy.zap.extension.customFire.ExtensionCustomFire.java

@Override
public int startScan(String name, Target target, User user, Object[] contextSpecificObjects) {

    if (name == null) {
        name = target.getDisplayName();// w w  w. j  a  va 2  s.c o m

    }

    switch (Control.getSingleton().getMode()) {
    case safe:

        throw new InvalidParameterException("Scans are not allowed in Safe mode");
    case protect:

        List<StructuralNode> nodes = target.getStartNodes();

        if (nodes != null) {
            for (StructuralNode node : nodes) {
                if (node instanceof StructuralSiteNode) {
                    SiteNode siteNode = ((StructuralSiteNode) node).getSiteNode();
                    if (!siteNode.isIncludedInScope()) {
                        throw new InvalidParameterException(
                                "Scans are not allowed on nodes not in scope Protected mode "
                                        + target.getStartNode().getHierarchicNodeName());
                    }
                }
            }
        }
        // No problem
        break;
    case standard:
        // No problem

        break;
    case attack:
        // No problem

        break;
    }

    int id = this.cscanController.startScan(name, target, user, contextSpecificObjects);

    if (View.isInitialised()) {

        CustomScan scanner = this.cscanController.getScan(id);

        scanner.addScannerListener(getCustomScanPanel()); //* So the UI gets updated

        this.getCustomScanPanel().scannerStarted(scanner);

        this.getCustomScanPanel().switchView(scanner);

        this.getCustomScanPanel().setTabFocus();

    }

    return id;
}

From source file:com.yunguchang.data.ApplicationRepository.java

@TransactionAttribute(REQUIRES_NEW)
public TBusApplyinfoEntity devolveApply(String applyId, String applyNo, String isSend, String status,
        String reason, Boolean bySync, PrincipalExt principalExt) {
    if (applyId == null && applyNo == null) {
        throw new InvalidParameterException("Approve info can not be null!");
    }// www. j a v a 2s  .  c  o  m
    TBusApplyinfoEntity applyinfoEntity;
    if (applyId != null) {
        applyinfoEntity = em.find(TBusApplyinfoEntity.class, applyId);
    } else {
        applyinfoEntity = getApplicationByNo(applyNo, principalExt);
    }
    if (applyinfoEntity == null) {
        throw logger.entityNotFound(TBusApplyinfoEntity.class, applyId);
    }
    applyinfoEntity.setIssend("1".equals(isSend) ? "1" : "0"); // 1  0 ?
    //        applyinfoEntity.setStatus("3");      // status = "3"

    applyinfoEntity.setReasonms(reason);

    if (bySync != null && bySync) {
        applyinfoEntity.setUpdateBySync(true);
    } else {
        applyinfoEntity.setUpdateBySync(false);
    }

    return applyinfoEntity;
}

From source file:org.easyxml.xml.Element.java

/**
 * /*  ww w. j a  v a2s.  c  o m*/
 * Method to evaluate the path by split the path to one path to locate the
 * element, and optional another part to locate its attribute.
 * 
 * @param path
 *            - The whole path of a Element or a Attribute.
 * 
 *            For example, "SOAP:Envelope>SOAP:Body>Child" denotes <Child>
 *            element/elements under <SOAP:Body>.
 * 
 *            "SOAP:Envelope>SOAP:Body>Child<Attr" denotes the "Attr"
 *            attribute of the above <Child> element/elements.
 * 
 * @return At most two segments, first for the element, optional second for
 *         the attribute.
 * 
 *         When the path denotes some elements, then only one segment would
 *         be returned.
 * 
 *         When the path denotes an attribute of some elements, then two
 *         segments would be returned.
 */

protected String[] parsePath(String path) {

    if (StringUtils.isBlank(path))

        throw new InvalidParameterException("Blank path cannot be used to locate elements!");

    String[] segments = path.split(Attribute.DefaultAttributePathSign);

    int segmentLength = segments.length;

    if (segmentLength > 2)

        throw new InvalidParameterException(String.format(
                "The path \'%s\' shall have at most one \'%s\' to denote the attribute of a kind of element."

                , path, Attribute.DefaultAttributePathSign));

    return segments;

}

From source file:eu.europa.ec.fisheries.uvms.reporting.service.util.ReportDeserializer.java

private void handleAll(JsonNode common, List<FilterDTO> filterDTOList, Long reportId,
        Selector positionSelector) {
    JsonNode startDateNode = common.get("startDate");
    JsonNode endDateNode = common.get("endDate");

    if (startDateNode == null) {
        throw new InvalidParameterException("StartDate is mandatory when selecting ALL");
    }// w w  w.  j av a 2  s.c o m
    if (endDateNode == null) {
        throw new InvalidParameterException("EndDate is mandatory when selecting ALL");
    }

    String startDate = startDateNode.asText();
    String endDate = endDateNode.asText();

    filterDTOList.add(CommonFilterDTO.CommonFilterDTOBuilder()
            .id(common.get(FilterDTO.ID) != null ? common.get(FilterDTO.ID).longValue() : null)
            .reportId(reportId).endDate(UI_FORMATTER.parseDateTime(endDate).toDate())
            .startDate(UI_FORMATTER.parseDateTime(startDate).toDate())
            .positionSelector(
                    PositionSelectorDTO.PositionSelectorDTOBuilder().selector(positionSelector).build())
            .build());

}

From source file:com.cloud.network.NetworkModelImpl.java

public boolean canIpUsedForNonConserveService(PublicIp ip, Service service) {
    // If it's non-conserve mode, then the new ip should not be used by any other services
    List<PublicIpAddress> ipList = new ArrayList<PublicIpAddress>();
    ipList.add(ip);/*from   w ww.  jav a  2  s.com*/
    Map<PublicIpAddress, Set<Service>> ipToServices = getIpToServices(ipList, false, false);
    Set<Service> services = ipToServices.get(ip);
    // Not used currently, safe
    if (services == null || services.isEmpty()) {
        return true;
    }
    // Since it's non-conserve mode, only one service should used for IP
    if (services.size() != 1) {
        throw new InvalidParameterException("There are multiple services used ip " + ip.getAddress() + ".");
    }
    if (service != null && !((Service) services.toArray()[0] == service || service.equals(Service.Firewall))) {
        throw new InvalidParameterException("The IP " + ip.getAddress() + " is already used as "
                + ((Service) services.toArray()[0]).getName() + " rather than " + service.getName());
    }
    return true;
}