List of usage examples for java.security InvalidParameterException InvalidParameterException
public InvalidParameterException(String msg)
From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Produce an EDM from an uploaded RAML file * <p>//from w w w. j a v a 2s . 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 an HTTP response containing the EDM transformation for the uploaded RAML file */ @POST @Path("edm") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) public Response genEdm(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream, @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail) { log.info("POST raml/edm"); 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()); 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; EDM edm = new EDM(raml); Document doc = null; try { doc = edm.getDocument(); StringWriter stringWriter = new StringWriter(); EDM.prettyPrint(doc, stringWriter); response = Response.status(Status.OK).entity(stringWriter.toString()).build(); } catch (Exception e) { String msg = String.format("Failed to build EDM document - %s", e.getMessage()); throw new Exception(msg, e.getCause()); } } 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; }
From source file:org.openanzo.jdbc.opgen.RdbStatement.java
/** * Get the return type for this statement * //from www . ja v a 2 s.c o m * @return the return type for this statement */ public String getReturnType() { if (results == Result.NONE) { return "void"; } else if (results == Result.ITERATOR) { return "org.openanzo.jdbc.utils.ClosableIterator"; } else if (results == Result.ROW) { return capitalizedName() + "Result"; } else if (results == Result.VALUE) { return getValueReturnType(false); } else if (results == Result.COUNTER) { return "int"; } else if (results == Result.IDENTITY) { return "Long"; } throw new InvalidParameterException("Not a valid enumeration value: " + results.getValue()); }
From source file:org.pentaho.big.data.kettle.plugins.hdfs.trans.HadoopFileInputMeta.java
protected String encryptDecryptPassword(String source, EncryptDirection direction) { Validate.notNull(direction, "'direction' must not be null"); try {//from w w w.j a v a2s . c o m URI uri = new URI(source); String userInfo = uri.getUserInfo(); if (userInfo != null) { String[] userInfoArray = userInfo.split(":", 2); if (userInfoArray.length < 2) { return source; //no password present } String password = userInfoArray[1]; String processedPassword = password; switch (direction) { case ENCRYPT: processedPassword = Encr.encryptPasswordIfNotUsingVariables(password); break; case DECRYPT: processedPassword = Encr.decryptPasswordOptionallyEncrypted(password); break; default: throw new InvalidParameterException("direction must be 'ENCODE' or 'DECODE'"); } URI encryptedUri = new URI(uri.getScheme(), userInfoArray[0] + ":" + processedPassword, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); return encryptedUri.toString(); } } catch (URISyntaxException e) { return source; // if this is non-parseable as a uri just return the source without changing it. } return source; // Just for the compiler should NEVER hit this code }
From source file:eu.bittrade.libs.steemj.protocol.operations.WitnessUpdateOperation.java
@Override public void validate(ValidationType validationType) { if ((!ValidationType.SKIP_ASSET_VALIDATION.equals(validationType) && !ValidationType.SKIP_VALIDATION.equals(validationType)) && (this.getFee().getAmount() < 0 || !SteemJConfig.getInstance().getTokenSymbol().equals(this.getFee().getSymbol()))) { throw new InvalidParameterException("The fee needs to be a positive amount of STEEM."); }/*w w w . j a v a 2s . c o m*/ }
From source file:org.kuali.ole.module.purap.document.service.impl.PurApWorkflowIntegrationServiceImpl.java
/** * DON'T CALL THIS IF THE DOC HAS NOT BEEN SAVED * * @see org.kuali.ole.module.purap.document.service.PurApWorkflowIntegrationService#willDocumentStopAtGivenFutureRouteNode(org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument, * org.kuali.ole.module.purap.PurapWorkflowConstants.NodeDetails) *//*from w ww. j a va2 s . c om*/ @Override public boolean willDocumentStopAtGivenFutureRouteNode(PurchasingAccountsPayableDocument document, String givenNodeName) { if (givenNodeName == null) { throw new InvalidParameterException("Given Node Detail object was null"); } try { String activeNode = null; String[] nodeNames = document.getDocumentHeader().getWorkflowDocument().getCurrentNodeNames() .toArray(new String[0]); if (nodeNames.length == 1) { activeNode = nodeNames[0]; } if (isGivenNodeAfterCurrentNode(document, activeNode, givenNodeName)) { if (document.getDocumentHeader().getWorkflowDocument().isInitiated()) { // document is only initiated so we need to pass xml for workflow to simulate route properly RoutingReportCriteria.Builder builder = RoutingReportCriteria.Builder.createByDocumentTypeName( document.getDocumentHeader().getWorkflowDocument().getDocumentTypeName()); builder.setXmlContent(document.getXmlForRouteReport()); builder.setRoutingPrincipalId(GlobalVariables.getUserSession().getPerson().getPrincipalId()); builder.setTargetNodeName(givenNodeName); RoutingReportCriteria reportCriteria = builder.build(); boolean value = SpringContext.getBean(WorkflowDocumentActionsService.class) .documentWillHaveAtLeastOneActionRequest(reportCriteria, Arrays.asList(KewApiConstants.ACTION_REQUEST_APPROVE_REQ, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ), false); return value; } else { /* Document has had at least one workflow action taken so we need to pass the doc id so the simulation will use * the existing actions taken and action requests in determining if rules will fire or not. We also need to call * a save routing data so that the xml Workflow uses represents what is currently on the document */ RoutingReportCriteria.Builder builder = RoutingReportCriteria.Builder .createByDocumentId(document.getDocumentNumber()); builder.setXmlContent(document.getXmlForRouteReport()); builder.setTargetNodeName(givenNodeName); RoutingReportCriteria reportCriteria = builder.build(); boolean value = SpringContext.getBean(WorkflowDocumentActionsService.class) .documentWillHaveAtLeastOneActionRequest(reportCriteria, Arrays.asList(KewApiConstants.ACTION_REQUEST_APPROVE_REQ, KewApiConstants.ACTION_REQUEST_COMPLETE_REQ), false); return value; } } return false; } catch (Exception e) { String errorMessage = "Error trying to test document id '" + document.getDocumentNumber() + "' for action requests at node name '" + givenNodeName + "'"; LOG.error("isDocumentStoppingAtRouteLevel() " + errorMessage, e); throw new RuntimeException(errorMessage, e); } }
From source file:eu.bittrade.libs.steemj.protocol.operations.CommentOperation.java
/** * Set the content of this comment./*from w w w .j a v a2 s.co m*/ * * @param body * The content of this comment. * @throws InvalidParameterException * If no body has been provided. */ public void setBody(String body) { if (body == null || body.isEmpty()) { throw new InvalidParameterException("The body can't be empty."); } this.body = body; }
From source file:de.knurt.fam.core.persistence.dao.ibatis.UserDao4ibatis.java
/** {@inheritDoc} */ @Override/* w w w. j a v a2 s .c o m*/ public List<User> getUsersWithEMail(String email) throws InvalidParameterException { if (GenericValidator.isEmail(email)) { String where = String.format("mail = \"%s\"", email); return this.getWhere(where); } else { throw new InvalidParameterException(email + " is not an email"); } }
From source file:com.alibaba.jstorm.daemon.nimbus.ServiceHandler.java
/** * Submit one Topology/* w w w.ja v a2 s .com*/ * * @param topologyName String: topology name * @param uploadedJarLocation String: already uploaded jar path * @param jsonConf String: jsonConf serialize all toplogy configuration to * Json * @param topology StormTopology: topology Object */ @SuppressWarnings("unchecked") @Override public void submitTopologyWithOpts(String topologyName, String uploadedJarLocation, String jsonConf, StormTopology topology, SubmitOptions options) throws AlreadyAliveException, InvalidTopologyException, TopologyAssignException, TException { LOG.info("Receive " + topologyName + ", uploadedJarLocation:" + uploadedJarLocation); long start = System.nanoTime(); //check topologyname is valid if (!Common.charValidate(topologyName)) { throw new InvalidTopologyException(topologyName + " is not a valid topology name"); } try { checkTopologyActive(data, topologyName, false); } catch (AlreadyAliveException e) { LOG.info(topologyName + " already exists "); throw e; } catch (Throwable e) { LOG.info("Failed to check whether topology is alive or not", e); throw new TException(e); } String topologyId = null; synchronized (data) { // avoid to the same topologys wered submmitted at the same time Set<String> pendingTopologys = data.getPendingSubmitTopoloygs().keySet(); for (String cachTopologyId : pendingTopologys) { if (cachTopologyId.contains(topologyName + "-")) throw new AlreadyAliveException(topologyName + " were submitted"); } int counter = data.getSubmittedCount().incrementAndGet(); topologyId = Common.topologyNameToId(topologyName, counter); data.getPendingSubmitTopoloygs().put(topologyId, null); } try { Map<Object, Object> serializedConf = (Map<Object, Object>) JStormUtils.from_json(jsonConf); if (serializedConf == null) { LOG.warn("Failed to serialized Configuration"); throw new InvalidTopologyException("Failed to serialize topology configuration"); } serializedConf.put(Config.TOPOLOGY_ID, topologyId); serializedConf.put(Config.TOPOLOGY_NAME, topologyName); Map<Object, Object> stormConf; stormConf = NimbusUtils.normalizeConf(conf, serializedConf, topology); LOG.info("Normalized configuration:" + stormConf); Map<Object, Object> totalStormConf = new HashMap<Object, Object>(conf); totalStormConf.putAll(stormConf); StormTopology normalizedTopology = NimbusUtils.normalizeTopology(stormConf, topology, true); // this validates the structure of the topology Common.validate_basic(normalizedTopology, totalStormConf, topologyId); // don't need generate real topology, so skip Common.system_topology // Common.system_topology(totalStormConf, topology); StormClusterState stormClusterState = data.getStormClusterState(); double metricsSampleRate = ConfigExtension.getMetricSampleRate(stormConf); // create /local-dir/nimbus/topologyId/xxxx files setupStormCode(conf, topologyId, uploadedJarLocation, stormConf, normalizedTopology); // generate TaskInfo for every bolt or spout in ZK // /ZK/tasks/topoologyId/xxx setupZkTaskInfo(conf, topologyId, stormClusterState); // make assignments for a topology LOG.info("Submit for " + topologyName + " with conf " + serializedConf); makeAssignment(topologyName, topologyId, options.get_initial_status()); // when make assignment for a topology,so remove the topologyid form // pendingSubmitTopologys data.getPendingSubmitTopoloygs().remove(topologyId); // push start event after startup StartTopologyEvent startEvent = new StartTopologyEvent(); startEvent.clusterName = this.data.getClusterName(); startEvent.topologyId = topologyId; startEvent.timestamp = System.currentTimeMillis(); startEvent.sampleRate = metricsSampleRate; this.data.getMetricRunnable().pushEvent(startEvent); } catch (FailedAssignTopologyException e) { StringBuilder sb = new StringBuilder(); sb.append("Fail to sumbit topology, Root cause:"); if (e.getMessage() == null) { sb.append("submit timeout"); } else { sb.append(e.getMessage()); } sb.append("\n\n"); sb.append("topologyId:" + topologyId); sb.append(", uploadedJarLocation:" + uploadedJarLocation + "\n"); LOG.error(sb.toString(), e); data.getPendingSubmitTopoloygs().remove(topologyId); throw new TopologyAssignException(sb.toString()); } catch (InvalidParameterException e) { StringBuilder sb = new StringBuilder(); sb.append("Fail to sumbit topology "); sb.append(e.getMessage()); sb.append(", cause:" + e.getCause()); sb.append("\n\n"); sb.append("topologyId:" + topologyId); sb.append(", uploadedJarLocation:" + uploadedJarLocation + "\n"); LOG.error(sb.toString(), e); data.getPendingSubmitTopoloygs().remove(topologyId); throw new InvalidParameterException(sb.toString()); } catch (InvalidTopologyException e) { LOG.error("Topology is invalid. " + e.get_msg()); data.getPendingSubmitTopoloygs().remove(topologyId); throw e; } catch (Throwable e) { StringBuilder sb = new StringBuilder(); sb.append("Fail to sumbit topology "); sb.append(e.getMessage()); sb.append(", cause:" + e.getCause()); sb.append("\n\n"); sb.append("topologyId:" + topologyId); sb.append(", uploadedJarLocation:" + uploadedJarLocation + "\n"); LOG.error(sb.toString(), e); data.getPendingSubmitTopoloygs().remove(topologyId); throw new TopologyAssignException(sb.toString()); } finally { double spend = (System.nanoTime() - start) / TimeUtils.NS_PER_US; SimpleJStormMetric.updateNimbusHistogram("submitTopologyWithOpts", spend); LOG.info("submitTopologyWithOpts {} costs {}ms", topologyName, spend); } }
From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java
private KeyStore openKeyStore(Store store, String defaultType, char[] keyPass, ResolverMap resourceResolver, String baseLocation) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, NoSuchProviderException { String type = store.getType(); if (type == null) type = defaultType;/*from ww w .j a v a 2 s. co m*/ char[] password = keyPass; if (store.getPassword() != null) password = store.getPassword().toCharArray(); if (password == null) throw new InvalidParameterException("Password for key store is not set."); KeyStore ks; if (store.getProvider() != null) ks = KeyStore.getInstance(type, store.getProvider()); else ks = KeyStore.getInstance(type); ks.load(resourceResolver.resolve(ResolverMap.combine(baseLocation, store.getLocation())), password); if (!default_certificate_warned && ks.getCertificate("membrane") != null) { byte[] pkeEnc = ks.getCertificate("membrane").getEncoded(); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(pkeEnc); byte[] mdbytes = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { if (i > 0) sb.append(':'); sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } if (sb.toString().equals(DEFAULT_CERTIFICATE_SHA256)) { log.warn("Using Membrane with the default certificate. This is highly discouraged! " + "Please run the generate-ssl-keys script in the conf directory."); default_certificate_warned = true; } } return ks; }
From source file:eu.bittrade.libs.steemj.protocol.operations.EscrowReleaseOperation.java
@Override public void validate(ValidationType validationType) { if (!ValidationType.SKIP_VALIDATION.equals(validationType)) { if (!ValidationType.SKIP_ASSET_VALIDATION.equals(validationType)) { if (steemAmount.getAmount() < 0) { throw new InvalidParameterException("The steem amount cannot be negative."); } else if (!steemAmount.getSymbol().equals(SteemJConfig.getInstance().getTokenSymbol())) { throw new InvalidParameterException("The steem amount must contain STEEM."); } else if (sbdAmount.getAmount() < 0) { throw new InvalidParameterException("The sbd amount cannot be negative."); } else if (!sbdAmount.getSymbol().equals(SteemJConfig.getInstance().getDollarSymbol())) { throw new InvalidParameterException("The sbd amount must contain SBD."); } else if (sbdAmount.getAmount() + steemAmount.getAmount() < 0) { throw new InvalidParameterException("An escrow must release a non-zero amount."); }//from w ww . j av a 2s . c o m } if (!who.equals(from) && !who.equals(to) && !who.equals(agent)) { throw new InvalidParameterException( "The who account must be either the from account, the to account or the agent account."); } else if (!receiver.equals(from) && receiver.equals(to)) { throw new InvalidParameterException( "The receiver account must be either the from account or the to account."); } } }