List of usage examples for org.apache.commons.lang3 StringUtils substringAfterLast
public static String substringAfterLast(final String str, final String separator)
Gets the substring after the last occurrence of a separator.
From source file:com.netflix.spinnaker.clouddriver.ecs.deploy.ops.CreateServerGroupAtomicOperation.java
private String inferNextServerGroupVersion(AmazonECS ecs) { int latestVersion = 0; String familyName = getFamilyName(); String nextToken = null;/*from w w w.j a v a 2s . co m*/ do { ListServicesRequest request = new ListServicesRequest().withCluster(description.getEcsClusterName()); if (nextToken != null) { request.setNextToken(nextToken); } ListServicesResult result = ecs.listServices(request); for (String serviceArn : result.getServiceArns()) { if (serviceArn.contains(familyName)) { int currentVersion; try { String versionString = StringUtils.substringAfterLast(serviceArn, "-").replaceAll("v", ""); currentVersion = Integer.parseInt(versionString); } catch (NumberFormatException e) { currentVersion = 0; } latestVersion = Math.max(currentVersion, latestVersion); } } nextToken = result.getNextToken(); } while (nextToken != null && nextToken.length() != 0); return String.format("v%04d", (latestVersion + 1)); }
From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.Applications.java
@Nullable public String findCurrentPackageIdByAppId(String appGuid) throws CloudFoundryApiException { return safelyCall(() -> this.api.findDropletByApplicationGuid(appGuid)) .map(droplet -> StringUtils.substringAfterLast(droplet.getLinks().get("package").getHref(), "/")) .orElse(null);//from ww w. j a v a 2 s .c om }
From source file:ching.icecreaming.action.ViewAction.java
@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"), @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"), @Result(name = "error", location = "error.jsp") }) public String execute() throws Exception { Enumeration enumerator = null; String[] array1 = null, array2 = null; int int1 = -1, int2 = -1, int3 = -1; InputStream inputStream1 = null; OutputStream outputStream1 = null; java.io.File file1 = null, file2 = null, dir1 = null; List<File> files = null; HttpHost httpHost1 = null;//from ww w . ja v a 2s. c o m HttpGet httpGet1 = null, httpGet2 = null; HttpPut httpPut1 = null; URI uri1 = null; URL url1 = null; DefaultHttpClient httpClient1 = null; URIBuilder uriBuilder1 = null, uriBuilder2 = null; HttpResponse httpResponse1 = null, httpResponse2 = null; HttpEntity httpEntity1 = null, httpEntity2 = null; List<NameValuePair> nameValuePair1 = null; String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN; XMLConfiguration xmlConfiguration = null; List<HierarchicalConfiguration> list1 = null, list2 = null; HierarchicalConfiguration hierarchicalConfiguration2 = null; DataModel1 dataModel1 = null; DataModel2 dataModel2 = null; List<DataModel1> listObject1 = null, listObject3 = null; org.joda.time.DateTime dateTime1 = null, dateTime2 = null; org.joda.time.Period period1 = null; PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears() .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years"))) .appendSeparator(" ").appendMonths() .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months"))) .appendSeparator(" ").appendWeeks() .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks"))) .appendSeparator(" ").appendDays() .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days"))) .appendSeparator(" ").appendHours() .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours"))) .appendSeparator(" ").appendMinutes() .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes"))) .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2) .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds"))) .printZeroNever().toFormatter(); if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) { urlString = portletPreferences.getValue("urlString", "/"); wsType = portletPreferences.getValue("wsType", "folder"); } Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties"); timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID()); enumerator = portletPreferences.getNames(); if (enumerator.hasMoreElements()) { array1 = portletPreferences.getValues("server", null); if (array1 != null) { if (ArrayUtils.isNotEmpty(array1)) { for (int1 = 0; int1 < array1.length; int1++) { switch (int1) { case 0: sid = array1[int1]; break; case 1: uid = array1[int1]; break; case 2: pid = array1[int1]; break; case 3: alias1 = array1[int1]; break; default: break; } } sid = new String(Base64.decodeBase64(sid.getBytes())); uid = new String(Base64.decodeBase64(uid.getBytes())); pid = new String(Base64.decodeBase64(pid.getBytes())); } return1 = INPUT; } else { return1 = LOGIN; } } else { return1 = LOGIN; } if (StringUtils.equals(urlString, "/")) { if (listObject1 != null) { listObject1.clear(); } if (session.containsKey("breadcrumbs")) { session.remove("breadcrumbs"); } } else { array2 = StringUtils.split(urlString, "/"); listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs") : new ArrayList<DataModel1>(); int2 = array2.length - listObject1.size(); if (int2 > 0) { listObject1.add(new DataModel1(urlString, label1)); } else { int2 += listObject1.size(); for (int1 = listObject1.size() - 1; int1 >= int2; int1--) { listObject1.remove(int1); } } session.put("breadcrumbs", listObject1); } switch (wsType) { case "folder": break; case "reportUnit": try { dateTime1 = new org.joda.time.DateTime(); return1 = INPUT; httpClient1 = new DefaultHttpClient(); if (StringUtils.equals(button1, getText("Print"))) { nameValuePair1 = new ArrayList<NameValuePair>(); if (listObject2 != null) { if (listObject2.size() > 0) { for (DataModel2 dataObject2 : listObject2) { listObject3 = dataObject2.getOptions(); if (listObject3 == null) { string2 = dataObject2.getValue1(); if (StringUtils.isNotBlank(string2)) nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2)); } else { for (int1 = listObject3.size() - 1; int1 >= 0; int1--) { dataModel1 = (DataModel1) listObject3.get(int1); string2 = dataModel1.getString2(); if (StringUtils.isNotBlank(string2)) nameValuePair1 .add(new BasicNameValuePair(dataObject2.getId(), string2)); } } } } } url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); if (StringUtils.isBlank(format1)) format1 = "pdf"; uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1); if (StringUtils.isNotBlank(locale2)) { nameValuePair1.add(new BasicNameValuePair("userLocale", locale2)); } if (StringUtils.isNotBlank(page1)) { if (NumberUtils.isNumber(page1)) { nameValuePair1.add(new BasicNameValuePair("page", page1)); } } if (nameValuePair1.size() > 0) { uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8")); } uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); if (int1 == HttpStatus.SC_OK) { string3 = System.getProperty("java.io.tmpdir") + File.separator + httpServletRequest.getSession().getId(); dir1 = new File(string3); if (!dir1.exists()) { dir1.mkdir(); } httpEntity1 = httpResponse1.getEntity(); file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1); if (StringUtils.equalsIgnoreCase(format1, "html")) { result1 = EntityUtils.toString(httpEntity1); FileUtils.writeStringToFile(file1, result1); array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\""); if (ArrayUtils.isNotEmpty(array1)) { dir1 = new File( string3 + File.separator + FilenameUtils.getBaseName(file1.getName())); if (dir1.exists()) { FileUtils.deleteDirectory(dir1); } file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); if (file2.exists()) { if (FileUtils.deleteQuietly(file2)) { } } for (int2 = 0; int2 < array1.length; int2++) { try { string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/" + StringUtils.substringAfter(array1[int2], "/"); uriBuilder1.setPath(string2); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); } finally { if (int1 == HttpStatus.SC_OK) { try { string2 = StringUtils.substringBeforeLast(array1[int2], "/"); dir1 = new File(string3 + File.separator + string2); if (!dir1.exists()) { dir1.mkdirs(); } httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); } finally { string1 = StringUtils.substringAfterLast(array1[int2], "/"); file2 = new File(string3 + File.separator + string2, string1); outputStream1 = new FileOutputStream(file2); IOUtils.copy(inputStream1, outputStream1); } } } } outputStream1 = new FileOutputStream( FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1); archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName())); IOUtils.copy(new FileInputStream(file1), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName())); files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); for (File file3 : files) { archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils .substringAfter(file3.getCanonicalPath(), string3 + File.separator))); IOUtils.copy(new FileInputStream(file3), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); } archiveOutputStream1.close(); } bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false); string4 = bugfixGateIn ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=", portletRequest.getContextPath(), httpServletRequest.getSession().getId()) : String.format("<img src=\"%s/namespace1/file-link?fileName=", portletRequest.getContextPath()); result1 = StringUtils.replace(result1, "<img src=\"", string4); } else { inputStream1 = httpEntity1.getContent(); outputStream1 = new FileOutputStream(file1); IOUtils.copy(inputStream1, outputStream1); result1 = file1.getAbsolutePath(); } return1 = SUCCESS; } else { addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); } dateTime2 = new org.joda.time.DateTime(); period1 = new Period(dateTime1, dateTime2.plusSeconds(1)); message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1); } else { url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls"); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); switch (int1) { case HttpStatus.SC_NO_CONTENT: break; case HttpStatus.SC_OK: httpEntity1 = httpResponse1.getEntity(); if (httpEntity1 != null) { inputStream1 = httpEntity1.getContent(); if (inputStream1 != null) { xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("inputControl"); if (list1.size() > 0) { listObject2 = new ArrayList<DataModel2>(); for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) { string2 = hierarchicalConfiguration1.getString("type"); dataModel2 = new DataModel2(); dataModel2.setId(hierarchicalConfiguration1.getString("id")); dataModel2.setLabel1(hierarchicalConfiguration1.getString("label")); dataModel2.setType1(string2); dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory")); dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly")); dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible")); switch (string2) { case "bool": case "singleValueText": case "singleValueNumber": case "singleValueDate": case "singleValueDatetime": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); dataModel2.setValue1(hierarchicalConfiguration2.getString("value")); break; case "singleSelect": case "singleSelectRadio": case "multiSelect": case "multiSelectCheckbox": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); list2 = hierarchicalConfiguration2.configurationsAt("options.option"); if (list2.size() > 0) { listObject3 = new ArrayList<DataModel1>(); for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) { dataModel1 = new DataModel1( hierarchicalConfiguration3.getString("label"), hierarchicalConfiguration3.getString("value")); if (hierarchicalConfiguration3.getBoolean("selected")) { dataModel2.setValue1( hierarchicalConfiguration3.getString("value")); } listObject3.add(dataModel1); } dataModel2.setOptions(listObject3); } break; default: break; } listObject2.add(dataModel2); } } } } break; default: addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); break; } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int2 = httpResponse1.getStatusLine().getStatusCode(); if (int2 == HttpStatus.SC_OK) { httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("resourceDescriptor"); for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) { if (StringUtils.equalsIgnoreCase( StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) { if (map1 == null) map1 = new HashMap<String, String>(); string2 = StringUtils.substringBetween( StringUtils.substringAfter( hierarchicalConfiguration4.getString("[@uriString]"), "_files/"), "_", ".properties"); map1.put(string2, StringUtils.isBlank(string2) ? getText("Default") : getText(string2)); } } } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } } } catch (IOException | ConfigurationException | URISyntaxException exception1) { exception1.printStackTrace(); addActionError(exception1.getLocalizedMessage()); httpGet1.abort(); return ERROR; } finally { httpClient1.getConnectionManager().shutdown(); IOUtils.closeQuietly(inputStream1); } break; default: addActionError(getText("This.file.type.is.not.supported")); break; } if (return1 != LOGIN) { sid = new String(Base64.encodeBase64(sid.getBytes())); uid = new String(Base64.encodeBase64(uid.getBytes())); pid = new String(Base64.encodeBase64(pid.getBytes())); } return return1; }
From source file:com.thinkbiganalytics.feedmgr.nifi.NifiFlowCache.java
/** * Ensure that there is a configured reporting task *//*from w ww . j a v a 2 s .c o m*/ private void ensureNiFiKyloReportingTask() { String reportingTaskName = StringUtils.substringAfterLast(NiFiKyloProvenanceEventReportingTaskType, "."); if (!nifiRestClient.getNiFiRestClient().reportingTasks() .findFirstByType(NiFiKyloProvenanceEventReportingTaskType).isPresent()) { log.info("Attempting to create the {} in NiFi ", reportingTaskName); //create it //1 ensure the controller service exists and is wired correctly Optional<ControllerServiceDTO> controllerService = nifiRestClient.getNiFiRestClient().reportingTasks() .findFirstControllerServiceByType(NiFiMetadataControllerServiceType); ControllerServiceDTO metadataService = null; if (controllerService.isPresent()) { metadataService = controllerService.get(); } else { log.info("Attempting to create the Controller Service: {} with the name {} in NiFi ", NiFiMetadataControllerServiceType, NiFiMetadataServiceName); //create it and enable it //first create it ControllerServiceDTO controllerServiceDTO = new ControllerServiceDTO(); controllerServiceDTO.setType(NiFiMetadataControllerServiceType); controllerServiceDTO.setName(NiFiMetadataServiceName); metadataService = nifiRestClient.getNiFiRestClient().reportingTasks() .createReportingTaskControllerService(controllerServiceDTO); //find the properties to inject Map<String, Object> configProperties = propertyExpressionResolver.getStaticConfigProperties(); Map<String, String> stringConfigProperties = new HashMap<>(); if (configProperties != null) { //transform the object map to the String map stringConfigProperties = configProperties.entrySet().stream().collect(Collectors .toMap(Map.Entry::getKey, e -> e.getValue() != null ? e.getValue().toString() : null)); } metadataService = nifiRestClient.enableControllerServiceAndSetProperties(metadataService.getId(), stringConfigProperties); } if (metadataService != null) { try { if (NifiProcessUtil.SERVICE_STATE.DISABLED.name() .equalsIgnoreCase(metadataService.getState())) { log.info("Reporting Task Controller Service {} exists, ensuring it is enabled.", NiFiMetadataServiceName); //enable it.... metadataService = nifiRestClient .enableControllerServiceAndSetProperties(metadataService.getId(), null); } } catch (NifiClientRuntimeException e) { //swallow the exception and attempt to move on to create the task } log.info("Creating the Reporting Task {} ", reportingTaskName); ReportingTaskDTO reportingTaskDTO = new ReportingTaskDTO(); reportingTaskDTO.setType(NiFiKyloProvenanceEventReportingTaskType); reportingTaskDTO = nifiRestClient.getNiFiRestClient().reportingTasks() .createReportingTask(reportingTaskDTO); //now set the properties ReportingTaskDTO updatedReportingTask = new ReportingTaskDTO(); updatedReportingTask.setType(NiFiKyloProvenanceEventReportingTaskType); updatedReportingTask.setId(reportingTaskDTO.getId()); updatedReportingTask.setName(reportingTaskName); updatedReportingTask.setProperties(new HashMap<>(1)); updatedReportingTask.getProperties().put("Metadata Service", metadataService.getId()); updatedReportingTask.setSchedulingStrategy("TIMER_DRIVEN"); updatedReportingTask.setSchedulingPeriod("5 secs"); updatedReportingTask.setComments( "Reporting task that will query the provenance repository and send the events and summary statistics over to Kylo via a JMS queue"); updatedReportingTask.setState(NifiProcessUtil.PROCESS_STATE.RUNNING.name()); //update it reportingTaskDTO = nifiRestClient.getNiFiRestClient().reportingTasks().update(updatedReportingTask); if (reportingTaskDTO != null) { log.info("Successfully created the Reporting Task {} ", reportingTaskName); } else { log.info("Error creating the Reporting Task {}. You will need to go into NiFi to resolve. ", reportingTaskName); } } } ; }
From source file:de.blizzy.documentr.web.page.PageController.java
@RequestMapping(value = "/relocate/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:" + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{path:" + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}", method = RequestMethod.POST) @PreAuthorize("hasBranchPermission(#projectName, #branchName, EDIT_PAGE)") public String relocatePage(@PathVariable String projectName, @PathVariable String branchName, @PathVariable String path, @RequestParam String newParentPagePath, Authentication authentication) throws IOException { path = Util.toRealPagePath(path); newParentPagePath = Util.toRealPagePath(newParentPagePath); User user = userStore.getUser(authentication.getName()); pageStore.relocatePage(projectName, branchName, path, newParentPagePath, user); String pageName = path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path; //$NON-NLS-1$ //$NON-NLS-2$ return "redirect:/page/" + projectName + "/" + branchName + //$NON-NLS-1$ //$NON-NLS-2$ "/" + Util.toUrlPagePath(newParentPagePath + "/" + pageName); //$NON-NLS-1$ //$NON-NLS-2$ }
From source file:com.thinkbiganalytics.feedmgr.sla.DefaultServiceLevelAgreementService.java
/** * In order to Save an SLA if it is related to a Feed(s) the user needs to have EDIT_DETAILS permission on the Feed(s) * * @param serviceLevelAgreement the sla to save * @param feed an option Feed to relate to this SLA. If this is not present the related feeds are also embedded in the SLA policies. The Feed is a pointer access to the current * feed the user is editing if they are creating an SLA from the Feed Details page. If creating an SLA from the main SLA page the feed property will not be populated. *///from w w w .j a va 2 s. c om private ServiceLevelAgreement saveAndScheduleSla(ServiceLevelAgreementGroup serviceLevelAgreement, FeedMetadata feed) { //ensure user has permissions to edit the SLA if (serviceLevelAgreement != null) { ServiceLevelAgreementMetricTransformerHelper transformer = new ServiceLevelAgreementMetricTransformerHelper(); //Read the feeds on the SLA as a Service. Then verify the current user has access to edit these feeds List<String> feedsOnSla = metadataAccess.read(() -> { List<String> feedIds = new ArrayList<>(); //all referencing Feeds List<String> systemCategoryAndFeedNames = transformer.getCategoryFeedNames(serviceLevelAgreement); for (String categoryAndFeed : systemCategoryAndFeedNames) { //fetch and update the reference to the sla String categoryName = StringUtils.trim(StringUtils.substringBefore(categoryAndFeed, ".")); String feedName = StringUtils.trim(StringUtils.substringAfterLast(categoryAndFeed, ".")); Feed feedEntity = feedProvider.findBySystemName(categoryName, feedName); if (feedEntity != null) { feedIds.add(feedEntity.getId().toString()); } } return feedIds; }, MetadataAccess.SERVICE); boolean allowedToEdit = feedsOnSla.isEmpty() ? true : feedsOnSla.stream().allMatch(feedId -> feedManagerFeedService.checkFeedPermission(feedId, FeedAccessControl.EDIT_DETAILS)); if (allowedToEdit) { return metadataAccess.commit(() -> { //Re read back in the Feeds for this session Set<Feed> slaFeeds = new HashSet<Feed>(); Set<Feed.ID> slaFeedIds = new HashSet<Feed.ID>(); feedsOnSla.stream().forEach(feedId -> { Feed feedEntity = feedProvider.findById(feedProvider.resolveId(feedId)); if (feedEntity != null) { slaFeeds.add(feedEntity); slaFeedIds.add(feedEntity.getId()); } }); if (feed != null) { feedManagerFeedService.checkFeedPermission(feed.getId(), FeedAccessControl.EDIT_DETAILS); } if (feed != null) { transformer.applyFeedNameToCurrentFeedProperties(serviceLevelAgreement, feed.getCategory().getSystemName(), feed.getSystemFeedName()); } ServiceLevelAgreement sla = transformer.getServiceLevelAgreement(serviceLevelAgreement); ServiceLevelAgreementBuilder slaBuilder = null; com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement.ID existingId = null; if (StringUtils.isNotBlank(sla.getId())) { existingId = slaProvider.resolve(sla.getId()); } if (existingId != null) { slaBuilder = slaProvider.builder(existingId); } else { slaBuilder = slaProvider.builder(); } slaBuilder.name(sla.getName()).description(sla.getDescription()); for (com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup group : sla.getGroups()) { ObligationGroupBuilder groupBuilder = slaBuilder .obligationGroupBuilder(ObligationGroup.Condition.valueOf(group.getCondition())); for (Obligation o : group.getObligations()) { groupBuilder.obligationBuilder().metric(o.getMetrics()).description(o.getDescription()) .build(); } groupBuilder.build(); } com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement savedSla = slaBuilder.build(); List<ServiceLevelAgreementActionConfiguration> actions = transformer .getActionConfigurations(serviceLevelAgreement); // now assign the sla checks slaProvider.slaCheckBuilder(savedSla.getId()).removeSlaChecks().actionConfigurations(actions) .build(); if (feed != null) { Feed.ID feedId = feedProvider.resolveFeed(feed.getFeedId()); if (!slaFeedIds.contains(feedId)) { Feed feedEntity = feedProvider.getFeed(feedId); slaFeeds.add(feedEntity); } } //relate them Set<Feed.ID> feedIds = new HashSet<>(); FeedServiceLevelAgreementRelationship feedServiceLevelAgreementRelationship = feedSlaProvider .relateFeeds(savedSla, slaFeeds); if (feedServiceLevelAgreementRelationship != null && feedServiceLevelAgreementRelationship.getFeeds() != null) { feedIds = feedServiceLevelAgreementRelationship.getFeeds().stream().map(f -> f.getId()) .collect(Collectors.toSet()); } //Update the JPA mapping in Ops Manager for this SLA and its related Feeds serviceLevelAgreementDescriptionProvider.updateServiceLevelAgreement(savedSla.getId(), savedSla.getName(), savedSla.getDescription(), feedIds); com.thinkbiganalytics.metadata.rest.model.sla.FeedServiceLevelAgreement restModel = serviceLevelAgreementTransform .toModel(savedSla, slaFeeds, true); //schedule it serviceLevelAgreementScheduler.scheduleServiceLevelAgreement(savedSla); return restModel; }); } } return null; }
From source file:io.cloudex.cloud.impl.google.GoogleCloudServiceImpl.java
/** * Upload the provided file into cloud storage * THis is what Google returns:/*from w w w . j a va2s . c o m*/ * <pre> * CONFIG: { "kind": "storage#object", "id": "ecarf/umbel_links.nt_out.gz/1397227987451000", "selfLink": "https://www.googleapis.com/storage/v1beta2/b/ecarf/o/umbel_links.nt_out.gz", "name": "umbel_links.nt_out.gz", "bucket": "ecarf", "generation": "1397227987451000", "metageneration": "1", "contentType": "application/x-gzip", "updated": "2014-04-11T14:53:07.339Z", "storageClass": "STANDARD", "size": "8474390", "md5Hash": "UPhXcZZGbD9198OhQcdnvQ==", "owner": { "entity": "user-00b4903a97e56638621f0643dc282444442a11b19141d3c7b425c4d17895dcf6", "entityId": "00b4903a97e56638621f0643dc282444442a11b19141d3c7b425c4d17895dcf6" }, "crc32c": "3twYkA==", "etag": "CPj48u7X2L0CEAE=" } </pre> * @param filename * @param bucket * @throws IOException */ @Override public io.cloudex.framework.cloud.entities.StorageObject uploadFileToCloudStorage(String filename, String bucket, Callback callback) throws IOException { FileInputStream fileStream = new FileInputStream(filename); String contentType; boolean gzipDisabled; if (GzipUtils.isCompressedFilename(filename)) { contentType = Constants.GZIP_CONTENT_TYPE; gzipDisabled = true; } else { contentType = Files.probeContentType((new File(filename)).toPath()); if (contentType == null) { contentType = Constants.BINARY_CONTENT_TYPE; } gzipDisabled = false; } InputStreamContent mediaContent = new InputStreamContent(contentType, fileStream); // Not strictly necessary, but allows optimization in the cloud. mediaContent.setLength(fileStream.available()); Storage.Objects.Insert insertObject = getStorage().objects() .insert(bucket, new StorageObject().setName( StringUtils.substringAfterLast(filename, FileUtils.PATH_SEPARATOR)), mediaContent) .setOauthToken(this.getOAuthToken()); insertObject.getMediaHttpUploader().setProgressListener(new UploadProgressListener(callback)) .setDisableGZipContent(gzipDisabled); // For small files, you may wish to call setDirectUploadEnabled(true), to // reduce the number of HTTP requests made to the server. if (mediaContent.getLength() > 0 && mediaContent.getLength() <= 4 * FileUtils.ONE_MB /* 2MB */) { insertObject.getMediaHttpUploader().setDirectUploadEnabled(true); } StorageObject object = null; try { object = insertObject.execute(); } catch (IOException e) { log.error("Error whilst uploading file", e); ApiUtils.block(5); // try again object = insertObject.execute(); } return this.getCloudExStorageObject(object, bucket); }
From source file:com.xpn.xwiki.objects.BaseCollection.java
public List<ObjectDiff> getDiff(Object oldObject, XWikiContext context) { ArrayList<ObjectDiff> difflist = new ArrayList<ObjectDiff>(); BaseCollection oldCollection = (BaseCollection) oldObject; // Iterate over the new properties first, to handle changed and added objects for (Object key : this.getFields().keySet()) { String propertyName = (String) key; BaseProperty newProperty = (BaseProperty) this.getFields().get(propertyName); BaseProperty oldProperty = (BaseProperty) oldCollection.getFields().get(propertyName); BaseClass bclass = getXClass(context); PropertyClass pclass = (PropertyClass) ((bclass == null) ? null : bclass.getField(propertyName)); String propertyType = (pclass == null) ? "" : StringUtils.substringAfterLast(pclass.getClassType(), "."); if (oldProperty == null) { // The property exist in the new object, but not in the old one if ((newProperty != null) && (!newProperty.toText().equals(""))) { if (pclass != null) { String newPropertyValue = (newProperty.getValue() instanceof String) ? newProperty.toText() : pclass.displayView(propertyName, this, context); difflist.add(new ObjectDiff(getXClassReference(), getNumber(), "", ObjectDiff.ACTION_PROPERTYADDED, propertyName, propertyType, "", newPropertyValue)); }/*from www . jav a 2 s. c om*/ } } else if (!oldProperty.toText().equals(((newProperty == null) ? "" : newProperty.toText()))) { // The property exists in both objects and is different if (pclass != null) { // Put the values as they would be displayed in the interface String newPropertyValue = (newProperty.getValue() instanceof String) ? newProperty.toText() : pclass.displayView(propertyName, this, context); String oldPropertyValue = (oldProperty.getValue() instanceof String) ? oldProperty.toText() : pclass.displayView(propertyName, oldCollection, context); difflist.add( new ObjectDiff(getXClassReference(), getNumber(), "", ObjectDiff.ACTION_PROPERTYCHANGED, propertyName, propertyType, oldPropertyValue, newPropertyValue)); } else { // Cannot get property definition, so use the plain value difflist.add( new ObjectDiff(getXClassReference(), getNumber(), "", ObjectDiff.ACTION_PROPERTYCHANGED, propertyName, propertyType, oldProperty.toText(), newProperty.toText())); } } } // Iterate over the old properties, in case there are some removed properties for (Object key : oldCollection.getFields().keySet()) { String propertyName = (String) key; BaseProperty newProperty = (BaseProperty) this.getFields().get(propertyName); BaseProperty oldProperty = (BaseProperty) oldCollection.getFields().get(propertyName); BaseClass bclass = getXClass(context); PropertyClass pclass = (PropertyClass) ((bclass == null) ? null : bclass.getField(propertyName)); String propertyType = (pclass == null) ? "" : StringUtils.substringAfterLast(pclass.getClassType(), "."); if (newProperty == null) { // The property exists in the old object, but not in the new one if ((oldProperty != null) && (!oldProperty.toText().equals(""))) { if (pclass != null) { // Put the values as they would be displayed in the interface String oldPropertyValue = (oldProperty.getValue() instanceof String) ? oldProperty.toText() : pclass.displayView(propertyName, oldCollection, context); difflist.add(new ObjectDiff(oldCollection.getXClassReference(), oldCollection.getNumber(), "", ObjectDiff.ACTION_PROPERTYREMOVED, propertyName, propertyType, oldPropertyValue, "")); } else { // Cannot get property definition, so use the plain value difflist.add(new ObjectDiff(oldCollection.getXClassReference(), oldCollection.getNumber(), "", ObjectDiff.ACTION_PROPERTYREMOVED, propertyName, propertyType, oldProperty.toText(), "")); } } } } return difflist; }
From source file:com.zht.common.codegen.util.UIEasyStrUtil.java
public static void handlerProperty_Boolean(GenEntityProperty prop) { String entityClazzName = prop.getGenEntity().getName(); if (entityClazzName != null && entityClazzName.contains(".")) { entityClazzName = StringUtils.substringAfterLast(entityClazzName, "."); entityClazzName = ZStrUtil.toLowerCaseFirst(entityClazzName); }//from w ww . j a v a 2 s . c o m StringBuffer editStr = new StringBuffer(""); StringBuffer queryStr = new StringBuffer(""); StringBuffer displayStr = new StringBuffer(""); String editType = prop.getEditType(); if ("select".equals(editType)) { String data_options = " "; editStr = new StringBuffer("\r\t<select name=\"" + prop.getPropertyName() + "\" class=\"easyui-combobox\" style=\"width: 170px;\" "); if (prop.getNullable() != null && prop.getNullable() == false) { data_options += "required:true"; editStr.append(" data-options=\"" + data_options + "\""); } editStr.append(">").append("\r\t"); String con = prop.getEditContent(); if (con != null && con.length() > 0) { con = con.trim().replace("{", ""); String[] oneEContent = con.split("}"); if (oneEContent != null && oneEContent.length == 2) { for (String str : oneEContent) { String[] content = str.split("-"); String value = content[0].trim(); String display = content[1].trim(); editStr.append("<option value=\"" + value + "\" <c:if test=\"${" + entityClazzName + "." + prop.getPropertyName() + " eq " + value + " }\">selected='selected' </c:if> >" + display + "</option>").append("\r\t"); } } } editStr.append("</select>"); queryStr.append(editStr.toString().replace(" data-options=\"" + data_options + "\"", " ").replace( "name=\"" + prop.getPropertyName() + "\"", " name=\"webParams[" + prop.getPropertyName() + "]\" ")); editStr.append("\r\t"); queryStr.append("\r\t"); if (prop.getIsQueryCondtion()) { prop.setGeneratedQueryOfPropertyStr(queryStr.toString()); } prop.setGeneratedEditOfPropertyStr(editStr.toString()); displayStr.append("{field:'" + prop.getPropertyName() + "',title:'" + prop.getDisplay() + "',width:" + prop.getColumnWidth() + ","); String simpleFormat = prop.getSimpleFormat(); if (simpleFormat != null && simpleFormat.length() > 0) { displayStr.append(simpleFormat); } displayStr.append("},"); prop.setGeneratedListDisplayOfPropertyStr(displayStr.toString()); } }
From source file:com.simpligility.maven.plugins.android.AbstractEmulatorMojo.java
/** * This method extracts a port number from the serial number of a device. * It assumes that the device name is of format [xxxx-nnnn] where nnnn is the * port number./* w ww. ja v a 2 s .c om*/ * * @param device The device to extract the port number from. * @return Returns the port number of the device */ private int extractPortFromDevice(IDevice device) { String portStr = StringUtils.substringAfterLast(device.getSerialNumber(), "-"); if (StringUtils.isNotBlank(portStr) && StringUtils.isNumeric(portStr)) { return Integer.parseInt(portStr); } //If the port is not available then return -1 return -1; }