List of usage examples for java.security InvalidParameterException InvalidParameterException
public InvalidParameterException(String msg)
From source file:org.kaaproject.kaa.server.appenders.cassandra.appender.CassandraLogEventDao.java
private Insert[] prepareQuery(List<CassandraLogEventDto> logEventDtoList, GenericAvroConverter<GenericRecord> eventConverter, GenericAvroConverter<GenericRecord> headerConverter, GenericAvroConverter<GenericRecord> clientProfileConverter, GenericAvroConverter<GenericRecord> serverProfileConverter, String clientProfileJson, String serverProfileJson, String appToken) throws IOException { String reuseTsValue = null;/*from ww w . ja va 2 s . c o m*/ List<Insert> insertArray = new ArrayList<>(logEventDtoList.size()); // Process client profile data GenericRecord clientProfile = null; ByteBuffer clientProfileBinary = null; if (clientProfileConverter != null) { clientProfile = clientProfileConverter.decodeJson(clientProfileJson); clientProfileBinary = ByteBuffer.wrap(clientProfileConverter.encode(clientProfile)); } // Process server profile data GenericRecord serverProfile = null; ByteBuffer serverProfileBinary = null; if (serverProfileConverter != null) { serverProfile = serverProfileConverter.decodeJson(serverProfileJson); serverProfileBinary = ByteBuffer.wrap(serverProfileConverter.encode(serverProfile)); } for (int i = 0; i < logEventDtoList.size(); i++) { CassandraLogEventDto dto = logEventDtoList.get(i); GenericRecord logRecord = dto.getEvent(); if (logRecord != null) { List<DataMappingElement> mappingElements = findMappings(logRecord); LOG.debug("Found {} mapping element(s)", mappingElements.size()); if (mappingElements.size() > 0) { for (DataMappingElement mappingElement : mappingElements) { String tableName = toFullTableName(appToken, mappingElement.getTableNamePattern()); LOG.debug("Processing mapping for table: {}", tableName); Insert insert = QueryBuilder.insertInto(keyspaceName, tableName); for (ColumnMappingElement element : mappingElement.getColumnMapping()) { switch (element.getType()) { case HEADER_FIELD: insert.value(element.getColumnName(), formatField(element.getColumnType(), element.getValue(), dto.getHeader())); break; case EVENT_FIELD: insert.value(element.getColumnName(), formatField(element.getColumnType(), element.getValue(), dto.getEvent())); break; case CLIENT_FIELD: if (clientProfile != null) { insert.value(element.getColumnName(), formatField(element.getColumnType(), clientProfile.get(element.getValue()))); } else { throw new RuntimeException(ABSENT_CLIENT_PROFILE_ERROR); } break; case SERVER_FIELD: if (serverProfile != null) { insert.value(element.getColumnName(), formatField(element.getColumnType(), serverProfile.get(element.getValue()))); } else { throw new RuntimeException(ABSENT_SERVER_PROFILE_ERROR); } break; case HEADER_JSON: insert.value(element.getColumnName(), headerConverter.encodeToJson(dto.getHeader())); break; case HEADER_BINARY: insert.value(element.getColumnName(), ByteBuffer.wrap(headerConverter.encode(dto.getHeader()))); break; case EVENT_JSON: if (StringUtils.isEmpty(element.getValue())) { insert.value(element.getColumnName(), eventConverter.encodeToJson(dto.getEvent())); } else { GenericRecord gr = dto.getEvent(); GenericRecord currentRecord = (GenericRecord) gr.get(element.getValue()); if (currentRecord != null) { insert.value(element.getColumnName(), eventConverter.encodeToJson(currentRecord)); } else { insert.value(element.getColumnName(), eventConverter.encodeToJson(dto.getEvent())); } } break; case EVENT_BINARY: insert.value(element.getColumnName(), ByteBuffer.wrap(eventConverter.encode(dto.getEvent()))); break; case CLIENT_JSON: if (clientProfileJson != null) { insert.value(element.getColumnName(), clientProfileJson); } else { throw new RuntimeException(ABSENT_CLIENT_PROFILE_ERROR); } break; case CLIENT_BINARY: if (clientProfileBinary != null) { insert.value(element.getColumnName(), clientProfileBinary); } else { throw new RuntimeException(ABSENT_CLIENT_PROFILE_ERROR); } break; case SERVER_JSON: if (serverProfileJson != null) { insert.value(element.getColumnName(), serverProfileJson); } else { throw new RuntimeException(ABSENT_SERVER_PROFILE_ERROR); } case SERVER_BINARY: if (serverProfileBinary != null) { insert.value(element.getColumnName(), clientProfileBinary); } else { throw new RuntimeException(ABSENT_SERVER_PROFILE_ERROR); } break; case UUID: insert.value(element.getColumnName(), UUID.randomUUID()); break; case TS: reuseTsValue = formatTs(reuseTsValue, element); insert.value(element.getColumnName(), reuseTsValue); break; } } // Here we get ttl parameter from config and add it to insert query insert.using(QueryBuilder.ttl(configuration.getDataTTL())); insertArray.add(insert); } } else { LOG.warn("Not found mapping configuration. LogRecord: [{}]", logRecord); } } else { throw new InvalidParameterException("Data field inside log event is empty."); } } return insertArray.toArray(new Insert[insertArray.size()]); }
From source file:com.cloud.hypervisor.vmware.mo.HypervisorHostHelper.java
/** * @param ethPortProfileName// w w w. ja v a 2 s .co m * @param namePrefix * @param hostMo * @param vlanId * @param networkRateMbps * @param networkRateMulticastMbps * @param timeOutMs * @param vSwitchType * @param numPorts * @param details * @return * @throws Exception */ public static Pair<ManagedObjectReference, String> prepareNetwork(String physicalNetwork, String namePrefix, HostMO hostMo, String vlanId, String secondaryvlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, VirtualSwitchType vSwitchType, int numPorts, String gateway, boolean configureVServiceInNexus, BroadcastDomainType broadcastDomainType, Map<String, String> vsmCredentials, Map<NetworkOffering.Detail, String> details) throws Exception { ManagedObjectReference morNetwork = null; VmwareContext context = hostMo.getContext(); ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter(); DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); DistributedVirtualSwitchMO dvSwitchMo = null; ManagedObjectReference morEthernetPortProfile = null; String ethPortProfileName = null; ManagedObjectReference morDvSwitch = null; String dvSwitchName = null; boolean bWaitPortGroupReady = false; boolean createGCTag = false; String vcApiVersion; String minVcApiVersionSupportingAutoExpand; boolean autoExpandSupported; String networkName; Integer vid = null; Integer spvlanid = null; // secondary pvlan id /** This is the list of BroadcastDomainTypes we can actually * prepare networks for in this function. */ BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan, BroadcastDomainType.Vsp }; if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) { throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType + " it not supported on a VMWare hypervisor at this time."); } if (broadcastDomainType == BroadcastDomainType.Lswitch) { if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) { throw new InvalidParameterException( "Nexus Distributed Virtualswitch is not supported with BroadcastDomainType " + broadcastDomainType); } /** * Nicira NVP requires all vms to be connected to a single port-group. * A unique vlan needs to be set per port. This vlan is specific to * this implementation and has no reference to other vlans in CS */ networkName = "br-int"; // FIXME Should be set via a configuration item in CS // No doubt about this, depending on vid=null to avoid lots of code below vid = null; } else { if (vlanId != null) { vlanId = vlanId.replace("vlan://", ""); } networkName = composeCloudNetworkName(namePrefix, vlanId, secondaryvlanId, networkRateMbps, physicalNetwork); if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId) && !StringUtils.containsAny(vlanId, ",-")) { createGCTag = true; vid = Integer.parseInt(vlanId); } if (vlanId != null && StringUtils.containsAny(vlanId, ",-")) { createGCTag = true; } if (secondaryvlanId != null) { spvlanid = Integer.parseInt(secondaryvlanId); } } if (vSwitchType == VirtualSwitchType.VMwareDistributedVirtualSwitch) { DVSTrafficShapingPolicy shapingPolicy; DVSSecurityPolicy secPolicy; vcApiVersion = getVcenterApiVersion(context); minVcApiVersionSupportingAutoExpand = "5.0"; autoExpandSupported = isFeatureSupportedInVcenterApiVersion(vcApiVersion, minVcApiVersionSupportingAutoExpand); dvSwitchName = physicalNetwork; // TODO(sateesh): Remove this after ensuring proper default value for vSwitchName throughout traffic types // and switch types. if (dvSwitchName == null) { s_logger.warn("Detected null dvSwitch. Defaulting to dvSwitch0"); dvSwitchName = "dvSwitch0"; } morDvSwitch = dataCenterMo.getDvSwitchMor(dvSwitchName); if (morDvSwitch == null) { String msg = "Unable to find distributed vSwitch " + dvSwitchName; s_logger.error(msg); throw new Exception(msg); } else { s_logger.debug("Found distributed vSwitch " + dvSwitchName); } if (broadcastDomainType == BroadcastDomainType.Lswitch) { if (!dataCenterMo.hasDvPortGroup(networkName)) { throw new InvalidParameterException("NVP integration port-group " + networkName + " does not exist on the DVS " + dvSwitchName); } bWaitPortGroupReady = false; } else { dvSwitchMo = new DistributedVirtualSwitchMO(context, morDvSwitch); shapingPolicy = getDVSShapingPolicy(networkRateMbps); secPolicy = createDVSSecurityPolicy(details); // First, if both vlan id and pvlan id are provided, we need to // reconfigure the DVSwitch to have a tuple <vlan id, pvlan id> of // type isolated. if (vid != null && spvlanid != null) { setupPVlanPair(dvSwitchMo, morDvSwitch, vid, spvlanid); } VMwareDVSPortgroupPolicy portGroupPolicy = null; if (broadcastDomainType == BroadcastDomainType.Vsp) { //If the broadcastDomainType is Vsp, then set the VMwareDVSPortgroupPolicy portGroupPolicy = new VMwareDVSPortgroupPolicy(); portGroupPolicy.setVlanOverrideAllowed(true); portGroupPolicy.setBlockOverrideAllowed(true); portGroupPolicy.setPortConfigResetAtDisconnect(true); } // Next, create the port group. For this, we need to create a VLAN spec. createPortGroup(physicalNetwork, networkName, vlanId, vid, spvlanid, dataCenterMo, shapingPolicy, secPolicy, portGroupPolicy, dvSwitchMo, numPorts, autoExpandSupported); bWaitPortGroupReady = true; } } else if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) { ethPortProfileName = physicalNetwork; // TODO(sateesh): Remove this after ensuring proper default value for vSwitchName throughout traffic types // and switch types. if (ethPortProfileName == null) { s_logger.warn("Detected null ethrenet port profile. Defaulting to epp0."); ethPortProfileName = "epp0"; } morEthernetPortProfile = dataCenterMo.getDvPortGroupMor(ethPortProfileName); if (morEthernetPortProfile == null) { String msg = "Unable to find Ethernet port profile " + ethPortProfileName; s_logger.error(msg); throw new Exception(msg); } else { s_logger.info("Found Ethernet port profile " + ethPortProfileName); } long averageBandwidth = 0L; if (networkRateMbps != null && networkRateMbps.intValue() > 0) { averageBandwidth = networkRateMbps.intValue() * 1024L * 1024L; } // We chose 50% higher allocation than average bandwidth. // TODO(sateesh): Optionally let user specify the peak coefficient long peakBandwidth = (long) (averageBandwidth * 1.5); // TODO(sateesh): Optionally let user specify the burst coefficient long burstSize = 5 * averageBandwidth / 8; if (vsmCredentials != null) { s_logger.info("Stocking credentials of Nexus VSM"); context.registerStockObject("vsmcredentials", vsmCredentials); } if (!dataCenterMo.hasDvPortGroup(networkName)) { s_logger.info("Port profile " + networkName + " not found."); createPortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize, gateway, configureVServiceInNexus); bWaitPortGroupReady = true; } else { s_logger.info("Port profile " + networkName + " found."); updatePortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize); } } // Wait for dvPortGroup on vCenter if (bWaitPortGroupReady) morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs); else morNetwork = dataCenterMo.getDvPortGroupMor(networkName); if (morNetwork == null) { String msg = "Failed to create guest network " + networkName; s_logger.error(msg); throw new Exception(msg); } if (createGCTag) { NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork); networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true"); s_logger.debug("Added custom field : " + CustomFieldConstants.CLOUD_GC_DVP); } return new Pair<ManagedObjectReference, String>(morNetwork, networkName); }
From source file:org.parosproxy.paros.core.scanner.AbstractPlugin.java
@Override public void cloneInto(Plugin plugin) { if (plugin instanceof AbstractPlugin) { AbstractPlugin ap = (AbstractPlugin) plugin; ap.setAlertThreshold(this.getAlertThreshold(true)); ap.setEnabled(this.isEnabled()); ap.setAttackStrength(this.getAttackStrength(true)); ap.setDefaultAlertThreshold(this.defaultAttackThreshold); ap.setDefaultAttackStrength(this.defaultAttackStrength); ap.setTechSet(this.getTechSet()); ap.setStatus(this.getStatus()); ap.saveTo(plugin.getConfig());// w w w . j a v a 2 s . c o m } else { throw new InvalidParameterException("Not an AbstractPlugin"); } }
From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Produce a list of request operations from an uploaded RAML file * <p>/*from w ww .j a v a2 s.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. * @param generateServiceDocument when true, the VSI transformation will include a service document transaction defined. (default: false) * @return HTTP response containing a list of REST operations defined in the uploaded RAML file */ @POST @Path("vsiOperations") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN) public Response genVsiOperations(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream, @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail, @DefaultValue("") @FormDataParam("baseUri") String baseUri, @DefaultValue("false") @FormDataParam("generateServiceDocument") Boolean generateServiceDocument) { log.info("POST raml/vsiOperations"); 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); } VSI vsi = new VSI(raml, ramlFile.getParentFile(), generateServiceDocument); StringBuffer sb = new StringBuffer(); for (String operation : vsi.getOperationsList(raml.getResources())) { sb.append(String.format("%s\n", operation)); } response = Response.status(Status.OK).entity(sb.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.transdroid.core.app.settings.ApplicationSettings.java
/** * Stores the user settings for some specific app widget. Existing settings for the supplied app widget ID will be * overridden.//from ww w . j av a 2 s .co m * @param appWidgetId The unique ID of the app widget to store settings for, as supplied by the AppWidgetManager * @param settings A widget configuration object, which may not be null */ public void setWidgetConfig(int appWidgetId, ListWidgetConfig settings) { if (settings == null) throw new InvalidParameterException( "The widget setting may not be null. Use removeWidgetConfig instead to remove existing settings for some app widget."); Editor edit = prefs.edit(); edit.putInt("widget_server_" + appWidgetId, settings.getServerId()); edit.putString("widget_status_" + appWidgetId, settings.getStatusType().name()); edit.putString("widget_sortby_" + appWidgetId, settings.getSortBy().name()); edit.putBoolean("widget_reverse_" + appWidgetId, settings.shouldReserveSort()); edit.putBoolean("widget_showstatus_" + appWidgetId, settings.shouldShowStatusView()); edit.putBoolean("widget_darktheme_" + appWidgetId, settings.shouldUseDarkTheme()); edit.apply(); }
From source file:squash.deployment.lambdas.ApiGatewayCustomResourceLambda.java
CreateResourceResult createTopLevelResourceOnApi(String resourceName, String restApiId, AmazonApiGateway client, LambdaLogger logger) {/*from w w w. j av a2 s . c o m*/ logger.log("Creating top-level resource: " + resourceName); // Short sleep - this avoids the Too Many Requests error in this // custom resource when creating the cloudformation stack. pause(logger); CreateResourceRequest createResourceRequest = new CreateResourceRequest(); createResourceRequest.setRestApiId(restApiId); if (resourceName.equals("bookings")) { createResourceRequest.setPathPart("bookings"); } else if (resourceName.equals("bookingrules")) { createResourceRequest.setPathPart("bookingrules"); } else if (resourceName.equals("validdates")) { createResourceRequest.setPathPart("validdates"); } else if (resourceName.equals("reservationform")) { createResourceRequest.setPathPart("reservationform"); } else if (resourceName.equals("cancellationform")) { createResourceRequest.setPathPart("cancellationform"); } else { throw new InvalidParameterException("Invalid resource name: " + resourceName); } // Get the id of the parent resource GetResourcesRequest getResourcesRequest = new GetResourcesRequest(); // High enough limit for now getResourcesRequest.setLimit(10); getResourcesRequest.setRestApiId(restApiId); GetResourcesResult resourcesResult = client.getResources(getResourcesRequest); String rootResourceId = resourcesResult.getItems().stream() .filter(resource -> resource.getPath().equals("/")).findFirst().get().getId(); logger.log("Parent(root) resource id: " + rootResourceId); createResourceRequest.setParentId(rootResourceId); return client.createResource(createResourceRequest); }
From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Deploys an OData virtual service from an uploaded RAML file * <p>/*from ww w . ja v a 2 s. c om*/ * @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. * @param authorization basic authorization string (user:password) used to grant access to LISA/DevTest REST APIs (when required) * @return HTTP response containing a status of OData virtual service deployed from uploaded RAML file */ @POST @Path("odataVs") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response deployOdataVS(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream, @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail, @DefaultValue("") @FormDataParam("baseUri") String baseUri, @DefaultValue("") @FormDataParam("authorization") String authorization) { log.info("POST raml/odataVs"); 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); } try { Context initialContext = new InitialContext(); Context envContext = (Context) initialContext.lookup("java:comp/env"); String vseServerUrl = (String) envContext.lookup("vseServerUrl"); String vseServicePortRange = (String) envContext.lookup("vseServicePortRange"); int vseServiceReadyWaitSeconds = (Integer) envContext.lookup("vseServiceReadyWaitSeconds"); // Generate mar and deploy VS VirtualServiceBuilder vs = new VirtualServiceBuilder(vseServerUrl, vseServicePortRange, vseServiceReadyWaitSeconds, false, authorization); response = vs.setInputFile(raml, ramlFile.getParentFile(), false); } catch (Exception e) { String msg = String.format("Failed to deploy service - %s", e.getMessage()); throw new Exception(msg, e.getCause()); } } 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); 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.matonto.catalog.impl.SimpleCatalogManager.java
@Override public InProgressCommit createInProgressCommit(User user, Resource recordId) throws InvalidParameterException { if (!resourceExists(recordId, VersionedRDFRecord.TYPE)) { throw new InvalidParameterException("The provided Resource does not identify a Record entity."); } else if (getInProgressCommitIRI(user.getResource(), recordId).isPresent()) { throw new MatOntoException("The user already has an InProgressCommit for the identified Record."); } else {//from w w w . ja va 2 s. c o m UUID uuid = UUID.randomUUID(); Revision revision = revisionFactory.createNew(vf.createIRI(REVISION_NAMESPACE + uuid)); revision.setAdditions(vf.createIRI(ADDITIONS_NAMESPACE + uuid)); revision.setDeletions(vf.createIRI(DELETIONS_NAMESPACE + uuid)); InProgressCommit inProgressCommit = inProgressCommitFactory .createNew(vf.createIRI(IN_PROGRESS_COMMIT_NAMESPACE + uuid)); inProgressCommit.setOnVersionedRDFRecord(versionedRDFRecordFactory.createNew(recordId)); inProgressCommit.setProperty(user.getResource(), vf.createIRI(Activity.wasAssociatedWith_IRI)); inProgressCommit.setProperty(revision.getResource(), vf.createIRI(Activity.generated_IRI)); inProgressCommit.getModel().addAll(revision.getModel()); return inProgressCommit; } }
From source file:org.parosproxy.paros.Constant.java
public static void setLowMemoryOption(boolean lowMem) { if (lowMemoryOption != null) { throw new InvalidParameterException("Low memory option already set to " + lowMemoryOption); }/*from ww w .j av a 2 s . c o m*/ lowMemoryOption = lowMem; }
From source file:org.opensolaris.opengrok.web.PageConfig.java
/** * Get opengrok's configured dataroot directory. It is verified, that the * used environment has a valid opengrok data root set and that it is an * accessible directory.//from w ww . j a v a 2 s .c o m * * @return the opengrok data directory. * @throws InvalidParameterException if inaccessible or not set. */ public File getDataRoot() { if (dataRoot == null) { String tmp = getEnv().getDataRootPath(); if (tmp == null || tmp.length() == 0) { throw new InvalidParameterException("dataRoot parameter is not " + "set in configuration.xml!"); } dataRoot = new File(tmp); if (!(dataRoot.isDirectory() && dataRoot.canRead())) { throw new InvalidParameterException( "The configured dataRoot '" + tmp + "' refers to a none-existing or unreadable directory!"); } } return dataRoot; }