List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file, final String mimeType)
From source file:org.ohmage.OhmageApi.java
public UploadResponse surveyUpload(String serverUrl, String username, String hashedPassword, String client, String campaignUrn, String campaignCreationTimestamp, String responseJson, File[] photos) { final boolean GZIP = false; String url = serverUrl + SURVEY_UPLOAD_PATH; try {/*from ww w . j a v a 2 s . c o m*/ MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("campaign_urn", new StringBody(campaignUrn)); multipartEntity.addPart("campaign_creation_timestamp", new StringBody(campaignCreationTimestamp)); multipartEntity.addPart("user", new StringBody(username)); multipartEntity.addPart("password", new StringBody(hashedPassword)); multipartEntity.addPart("client", new StringBody(client)); multipartEntity.addPart("surveys", new StringBody(responseJson)); if (photos != null) { for (int i = 0; i < photos.length; i++) { multipartEntity.addPart(photos[i].getName().split("\\.")[0], new FileBody(photos[i], "image/jpeg")); } } return parseUploadResponse(doHttpPost(url, multipartEntity, GZIP)); } catch (IOException e) { Log.e(TAG, "IOException while creating http entity", e); return new UploadResponse(Result.INTERNAL_ERROR, null); } }
From source file:org.ohmage.OhmageApi.java
public UploadResponse mediaUpload(String serverUrl, String username, String hashedPassword, String client, String campaignUrn, String campaignCreationTimestamp, String uuid, File data) { final boolean GZIP = false; String url = serverUrl + IMAGE_UPLOAD_PATH; try {// w ww.ja va2 s .c o m MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("campaign_urn", new StringBody(campaignUrn)); multipartEntity.addPart("campaign_creation_timestamp", new StringBody(campaignCreationTimestamp)); multipartEntity.addPart("user", new StringBody(username)); multipartEntity.addPart("password", new StringBody(hashedPassword)); multipartEntity.addPart("client", new StringBody(client)); multipartEntity.addPart("id", new StringBody(uuid)); multipartEntity.addPart("data", new FileBody(data, "image/jpeg")); return parseUploadResponse(doHttpPost(url, multipartEntity, GZIP)); } catch (IOException e) { Log.e(TAG, "IOException while creating http entity", e); return new UploadResponse(Result.INTERNAL_ERROR, null); } }
From source file:org.opendatakit.briefcase.util.AggregateUtils.java
public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u, String distinguishedFileTagName, File file, List<File> files, DocumentDescription description, SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) { boolean allSuccessful = true; formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true); EventBus.publish(new FormStatusEvent(formToTransfer)); boolean first = true; // handles case where there are no media files int lastJ = 0; int j = 0;/* ww w . ja va 2s .c o m*/ while (j < files.size() || first) { lastJ = j; first = false; if (terminationFuture.isCancelled()) { formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true); EventBus.publish(new FormStatusEvent(formToTransfer)); return false; } HttpPost httppost = WebUtils.createOpenRosaHttpPost(u); long byteCount = 0L; // mime post MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // add the submission file first... FileBody fb = new FileBody(file, ContentType.TEXT_XML); builder.addPart(distinguishedFileTagName, fb); log.info("added " + distinguishedFileTagName + ": " + file.getName()); byteCount += file.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } // we will be processing every one of these, so // we only need to deal with the content type determination... if (extension.equals("xml")) { fb = new FileBody(f, ContentType.TEXT_XML); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, ContentType.create("image/jpeg")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, ContentType.create("audio/3gpp")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, ContentType.create("video/3gpp")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, ContentType.create("video/mp4")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, ContentType.create("text/csv")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added csv file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, ContentType.create("application/vnd.ms-excel")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.info("added xls file " + f.getName()); } else { fb = new FileBody(f, ContentType.create("application/octet-stream")); builder.addPart(f.getName(), fb); byteCount += f.length(); log.warn("added unrecognized file (application/octet-stream) " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) { // more than 100 attachments or the next file would exceed the 10MB threshold... log.info("Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8"))); builder.addPart("*isIncomplete*", sb); } catch (Exception e) { log.error("impossible condition", e); throw new IllegalStateException("never happens"); } ++j; // advance over the last attachment added... break; } } } httppost.setEntity(builder.build()); int[] validStatusList = { 201 }; try { if (j != files.size()) { formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size() + " media attachments", true); } else if (j == 0) { formToTransfer.setStatusString( "Uploading " + description.getDocumentDescriptionType() + " with no media attachments", true); } else { formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and " + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true); } EventBus.publish(new FormStatusEvent(formToTransfer)); httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action); } catch (XmlDocumentFetchException e) { allSuccessful = false; log.error("upload failed", e); formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false); EventBus.publish(new FormStatusEvent(formToTransfer)); if (description.isCancelled()) return false; } } return allSuccessful; }
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.RMServiceImpl.java
public String login(String login, String pass, File cred, String ssh) throws RestServerException, ServiceException { HttpPost httpPost = new HttpPost(RMConfig.get().getRestUrl() + "/rm/login"); try {//from w w w .ja v a 2 s. c o m MultipartEntity entity; if (cred == null) { entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh); } else { entity = new MultipartEntity(); entity.addPart("credential", new FileBody(cred, "application/octet-stream")); } httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); String responseAsString = convertToString(response.getEntity().getContent()); switch (response.getStatusLine().getStatusCode()) { case 200: break; default: if (responseAsString.trim().length() == 0) { responseAsString = "{ \"httpErrorCode\": " + response.getStatusLine().getStatusCode() + "," + "\"errorMessage\": \"" + response.getStatusLine().getReasonPhrase() + "\" }"; } throw new RestServerException(response.getStatusLine().getStatusCode(), responseAsString); } return responseAsString; } catch (IOException e) { throw new ServiceException(e.getMessage()); } finally { httpPost.releaseConnection(); if (cred != null) { cred.delete(); } } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.SchedulerServiceImpl.java
/** * Login to the scheduler using a Credentials file * * @return the sessionId which can be parsed as an Integer, or an error * message//from w w w . j ava 2s . co m * @throws RestServerException * @throws ServiceException */ @Override public String login(String login, String pass, File cred, String ssh) throws RestServerException, ServiceException { HttpPost method = new HttpPost(SchedulerConfig.get().getRestUrl() + "/scheduler/login"); try { MultipartEntity entity; if (cred == null) { entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh); } else { entity = new MultipartEntity(); entity.addPart("credential", new FileBody(cred, "application/octet-stream")); } method.setEntity(entity); HttpResponse response = httpClient.execute(method); String responseAsString = convertToString(response.getEntity().getContent()); switch (response.getStatusLine().getStatusCode()) { case 200: break; default: String message = responseAsString; if (message.trim().length() == 0) { message = "{ \"httpErrorCode\": " + response.getStatusLine().getStatusCode() + "," + "\"errorMessage\": \"" + response.getStatusLine().getReasonPhrase() + "\" }"; } throw new RestServerException(response.getStatusLine().getStatusCode(), message); } return responseAsString; } catch (IOException e) { throw new ServiceException(e.getMessage()); } finally { method.releaseConnection(); if (cred != null) { cred.delete(); } } }
From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java
/** * This method is to functionality of add a new API in API-Provider * * @param cx Rhino context/*from www . j av a2s .c om*/ * @param thisObj Scriptable object * @param args Passing arguments * @param funObj Function object * @return true if the API was added successfully * @throws APIManagementException Wrapped exception by org.wso2.carbon.apimgt.api.APIManagementException * @throws FaultGatewaysException */ public static boolean jsFunction_addAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws APIManagementException, ScriptException, FaultGatewaysException { if (args == null || args.length == 0) { handleException("Invalid number of input parameters."); } boolean success; NativeObject apiData = (NativeObject) args[0]; String provider = String.valueOf(apiData.get("provider", apiData)); if (provider != null) { provider = APIUtil.replaceEmailDomain(provider); } String name = (String) apiData.get("apiName", apiData); String version = (String) apiData.get("version", apiData); String defaultVersion = (String) apiData.get("defaultVersion", apiData); String description = (String) apiData.get("description", apiData); String endpoint = (String) apiData.get("endpoint", apiData); String sandboxUrl = (String) apiData.get("sandbox", apiData); String visibility = (String) apiData.get("visibility", apiData); String thumbUrl = (String) apiData.get("thumbUrl", apiData); String environments = (String) apiData.get("environments", apiData); String visibleRoles = ""; if (name != null) { name = name.trim(); if (name.isEmpty()) { handleException("API name is not specified"); } } if (version != null) { version = version.trim(); if (version.isEmpty()) { handleException("Version not specified for API " + name); } } if (visibility != null && visibility.equals(APIConstants.API_RESTRICTED_VISIBILITY)) { visibleRoles = (String) apiData.get("visibleRoles", apiData); } if (sandboxUrl != null && sandboxUrl.trim().length() == 0) { sandboxUrl = null; } if (endpoint != null && endpoint.trim().length() == 0) { endpoint = null; } if (endpoint != null && !endpoint.startsWith("http") && !endpoint.startsWith("https")) { endpoint = "http://" + endpoint; } if (sandboxUrl != null && !sandboxUrl.startsWith("http") && !sandboxUrl.startsWith("https")) { sandboxUrl = "http://" + sandboxUrl; } String redirectURL = (String) apiData.get("redirectURL", apiData); boolean advertiseOnly = Boolean.parseBoolean((String) apiData.get("advertiseOnly", apiData)); String apiOwner = (String) apiData.get("apiOwner", apiData); if (apiOwner == null || apiOwner.equals("")) { apiOwner = provider; } String wsdl = (String) apiData.get("wsdl", apiData); String wadl = (String) apiData.get("wadl", apiData); String tags = (String) apiData.get("tags", apiData); String subscriptionAvailability = (String) apiData.get("subscriptionAvailability", apiData); String subscriptionAvailableTenants = ""; if (subscriptionAvailability != null && subscriptionAvailability.equals(APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS)) { subscriptionAvailableTenants = (String) apiData.get("subscriptionTenants", apiData); } Set<String> tag = new HashSet<String>(); if (tags != null) { if (tags.contains(",")) { String[] userTag = tags.split(","); tag.addAll(Arrays.asList(userTag).subList(0, tags.split(",").length)); } else { tag.add(tags); } } String transport = getTransports(apiData); String tier = (String) apiData.get("tier", apiData); if (StringUtils.isBlank(tier)) { handleException("No tier defined for the API"); } FileHostObject fileHostObject = (FileHostObject) apiData.get("imageUrl", apiData); String contextVal = (String) apiData.get("context", apiData); if (contextVal.isEmpty()) { handleException("Context not defined for API"); } if (contextVal.endsWith("/")) { handleException("Context cannot end with '/' character"); } APIProvider apiProvider = getAPIProvider(thisObj); //check for context exists if (apiProvider.isDuplicateContextTemplate(contextVal)) { handleException("Error occurred while adding the API. A duplicate API context already exists for " + contextVal); } String context = contextVal.startsWith("/") ? contextVal : ("/" + contextVal); String providerDomain = MultitenantUtils.getTenantDomain(String.valueOf(apiData.get("provider", apiData))); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain)) { //Create tenant aware context for API context = "/t/" + providerDomain + context; } // This is to support the new Pluggable version strategy // if the context does not contain any {version} segment, we use the default version strategy. context = checkAndSetVersionParam(context); String contextTemplate = context; context = updateContextWithVersion(version, contextVal, context); NativeArray uriTemplateArr = (NativeArray) apiData.get("uriTemplateArr", apiData); String techOwner = (String) apiData.get("techOwner", apiData); String techOwnerEmail = (String) apiData.get("techOwnerEmail", apiData); String bizOwner = (String) apiData.get("bizOwner", apiData); String bizOwnerEmail = (String) apiData.get("bizOwnerEmail", apiData); String endpointSecured = (String) apiData.get("endpointSecured", apiData); String endpointAuthDigest = (String) apiData.get("endpointAuthDigest", apiData); String endpointUTUsername = (String) apiData.get("endpointUTUsername", apiData); String endpointUTPassword = (String) apiData.get("endpointUTPassword", apiData); String inSequence = (String) apiData.get("inSequence", apiData); String outSequence = (String) apiData.get("outSequence", apiData); String faultSequence = (String) apiData.get("faultSequence", apiData); String responseCache = (String) apiData.get("responseCache", apiData); String corsConfiguraion = (String) apiData.get("corsConfiguration", apiData); int cacheTimeOut = APIConstants.API_RESPONSE_CACHE_TIMEOUT; if (APIConstants.ENABLED.equalsIgnoreCase(responseCache)) { responseCache = APIConstants.ENABLED; try { cacheTimeOut = Integer.parseInt((String) apiData.get("cacheTimeout", apiData)); } catch (NumberFormatException e) { //ignore } } else { responseCache = APIConstants.DISABLED; } provider = (provider != null ? provider.trim() : null); name = (name != null ? name.trim() : null); version = (version != null ? version.trim() : null); APIIdentifier apiId = new APIIdentifier(provider, name, version); if (apiProvider.isAPIAvailable(apiId)) { handleException("Error occurred while adding the API. A duplicate API already exists for " + name + "-" + version); } API api = new API(apiId); // to keep the backword compatibility if swagger not set process from // resource_config or old way. if (apiData.get("swagger", apiData) == null) { if (apiData.get("resource_config", apiData) != null) { Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>(); JSONParser parser = new JSONParser(); JSONObject resourceConfig = null; try { resourceConfig = (JSONObject) parser.parse((String) apiData.get("resource_config", apiData)); } catch (ParseException e) { handleException("Invalid resource config", e); } catch (ClassCastException e) { handleException("Unable to create JSON object from resource config", e); } // process scopes JSONArray scopes = (JSONArray) resourceConfig.get("scopes"); Set<Scope> scopeList = new LinkedHashSet<Scope>(); for (int i = 0; i < scopes.size(); i++) { Map scope = (Map) scopes.get(i); // access with get() method Scope scopeObj = new Scope(); scopeObj.setKey((String) scope.get("key")); scopeObj.setName((String) scope.get("name")); scopeObj.setRoles((String) scope.get("roles")); scopeObj.setDescription((String) scope.get("description")); scopeList.add(scopeObj); } api.setScopes(scopeList); JSONArray resources = (JSONArray) resourceConfig.get("resources"); for (int k = 0; k < resources.size(); k++) { JSONObject resource = (JSONObject) resources.get(k); Map http_verbs = (Map) resource.get("http_verbs"); Iterator iterator = http_verbs.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); Map mapEntryValue = (Map) mapEntry.getValue(); URITemplate template = new URITemplate(); String uriTempVal = (String) resource.get("url_pattern"); uriTempVal = uriTempVal.startsWith("/") ? uriTempVal : ("/" + uriTempVal); template.setUriTemplate(uriTempVal); String verb = (String) mapEntry.getKey(); if (isHTTPMethodValid(verb)) { template.setHTTPVerb(verb); } else { handleException("Specified HTTP verb " + verb + " is invalid"); } String authType = (String) mapEntryValue.get("auth_type"); if (authType.equals("Application & Application User")) { authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } if (authType.equals("Application User")) { authType = "Application_User"; } if (authType.equals("Application")) { authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN; } template.setThrottlingTier((String) mapEntryValue.get("throttling_tier")); template.setAuthType(authType); template.setResourceURI(endpoint); template.setResourceSandboxURI(sandboxUrl); Scope scope = APIUtil.findScopeByKey(scopeList, (String) mapEntryValue.get("scope")); template.setScope(scope); uriTemplates.add(template); } } // todo handle casting exceptions api.setUriTemplates(uriTemplates); // todo clean out the code. } else { // following is the old fashioned way of processing resources NativeArray uriMethodArr = (NativeArray) apiData.get("uriMethodArr", apiData); NativeArray authTypeArr = (NativeArray) apiData.get("uriAuthMethodArr", apiData); NativeArray throttlingTierArr = (NativeArray) apiData.get("throttlingTierArr", apiData); if (uriTemplateArr != null && uriMethodArr != null && authTypeArr != null) { if (uriTemplateArr.getLength() == uriMethodArr.getLength()) { Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>(); for (int i = 0; i < uriTemplateArr.getLength(); i++) { String uriMethods = (String) uriMethodArr.get(i, uriMethodArr); String uriMethodsAuthTypes = (String) authTypeArr.get(i, authTypeArr); String[] uriMethodArray = uriMethods.split(","); String[] authTypeArray = uriMethodsAuthTypes.split(","); String uriMethodsThrottlingTiers = (String) throttlingTierArr.get(i, throttlingTierArr); String[] throttlingTierArray = uriMethodsThrottlingTiers.split(","); for (int k = 0; k < uriMethodArray.length; k++) { for (int j = 0; j < authTypeArray.length; j++) { if (j == k) { URITemplate template = new URITemplate(); String uriTemp = (String) uriTemplateArr.get(i, uriTemplateArr); String uriTempVal = uriTemp.startsWith("/") ? uriTemp : ("/" + uriTemp); template.setUriTemplate(uriTempVal); String throttlingTier = throttlingTierArray[j]; if (isHTTPMethodValid(uriMethodArray[k])) { template.setHTTPVerb(uriMethodArray[k]); } else { handleException( "Specified HTTP verb " + uriMethodArray[k] + " is invalid"); } String authType = authTypeArray[j]; if (authType.equals("Application & Application User")) { authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } if (authType.equals("Application User")) { authType = "Application_User"; } if (authType.equals("Application")) { authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN; } template.setThrottlingTier(throttlingTier); template.setAuthType(authType); template.setResourceURI(endpoint); template.setResourceSandboxURI(sandboxUrl); uriTemplates.add(template); break; } } } } api.setUriTemplates(uriTemplates); } } } } api.setDescription(StringEscapeUtils.escapeHtml(description)); api.setWsdlUrl(wsdl); api.setWadlUrl(wadl); api.setLastUpdated(new Date()); api.setUrl(endpoint); api.setSandboxUrl(sandboxUrl); api.addTags(tag); api.setTransports(transport); api.setApiOwner(apiOwner); api.setAdvertiseOnly(advertiseOnly); api.setRedirectURL(redirectURL); api.setSubscriptionAvailability(subscriptionAvailability); api.setSubscriptionAvailableTenants(subscriptionAvailableTenants); api.setResponseCache(responseCache); api.setCacheTimeout(cacheTimeOut); api.setAsDefaultVersion("default_version".equals(defaultVersion)); api.setProductionMaxTps((String) apiData.get("productionTps", apiData)); api.setSandboxMaxTps((String) apiData.get("sandboxTps", apiData)); if (!"none".equals(inSequence)) { api.setInSequence(inSequence); } if (!"none".equals(outSequence)) { api.setOutSequence(outSequence); } List<String> sequenceList = apiProvider.getCustomFaultSequences(apiId); if (!"none".equals(faultSequence) && sequenceList.contains(faultSequence)) { api.setFaultSequence(faultSequence); } Set<Tier> availableTier = new HashSet<Tier>(); String[] tierNames; if (tier != null) { tierNames = tier.split(","); if (!APIUtil.isAdvanceThrottlingEnabled()) { Set<Tier> definedTiers = apiProvider.getTiers(); for (String tierName : tierNames) { boolean isTierValid = false; for (Tier definedTier : definedTiers) { if (tierName.equals(definedTier.getName())) { isTierValid = true; break; } } if (!isTierValid) { handleException("Specified tier " + tierName + " does not exist"); } availableTier.add(new Tier(tierName)); } } else { Policy[] definedTiers = apiProvider.getPolicies(provider, PolicyConstants.POLICY_LEVEL_SUB); for (String tierName : tierNames) { boolean isTierValid = false; for (Policy definedTier : definedTiers) { if (tierName.equals(definedTier.getPolicyName())) { isTierValid = true; break; } } if (!isTierValid) { handleException("Specified tier " + tierName + " does not exist"); } availableTier.add(new Tier(tierName)); } } api.addAvailableTiers(availableTier); } api.setStatus(APIStatus.CREATED); api.setContext(context); api.setContextTemplate(contextTemplate); api.setBusinessOwner(bizOwner); api.setBusinessOwnerEmail(bizOwnerEmail); api.setTechnicalOwner(techOwner); api.setTechnicalOwnerEmail(techOwnerEmail); api.setVisibility(visibility); api.setVisibleRoles(visibleRoles != null ? visibleRoles.trim() : null); api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environments)); CORSConfiguration corsConfiguration = APIUtil.getCorsConfigurationDtoFromJson(corsConfiguraion); if (corsConfiguration != null) { api.setCorsConfiguration(corsConfiguration); } String endpointConfig = (String) apiData.get("endpoint_config", apiData); if (StringUtils.isEmpty(endpointConfig)) { handleException("Endpoint Configuration is missing"); } else { api.setEndpointConfig(endpointConfig); //Validate endpoint URI format validateEndpointURI(api.getEndpointConfig()); } //set secured endpoint parameters if ("secured".equals(endpointSecured)) { api.setEndpointSecured(true); api.setEndpointUTUsername(endpointUTUsername); api.setEndpointUTPassword(endpointUTPassword); if ("digestAuth".equals(endpointAuthDigest)) { api.setEndpointAuthDigest(true); } else { api.setEndpointAuthDigest(false); } } checkFileSize(fileHostObject); boolean isTenantFlowStarted = false; try { String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider)); if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { isTenantFlowStarted = true; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } apiProvider.addAPI(api); if (fileHostObject != null && fileHostObject.getJavaScriptFile().getLength() != 0) { String thumbPath = addThumbIcon(fileHostObject.getInputStream(), fileHostObject.getJavaScriptFile().getContentType(), apiProvider, api); apiProvider.updateAPI(api); } NativeArray externalAPIStores = (NativeArray) apiData.get("externalAPIStores", apiData); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); if (externalAPIStores.getLength() != 0) { Set<APIStore> apiStores = new HashSet<APIStore>(); for (int k = 0; k < externalAPIStores.getLength(); k++) { String apiStoreName = externalAPIStores.get(k, externalAPIStores).toString(); apiStores.add(APIUtil.getExternalAPIStore(apiStoreName, tenantId)); } apiProvider.publishToExternalAPIStores(api, apiStores, false); } success = true; } catch (Exception e) { handleException("Error while adding the API- " + name + "-" + version, e); return false; } finally { if (isTenantFlowStarted) { PrivilegedCarbonContext.endTenantFlow(); } } if (thumbUrl != null && !thumbUrl.isEmpty()) { try { URL url = new URL(thumbUrl); String imageType = url.openConnection().getContentType(); File fileToUploadFromUrl = new File(ICON_PATH); if (!fileToUploadFromUrl.exists()) { if (!fileToUploadFromUrl.createNewFile()) { log.error("Unable to create new file under : " + ICON_PATH); } } FileUtils.copyURLToFile(url, fileToUploadFromUrl); FileBody fileBody = new FileBody(fileToUploadFromUrl, imageType); checkImageSize(fileToUploadFromUrl); String thumbPath = addThumbIcon(fileBody.getInputStream(), url.openConnection().getContentType(), apiProvider, api); } catch (IOException e) { handleException("[Error] Cannot read data from the URL", e); } apiProvider.updateAPI(api); } if (apiData.get("swagger", apiData) != null) { // Read URI Templates from swagger resource and set to api object Set<URITemplate> uriTemplates = definitionFromSwagger20.getURITemplates(api, String.valueOf(apiData.get("swagger", apiData))); api.setUriTemplates(uriTemplates); // scopes Set<Scope> scopes = definitionFromSwagger20.getScopes(String.valueOf(apiData.get("swagger", apiData))); api.setScopes(scopes); String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider)); try { int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); for (URITemplate uriTemplate : uriTemplates) { Scope scope = uriTemplate.getScope(); if (scope != null && !(APIUtil.isWhiteListedScope(scope.getKey()))) { if (apiProvider.isScopeKeyAssigned(apiId, scope.getKey(), tenantId)) { handleException("Scope " + scope.getKey() + " is already assigned by another API"); } } } } catch (UserStoreException e) { handleException("Error while reading tenant information ", e); } // Save swagger in the registry apiProvider.saveSwagger20Definition(api.getId(), (String) apiData.get("swagger", apiData)); saveAPI(apiProvider, api, null, false); } else { String apiDefinitionJSON = definitionFromSwagger20.generateAPIDefinition(api); apiProvider.saveSwagger20Definition(api.getId(), apiDefinitionJSON); } return success; }
From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java
public static boolean jsFunction_updateAPI(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws APIManagementException, FaultGatewaysException { if (args == null || args.length == 0) { handleException("Invalid number of input parameters."); }//from w ww.j a va 2s . co m NativeObject apiData = (NativeObject) args[0]; boolean success; String provider = String.valueOf(apiData.get("provider", apiData)); if (provider != null) { provider = APIUtil.replaceEmailDomain(provider); } String name = (String) apiData.get("apiName", apiData); String version = (String) apiData.get("version", apiData); String defaultVersion = (String) apiData.get("defaultVersion", apiData); String description = (String) apiData.get("description", apiData); FileHostObject fileHostObject = (FileHostObject) apiData.get("imageUrl", apiData); String endpoint = (String) apiData.get("endpoint", apiData); String sandboxUrl = (String) apiData.get("sandbox", apiData); String techOwner = (String) apiData.get("techOwner", apiData); String techOwnerEmail = (String) apiData.get("techOwnerEmail", apiData); String bizOwner = (String) apiData.get("bizOwner", apiData); String bizOwnerEmail = (String) apiData.get("bizOwnerEmail", apiData); String visibility = (String) apiData.get("visibility", apiData); String thumbUrl = (String) apiData.get("thumbUrl", apiData); String environments = (String) apiData.get("environments", apiData); String corsConfiguraion = (String) apiData.get("corsConfiguration", apiData); String visibleRoles = ""; if (visibility != null && visibility.equals(APIConstants.API_RESTRICTED_VISIBILITY)) { visibleRoles = (String) apiData.get("visibleRoles", apiData); } String visibleTenants = ""; if (visibility != null && visibility.equals(APIConstants.API_CONTROLLED_VISIBILITY)) { visibleTenants = (String) apiData.get("visibleTenants", apiData); } String endpointSecured = (String) apiData.get("endpointSecured", apiData); String endpointAuthDigest = (String) apiData.get("endpointAuthDigest", apiData); String endpointUTUsername = (String) apiData.get("endpointUTUsername", apiData); String endpointUTPassword = (String) apiData.get("endpointUTPassword", apiData); String inSequence = (String) apiData.get("inSequence", apiData); String outSequence = (String) apiData.get("outSequence", apiData); String faultSequence = (String) apiData.get("faultSequence", apiData); String responseCache = (String) apiData.get("responseCache", apiData); int cacheTimeOut = APIConstants.API_RESPONSE_CACHE_TIMEOUT; if (APIConstants.ENABLED.equalsIgnoreCase(responseCache)) { responseCache = APIConstants.ENABLED; try { cacheTimeOut = Integer.parseInt((String) apiData.get("cacheTimeout", apiData)); } catch (NumberFormatException e) { //ignore } } else { responseCache = APIConstants.DISABLED; } if (sandboxUrl != null && sandboxUrl.trim().length() == 0) { sandboxUrl = null; } if (endpoint != null && endpoint.trim().length() == 0) { endpoint = null; } if (endpoint != null && !endpoint.startsWith("http") && !endpoint.startsWith("https")) { endpoint = "http://" + endpoint; } if (sandboxUrl != null && !sandboxUrl.startsWith("http") && !sandboxUrl.startsWith("https")) { sandboxUrl = "http://" + sandboxUrl; } String redirectURL = (String) apiData.get("redirectURL", apiData); boolean advertiseOnly = Boolean.parseBoolean((String) apiData.get("advertiseOnly", apiData)); String apiOwner = (String) apiData.get("apiOwner", apiData); if (apiOwner == null || apiOwner.equals("")) { apiOwner = provider; } String wsdl = (String) apiData.get("wsdl", apiData); String wadl = (String) apiData.get("wadl", apiData); String subscriptionAvailability = (String) apiData.get("subscriptionAvailability", apiData); String subscriptionAvailableTenants = ""; if (subscriptionAvailability != null && subscriptionAvailability.equals(APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS)) { subscriptionAvailableTenants = (String) apiData.get("subscriptionTenants", apiData); } String tags = (String) apiData.get("tags", apiData); Set<String> tag = new HashSet<String>(); if (tags != null) { if (tags.contains(",")) { String[] userTag = tags.split(","); tag.addAll(Arrays.asList(userTag).subList(0, tags.split(",").length)); } else { tag.add(tags); } } provider = (provider != null ? provider.trim() : null); name = (name != null ? name.trim() : null); version = (version != null ? version.trim() : null); APIIdentifier oldApiId = new APIIdentifier(provider, name, version); APIProvider apiProvider = getAPIProvider(thisObj); boolean isTenantFlowStarted = false; String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider)); if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { isTenantFlowStarted = true; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); } API oldApi = apiProvider.getAPI(oldApiId); String transport = getTransports(apiData); String tier = (String) apiData.get("tier", apiData); String apiLevelPolicy = (String) apiData.get("apiPolicy", apiData); String contextVal = (String) apiData.get("context", apiData); String context = contextVal.startsWith("/") ? contextVal : ("/" + contextVal); String providerDomain = MultitenantUtils.getTenantDomain(String.valueOf(apiData.get("provider", apiData))); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && !context.contains("/t/" + providerDomain)) { //Create tenant aware context for API context = "/t/" + providerDomain + context; } // This is to support the new Pluggable version strategy // if the context does not contain any {version} segment, we use the default version strategy. context = checkAndSetVersionParam(context); String contextTemplate = context; context = updateContextWithVersion(version, contextVal, context); APIIdentifier apiId = new APIIdentifier(provider, name, version); API api = new API(apiId); // to keep the backword compatibility if swagger not set process from // resource_config or old way. if (apiData.get("swagger", apiData) == null) { if (apiData.get("resource_config", apiData) != null) { Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>(); JSONParser parser = new JSONParser(); JSONObject resourceConfig = null; try { resourceConfig = (JSONObject) parser.parse((String) apiData.get("resource_config", apiData)); } catch (ParseException e) { handleException("Invalid resource config", e); } catch (ClassCastException e) { handleException("Unable to create JSON object from resource config", e); } //process scopes JSONArray scopes = (JSONArray) resourceConfig.get("scopes"); Set<Scope> scopeList = new LinkedHashSet<Scope>(); for (int i = 0; i < scopes.size(); i++) { Map scope = (Map) scopes.get(i); //access with get() method Scope scopeObj = new Scope(); scopeObj.setKey((String) scope.get("key")); scopeObj.setName((String) scope.get("name")); scopeObj.setRoles((String) scope.get("roles")); scopeObj.setDescription((String) scope.get("description")); scopeList.add(scopeObj); } api.setScopes(scopeList); JSONArray resources = (JSONArray) resourceConfig.get("resources"); for (int k = 0; k < resources.size(); k++) { JSONObject resource = (JSONObject) resources.get(k); Map http_verbs = (Map) resource.get("http_verbs"); Iterator iterator = http_verbs.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); Map mapEntryValue = (Map) mapEntry.getValue(); URITemplate template = new URITemplate(); String uriTempVal = (String) resource.get("url_pattern"); uriTempVal = uriTempVal.startsWith("/") ? uriTempVal : ("/" + uriTempVal); template.setUriTemplate(uriTempVal); template.setHTTPVerb((String) mapEntry.getKey()); String authType = (String) mapEntryValue.get("auth_type"); if (authType.equals("Application & Application User")) { authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } if (authType.equals("Application User")) { authType = "Application_User"; } if (authType.equals("Application")) { authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN; } template.setThrottlingTier((String) mapEntryValue.get("throttling_tier")); template.setAuthType(authType); template.setResourceURI(endpoint); template.setResourceSandboxURI(sandboxUrl); Scope scope = APIUtil.findScopeByKey(scopeList, (String) mapEntryValue.get("scope")); template.setScope(scope); uriTemplates.add(template); } } //todo handle casting exceptions api.setUriTemplates(uriTemplates); //todo clean out the code. } else { //following is the old fashioned way of processing resources NativeArray uriMethodArr = (NativeArray) apiData.get("uriMethodArr", apiData); NativeArray authTypeArr = (NativeArray) apiData.get("uriAuthMethodArr", apiData); NativeArray throttlingTierArr = (NativeArray) apiData.get("throttlingTierArr", apiData); NativeArray uriTemplateArr = (NativeArray) apiData.get("uriTemplateArr", apiData); if (uriTemplateArr != null && uriMethodArr != null && authTypeArr != null) { if (uriTemplateArr.getLength() == uriMethodArr.getLength()) { Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>(); for (int i = 0; i < uriTemplateArr.getLength(); i++) { String uriMethods = (String) uriMethodArr.get(i, uriMethodArr); String uriMethodsAuthTypes = (String) authTypeArr.get(i, authTypeArr); String[] uriMethodArray = uriMethods.split(","); String[] authTypeArray = uriMethodsAuthTypes.split(","); String uriMethodsThrottlingTiers = (String) throttlingTierArr.get(i, throttlingTierArr); String[] throttlingTierArray = uriMethodsThrottlingTiers.split(","); for (int k = 0; k < uriMethodArray.length; k++) { for (int j = 0; j < authTypeArray.length; j++) { if (j == k) { URITemplate template = new URITemplate(); String uriTemp = (String) uriTemplateArr.get(i, uriTemplateArr); String uriTempVal = uriTemp.startsWith("/") ? uriTemp : ("/" + uriTemp); template.setUriTemplate(uriTempVal); String throttlingTier = throttlingTierArray[j]; template.setHTTPVerb(uriMethodArray[k]); String authType = authTypeArray[j]; if (authType.equals("Application & Application User")) { authType = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN; } if (authType.equals("Application User")) { authType = "Application_User"; } if (authType.equals("Application")) { authType = APIConstants.AUTH_APPLICATION_LEVEL_TOKEN; } template.setThrottlingTier(throttlingTier); template.setAuthType(authType); template.setResourceURI(endpoint); template.setResourceSandboxURI(sandboxUrl); uriTemplates.add(template); break; } } } } api.setUriTemplates(uriTemplates); } } } } api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environments)); CORSConfiguration corsConfiguration = APIUtil.getCorsConfigurationDtoFromJson(corsConfiguraion); if (corsConfiguration != null) { api.setCorsConfiguration(corsConfiguration); } api.setDescription(StringEscapeUtils.escapeHtml(description)); api.setLastUpdated(new Date()); api.setUrl(endpoint); api.setSandboxUrl(sandboxUrl); api.addTags(tag); api.setContext(context); api.setContextTemplate(contextTemplate); api.setVisibility(visibility); api.setVisibleRoles(visibleRoles != null ? visibleRoles.trim() : null); api.setVisibleTenants(visibleTenants != null ? visibleTenants.trim() : null); Set<Tier> availableTier = new HashSet<Tier>(); if (tier != null) { String[] tierNames = tier.split(","); for (String tierName : tierNames) { availableTier.add(new Tier(tierName)); } api.addAvailableTiers(availableTier); } if (apiLevelPolicy != null) { if ("none".equals(apiLevelPolicy)) { api.setApiLevelPolicy(null); } else { api.setApiLevelPolicy(apiLevelPolicy); } } api.setStatus(oldApi.getStatus()); api.setWsdlUrl(wsdl); api.setWadlUrl(wadl); api.setLastUpdated(new Date()); api.setBusinessOwner(bizOwner); api.setBusinessOwnerEmail(bizOwnerEmail); api.setTechnicalOwner(techOwner); api.setTechnicalOwnerEmail(techOwnerEmail); api.setTransports(transport); if (!"none".equals(inSequence)) { api.setInSequence(inSequence); } if (!"none".equals(outSequence)) { api.setOutSequence(outSequence); } List<String> sequenceList = apiProvider.getCustomFaultSequences(apiId); if (!"none".equals(faultSequence) && sequenceList.contains(faultSequence)) { api.setFaultSequence(faultSequence); } api.setOldInSequence(oldApi.getInSequence()); api.setOldOutSequence(oldApi.getOutSequence()); api.setOldFaultSequence(oldApi.getFaultSequence()); api.setRedirectURL(redirectURL); api.setApiOwner(apiOwner); api.setAdvertiseOnly(advertiseOnly); // @todo needs to be validated api.setEndpointConfig((String) apiData.get("endpoint_config", apiData)); //Validate endpoint URI format validateEndpointURI(api.getEndpointConfig()); api.setProductionMaxTps((String) apiData.get("productionTps", apiData)); api.setSandboxMaxTps((String) apiData.get("sandboxTps", apiData)); api.setSubscriptionAvailability(subscriptionAvailability); api.setSubscriptionAvailableTenants(subscriptionAvailableTenants); api.setResponseCache(responseCache); api.setCacheTimeout(cacheTimeOut); api.setAsDefaultVersion("default_version".equals(defaultVersion)); //set secured endpoint parameters if ("secured".equals(endpointSecured)) { api.setEndpointSecured(true); api.setEndpointUTUsername(endpointUTUsername); api.setEndpointUTPassword(endpointUTPassword); if ("digestAuth".equals(endpointAuthDigest)) { api.setEndpointAuthDigest(true); } else { api.setEndpointAuthDigest(false); } } try { checkFileSize(fileHostObject); if (fileHostObject != null && fileHostObject.getJavaScriptFile().getLength() != 0) { String thumbPath = addThumbIcon(fileHostObject.getInputStream(), fileHostObject.getJavaScriptFile().getContentType(), apiProvider, api); } else if (oldApi.getThumbnailUrl() != null) { // retain the previously uploaded image api.setThumbnailUrl(oldApi.getThumbnailUrl()); } if (thumbUrl != null && !thumbUrl.isEmpty()) { try { URL url = new URL(thumbUrl); String imageType = url.openConnection().getContentType(); File fileToUploadFromUrl = new File("tmp/icon"); if (!fileToUploadFromUrl.exists()) { if (!fileToUploadFromUrl.createNewFile()) { log.error("Unable to create new file under tmp/icon"); } } FileUtils.copyURLToFile(url, fileToUploadFromUrl); FileBody fileBody = new FileBody(fileToUploadFromUrl, imageType); checkImageSize(fileToUploadFromUrl); String thumbPath = addThumbIcon(fileBody.getInputStream(), url.openConnection().getContentType(), apiProvider, api); } catch (IOException e) { handleException("[Error] Cannot read data from the URL", e); } } if (apiData.get("swagger", apiData) != null) { // Read URI Templates from swagger resource and set to api object Set<URITemplate> uriTemplates = definitionFromSwagger20.getURITemplates(api, String.valueOf(apiData.get("swagger", apiData))); api.setUriTemplates(uriTemplates); // scopes Set<Scope> scopes = definitionFromSwagger20 .getScopes(String.valueOf(apiData.get("swagger", apiData))); api.setScopes(scopes); try { int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); for (URITemplate uriTemplate : uriTemplates) { Scope scope = uriTemplate.getScope(); if (scope != null && !(APIUtil.isWhiteListedScope(scope.getKey()))) { if (apiProvider.isScopeKeyAssigned(apiId, scope.getKey(), tenantId)) { handleException("Scope " + scope.getKey() + " is already assigned by another API"); } } } } catch (UserStoreException e) { handleException("Error while reading tenant information ", e); } // Save swagger in the registry apiProvider.saveSwagger20Definition(api.getId(), (String) apiData.get("swagger", apiData)); saveAPI(apiProvider, api, null, false); } else { String apiDefinitionJSON = definitionFromSwagger20.generateAPIDefinition(api); apiProvider.saveSwagger20Definition(api.getId(), apiDefinitionJSON); apiProvider.updateAPI(api); } success = true; } catch (Exception e) { handleException("Error while updating the API- " + name + "-" + version, e); return false; } finally { if (isTenantFlowStarted) { PrivilegedCarbonContext.endTenantFlow(); } } return success; }
From source file:org.wso2.msf4j.HttpServerTest.java
@Test public void testFormParamWithFile() throws IOException, URISyntaxException { HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST); File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY); builder.addPart("form", fileBody); HttpEntity build = builder.build();/* w ww .j a v a 2 s . com*/ connection.setRequestProperty("Content-Type", build.getContentType().getValue()); try (OutputStream out = connection.getOutputStream()) { build.writeTo(out); } InputStream inputStream = connection.getInputStream(); String response = StreamUtil.asString(inputStream); IOUtils.closeQuietly(inputStream); connection.disconnect(); assertEquals(response, file.getName()); }