List of usage examples for org.apache.commons.lang StringUtils defaultIfBlank
public static String defaultIfBlank(String str, String defaultStr)
Returns either the passed in String, or if the String is whitespace, empty ("") or null
, the value of defaultStr
.
From source file:org.ngrinder.perftest.service.PerfTestService.java
/** * Create {@link GrinderProperties} based on the passed {@link PerfTest}. * * @param perfTest base data// w w w .jav a 2 s. c o m * @param scriptHandler scriptHandler * @return created {@link GrinderProperties} instance */ public GrinderProperties getGrinderProperties(PerfTest perfTest, ScriptHandler scriptHandler) { try { // Use default properties first GrinderProperties grinderProperties = new GrinderProperties( config.getHome().getDefaultGrinderProperties()); User user = perfTest.getCreatedUser(); // Get all files in the script path String scriptName = perfTest.getScriptName(); FileEntry userDefinedGrinderProperties = fileEntryService.getOne(user, FilenameUtils.concat(FilenameUtils.getPath(scriptName), DEFAULT_GRINDER_PROPERTIES), -1L); if (!config.isSecurityEnabled() && userDefinedGrinderProperties != null) { // Make the property overridden by user property. GrinderProperties userProperties = new GrinderProperties(); userProperties.load(new StringReader(userDefinedGrinderProperties.getContent())); grinderProperties.putAll(userProperties); } grinderProperties.setAssociatedFile(new File(DEFAULT_GRINDER_PROPERTIES)); grinderProperties.setProperty(GRINDER_PROP_SCRIPT, scriptHandler.getScriptExecutePath(scriptName)); grinderProperties.setProperty(GRINDER_PROP_TEST_ID, "test_" + perfTest.getId()); grinderProperties.setInt(GRINDER_PROP_AGENTS, getSafe(perfTest.getAgentCount())); grinderProperties.setInt(GRINDER_PROP_PROCESSES, getSafe(perfTest.getProcesses())); grinderProperties.setInt(GRINDER_PROP_THREAD, getSafe(perfTest.getThreads())); if (perfTest.isThresholdDuration()) { grinderProperties.setLong(GRINDER_PROP_DURATION, getSafe(perfTest.getDuration())); grinderProperties.setInt(GRINDER_PROP_RUNS, 0); } else { grinderProperties.setInt(GRINDER_PROP_RUNS, getSafe(perfTest.getRunCount())); if (grinderProperties.containsKey(GRINDER_PROP_DURATION)) { grinderProperties.remove(GRINDER_PROP_DURATION); } } grinderProperties.setProperty(GRINDER_PROP_ETC_HOSTS, StringUtils.defaultIfBlank(perfTest.getTargetHosts(), "")); grinderProperties.setBoolean(GRINDER_PROP_USE_CONSOLE, true); if (BooleanUtils.isTrue(perfTest.getUseRampUp())) { grinderProperties.setBoolean(GRINDER_PROP_THREAD_RAMPUP, perfTest.getRampUpType() == RampUp.THREAD); grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, getSafe(perfTest.getRampUpStep())); grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT_INTERVAL, getSafe(perfTest.getRampUpIncrementInterval())); if (perfTest.getRampUpType() == RampUp.PROCESS) { grinderProperties.setInt(GRINDER_PROP_INITIAL_SLEEP_TIME, getSafe(perfTest.getRampUpInitSleepTime())); } else { grinderProperties.setInt(GRINDER_PROP_INITIAL_THREAD_SLEEP_TIME, getSafe(perfTest.getRampUpInitSleepTime())); } grinderProperties.setInt(GRINDER_PROP_INITIAL_PROCESS, getSafe(perfTest.getRampUpInitCount())); } else { grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, 0); } grinderProperties.setInt(GRINDER_PROP_REPORT_TO_CONSOLE, 500); grinderProperties.setProperty(GRINDER_PROP_USER, perfTest.getCreatedUser().getUserId()); grinderProperties.setProperty(GRINDER_PROP_JVM_CLASSPATH, getCustomClassPath(perfTest)); grinderProperties.setInt(GRINDER_PROP_IGNORE_SAMPLE_COUNT, getSafe(perfTest.getIgnoreSampleCount())); grinderProperties.setBoolean(GRINDER_PROP_SECURITY, config.isSecurityEnabled()); // For backward agent compatibility. // If the security is not enabled, pass it as jvm argument. // If enabled, pass it to grinder.param. In this case, I drop the // compatibility. if (StringUtils.isNotBlank(perfTest.getParam())) { String param = perfTest.getParam().replace("'", "\\'").replace(" ", ""); if (config.isSecurityEnabled()) { grinderProperties.setProperty(GRINDER_PROP_PARAM, StringUtils.trimToEmpty(param)); } else { String property = grinderProperties.getProperty(GRINDER_PROP_JVM_ARGUMENTS, ""); property = property + " -Dparam=" + param + " "; grinderProperties.setProperty(GRINDER_PROP_JVM_ARGUMENTS, property); } } LOGGER.info("Grinder Properties : {} ", grinderProperties); return grinderProperties; } catch (Exception e) { throw processException("error while prepare grinder property for " + perfTest.getTestName(), e); } }
From source file:org.ngrinder.script.controller.FileEntryController.java
/** * Provide new file creation form data.// w w w. j a v a 2 s. c o m * * @param user current user * @param path path in which a file will be added * @param testUrl url which the script may use * @param fileName fileName * @param scriptType Type of script. optional * @param createLibAndResources true if libs and resources should be created as well. * @param redirectAttributes redirect attributes storage * @param model model. * @return script/editor" */ @RequestMapping(value = "/new/**", params = "type=script", method = RequestMethod.POST) public String createForm(User user, @RemainedPath String path, @RequestParam(value = "testUrl", required = false) String testUrl, @RequestParam("fileName") String fileName, @RequestParam(value = "scriptType", required = false) String scriptType, @RequestParam(value = "createLibAndResource", defaultValue = "false") boolean createLibAndResources, @RequestParam(value = "options", required = false) String options, RedirectAttributes redirectAttributes, ModelMap model) { fileName = StringUtils.trimToEmpty(fileName); String name = "Test1"; if (StringUtils.isEmpty(testUrl)) { testUrl = StringUtils.defaultIfBlank(testUrl, "http://please_modify_this.com"); } else { name = UrlUtils.getHost(testUrl); } ScriptHandler scriptHandler = fileEntryService.getScriptHandler(scriptType); FileEntry entry = new FileEntry(); entry.setPath(fileName); if (scriptHandler instanceof ProjectHandler) { if (!fileEntryService.hasFileEntry(user, PathUtils.join(path, fileName))) { fileEntryService.prepareNewEntry(user, path, fileName, name, testUrl, scriptHandler, createLibAndResources, options); redirectAttributes.addFlashAttribute("message", fileName + " project is created."); return "redirect:/script/list/" + path + "/" + fileName; } else { redirectAttributes.addFlashAttribute("exception", fileName + " is already existing. Please choose the different name"); return "redirect:/script/list/" + path + "/"; } } else { String fullPath = PathUtils.join(path, fileName); if (fileEntryService.hasFileEntry(user, fullPath)) { model.addAttribute("file", fileEntryService.getOne(user, fullPath)); } else { model.addAttribute("file", fileEntryService.prepareNewEntry(user, path, fileName, name, testUrl, scriptHandler, createLibAndResources, options)); } } model.addAttribute("breadcrumbPath", getScriptPathBreadcrumbs(PathUtils.join(path, fileName))); model.addAttribute("scriptHandler", scriptHandler); model.addAttribute("createLibAndResource", createLibAndResources); return "script/editor"; }
From source file:org.ngrinder.script.service.ScriptValidationService.java
@Override public String validate(User user, IFileEntry scriptIEntry, boolean useScriptInSVN, String hostString) { FileEntry scriptEntry = cast(scriptIEntry); try {/*from w w w .j ava2 s . c o m*/ checkNotNull(scriptEntry, "scriptEntity should be not null"); checkNotEmpty(scriptEntry.getPath(), "scriptEntity path should be provided"); if (!useScriptInSVN) { checkNotEmpty(scriptEntry.getContent(), "scriptEntity content should be provided"); } checkNotNull(user, "user should be provided"); // String result = checkSyntaxErrors(scriptEntry.getContent()); ScriptHandler handler = scriptHandlerFactory.getHandler(scriptEntry); if (config.getControllerProperties().getPropertyBoolean(PROP_CONTROLLER_VALIDATION_SYNTAX_CHECK)) { String result = handler.checkSyntaxErrors(scriptEntry.getPath(), scriptEntry.getContent()); LOGGER.info("Perform Syntax Check by {} for {}", user.getUserId(), scriptEntry.getPath()); if (result != null) { return result; } } File scriptDirectory = config.getHome().getScriptDirectory(user); FileUtils.deleteDirectory(scriptDirectory); Preconditions.checkTrue(scriptDirectory.mkdirs(), "Script directory {} creation is failed."); ProcessingResultPrintStream processingResult = new ProcessingResultPrintStream( new ByteArrayOutputStream()); handler.prepareDist(0L, user, scriptEntry, scriptDirectory, config.getControllerProperties(), processingResult); if (!processingResult.isSuccess()) { return new String(processingResult.getLogByteArray()); } File scriptFile = new File(scriptDirectory, FilenameUtils.getName(scriptEntry.getPath())); if (useScriptInSVN) { fileEntryService.writeContentTo(user, scriptEntry.getPath(), scriptDirectory); } else { FileUtils.writeStringToFile(scriptFile, scriptEntry.getContent(), StringUtils.defaultIfBlank(scriptEntry.getEncoding(), "UTF-8")); } File doValidate = localScriptTestDriveService.doValidate(scriptDirectory, scriptFile, new Condition(), config.isSecurityEnabled(), hostString, getTimeout()); List<String> readLines = FileUtils.readLines(doValidate); StringBuilder output = new StringBuilder(); String path = config.getHome().getDirectory().getAbsolutePath(); for (String each : readLines) { if (!each.startsWith("*sys-package-mgr")) { each = each.replace(path, "${NGRINDER_HOME}"); output.append(each).append("\n"); } } return output.toString(); } catch (Exception e) { throw processException(e); } }
From source file:org.ngrinder.security.SvnHttpBasicEntryPoint.java
@Override public void commence(HttpServletRequest request, HttpServletResponse response, // LB AuthenticationException authException) throws IOException, ServletException { // Get the first part of url path and use it as a realm. String pathInfo = request.getPathInfo(); String[] split = StringUtils.split(pathInfo, '/'); response.addHeader("WWW-Authenticate", "Basic realm=\"" + StringUtils.defaultIfBlank(split[0], "admin") + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); }
From source file:org.ngrinder.user.controller.UserController.java
/** * Switch user identity.//from ww w .j a v a2 s. c om * * @param model model * @param to the user to whom a user will switch * @param response response * @return redirect:/perftest/ */ @RequestMapping("/switch") public String switchUser(@RequestParam(required = false, defaultValue = "") String to, HttpServletRequest request, HttpServletResponse response, ModelMap model) { Cookie cookie = new Cookie("switchUser", to); cookie.setPath("/"); // Delete Cookie if empty switchUser if (StringUtils.isEmpty(to)) { cookie.setMaxAge(0); } response.addCookie(cookie); model.clear(); final String referer = request.getHeader("referer"); return "redirect:" + StringUtils.defaultIfBlank(referer, "/"); }
From source file:org.niord.core.ChartConverter.java
public static void main(String[] args) throws IOException { String csvPath = "/Users/carolus/Downloads/charts.csv"; String resultPath = "/Users/carolus/Downloads/charts.json"; List<SystemChartVo> charts = new ArrayList<>(); Files.readAllLines(Paths.get(csvPath), Charset.forName("UTF-8")).forEach(line -> { String[] fields = line.split(";"); SystemChartVo chart = new SystemChartVo(); chart.setChartNumber(fields[0].split(" ")[1].trim()); if (StringUtils.isNotBlank(fields[1]) && StringUtils.isNumeric(fields[1])) { chart.setInternationalNumber(Integer.valueOf(fields[1])); }//from w ww .ja va 2 s.c o m chart.setName(StringUtils.defaultIfBlank(fields[3], "")); if (StringUtils.isNotBlank(fields[4]) && StringUtils.isNumeric(fields[4])) { chart.setScale(Integer.valueOf(fields[4])); } if (!"Ukendt / Unknown".equals(fields[5])) { chart.setHorizontalDatum(StringUtils.defaultIfBlank(fields[5], "")); } Double south = parsePos(fields[6]); Double west = -parsePos(fields[7]); Double north = parsePos(fields[8]); Double east = -parsePos(fields[9]); double[][] coords = new double[][] { { east, north }, { east, south }, { west, south }, { west, north }, { east, north }, }; PolygonVo geometry = new PolygonVo(); geometry.setCoordinates(new double[][][] { coords }); GeoJsonUtils.roundCoordinates(geometry, 8); chart.setGeometry(geometry); charts.add(chart); }); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(charts)); try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(resultPath), StandardCharsets.UTF_8)) { //writer.write("\uFEFF"); writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(charts)); } }
From source file:org.niord.core.geojson.GeoJsonUtils.java
/** * Serializes the GeoJSON of the feature collection into a flat list of coordinates for each feature. * The list of coordinates can e.g. be used to present for an end-user, rather than the underlying GeoJSON. * <p>/* w w w . j a v a 2s . c o m*/ * Each feature and each coordinate of each feature may have a localized name as stored in the * feature properties according to the {@linkplain FeatureName} conventions. * <p> * When serializing coordinates, adhere to a couple of rules: * <ul> * <li>If the "parentFeatureIds" feature property is defined, skip the coordinates.</li> * <li>If the "restriction" feature property has the value "affected", skip the coordinates.</li> * <li>For polygon linear rings, skip the last coordinate (which is identical to the first).</li> * <li>For (multi-)polygons, only include the exterior ring, not the interior ring.</li> * </ul> * <p> * This implementation should be kept in sync with the {@code MapService.serializeCoordinates()} JavaScript function. * * @param fc the feature collection to serialize * @param language the language * @return the serialized coordinates */ public static List<SerializedFeature> serializeFeatureCollection(FeatureCollectionVo fc, String language) { List<SerializedFeature> result = new ArrayList<>(); if (fc != null) { int startIndex = 1; for (FeatureVo feature : fc.getFeatures()) { if (feature.getProperties().containsKey("parentFeatureIds") || "affected".equals(feature.getProperties().get("restriction"))) { continue; } // If no language param is defined, check if the feature defines a "language" property. Default to "en" String featureLang = (String) feature.getProperties().get("language"); String lang = StringUtils.isBlank(language) ? StringUtils.defaultIfBlank(featureLang, "en") : language; // Check if the feature contains a "startCoordIndex" property that overrides our computed index Number startCoordIndex = (Number) feature.getProperties().get("startCoordIndex"); startIndex = startCoordIndex != null ? startCoordIndex.intValue() : startIndex; SerializedFeature sf = new SerializedFeature(); sf.setName(FeatureName.getFeatureName(feature.getProperties(), lang)); serializeGeometry(feature.getGeometry(), sf, feature.getProperties(), lang, new AtomicInteger(0)); if (StringUtils.isNotBlank(sf.getName()) || !sf.getCoordinates().isEmpty()) { result.add(sf); // Update the start indexes if the coordinates sf.setStartIndex(startIndex); for (SerializedCoordinates coord : sf.getCoordinates()) { coord.setIndex(startIndex++); } } } } return result; }
From source file:org.niord.core.mail.CachedUrlDataSource.java
/** {@inheritDoc} */ @Override public String getContentType() { return StringUtils.defaultIfBlank(loadData().getContentType(), DEFAULT_CONTENT_TYPE); }
From source file:org.niord.core.mail.CachedUrlDataSource.java
/** {@inheritDoc} */ @Override public String getName() { return StringUtils.defaultIfBlank(loadData().getName(), DEFAULT_NAME); }
From source file:org.niord.core.message.MessageMailService.java
/** * Generates an email from the given mail template * @param mailTemplate the message mail template *///from ww w .j a va 2s . co m public void sendMessageMail(MessageMailTemplate mailTemplate) throws Exception { if (mailTemplate.getRecipients().isEmpty()) { throw new Exception("No mail recipient specified"); } long t0 = System.currentTimeMillis(); String mailSubject = StringUtils.defaultIfBlank(mailTemplate.getSubject(), "No subject"); String mailMessage = StringUtils.defaultIfBlank(mailTemplate.getMailMessage(), ""); User user = userService.currentUser(); for (MailRecipient recipient : mailTemplate.getRecipients()) { try { String mailTo = recipient.getAddress().toString(); if (recipient.getAddress() instanceof InternetAddress) { mailTo = StringUtils.defaultIfBlank(((InternetAddress) recipient.getAddress()).getPersonal(), mailTo); } String mailContents = templateService.newTemplateBuilder() .templatePath(mailTemplate.getTemplatePath()).data("messages", mailTemplate.getMessages()) .data("areaHeadings", false).data("mailTo", mailTo).data("mailMessage", mailMessage) .data("mailSender", user.getName()).data("mapThumbnails", false).data("frontPage", false) .data("link", true).dictionaryNames("message", "mail").language(mailTemplate.getLanguage()) .process(); ScheduledMail scheduledMail = new ScheduledMail(); scheduledMail.setSubject(mailSubject); scheduledMail.setHtmlContents(mailContents); scheduledMail.addRecipient( new ScheduledMailRecipient(RecipientType.TO, recipient.getAddress().toString())); scheduledMail.setSender(user.getInternetAddress()); saveEntity(scheduledMail); String msg = "Mail scheduled to " + mailTo + " in " + (System.currentTimeMillis() - t0) + " ms"; log.info(msg); } catch (Exception e) { log.error("Error generating PDF for messages", e); throw e; } } }