List of usage examples for org.apache.commons.lang3 StringUtils defaultString
public static String defaultString(final String str)
Returns either the passed in String, or if the String is null , an empty String ("").
StringUtils.defaultString(null) = "" StringUtils.defaultString("") = "" StringUtils.defaultString("bat") = "bat"
From source file:com.raddle.tools.ClipboardTransferMain.java
public ClipboardTransferMain() { super();/* ww w.ja v a2 s . c o m*/ initGUI(); //// ?? Properties p = new Properties(); File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties"); if (pf.exists()) { try { p.load(new FileInputStream(pf)); serverAddrTxt.setText(StringUtils.defaultString(p.getProperty("server.addr"))); portTxt.setText(StringUtils.defaultString(p.getProperty("local.port"))); modifyClipChk.setSelected("true".equals(p.getProperty("allow.modify.local.clip"))); autoChk.setSelected("true".equals(p.getProperty("auto.modify.remote.clip"))); } catch (Exception e) { updateMessage(e.getMessage()); } } m.addListener(new ClipboardListener() { @Override public void contentChanged(Clipboard clipboard) { setRemoteClipboard(false); } }); m.setEnabled(autoChk.isSelected()); // try { pasteImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_paste.png")); grayImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_gray.png")); sendImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/mail-send.png")); BufferedImage taskImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/taskbar.png")); setIconImage(taskImage); SystemTray systemTray = SystemTray.getSystemTray(); trayIcon = new TrayIcon(grayImage, "??"); systemTray.add(trayIcon); //// trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) {// ??? if (ClipboardTransferMain.this.isVisible()) { ClipboardTransferMain.this.setState(ICONIFIED); } else { ClipboardTransferMain.this.setVisible(true); ClipboardTransferMain.this.setState(NORMAL); } } } }); ////// event this.addWindowListener(new WindowAdapter() { @Override public void windowIconified(WindowEvent e) { ClipboardTransferMain.this.setVisible(false); super.windowIconified(e); } @Override public void windowClosing(WindowEvent e) { File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties"); pf.getParentFile().mkdirs(); try { Properties op = new Properties(); op.setProperty("server.addr", serverAddrTxt.getText()); op.setProperty("local.port", portTxt.getText()); op.setProperty("allow.modify.local.clip", modifyClipChk.isSelected() + ""); op.setProperty("auto.modify.remote.clip", autoChk.isSelected() + ""); FileOutputStream os = new FileOutputStream(pf); op.store(os, "clip-trans"); os.flush(); os.close(); } catch (Exception e1) { } shutdown(); super.windowClosing(e); } }); } catch (Exception e) { updateMessage(e.getMessage()); } Thread thread = new Thread() { @Override public void run() { while (true) { try { String poll = iconQueue.take(); if ("send".equals(poll)) { trayIcon.setImage(grayImage); } else if ("paste".equals(poll)) { Thread.sleep(20); trayIcon.setImage(grayImage); } } catch (InterruptedException e1) { return; } } } }; thread.setDaemon(true); thread.start(); }
From source file:com.netsteadfast.greenstep.bsc.command.PersonalReportBodyCommand.java
private void fillReportProperty(Map<String, Object> parameter) throws ServiceException, Exception { BscReportPropertyUtils.loadData();// w w w .j ava 2 s .co m parameter.put("objectiveTitle", BscReportPropertyUtils.getObjectiveTitle()); parameter.put("kpiTitle", BscReportPropertyUtils.getKpiTitle()); String classLevel = BscReportPropertyUtils.getPersonalReportClassLevel(); classLevel = StringUtils.defaultString(classLevel); classLevel = classLevel.replaceAll("\n", Constants.HTML_BR); parameter.put("classLevel", classLevel); }
From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpRes = (HttpServletResponse) response; UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME); logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr()); if (httpReq.getSession(false) == null) { chain.doFilter(request, response); return;//from w w w . java 2s . c o m } logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list " + exclList.getExclusionMap()); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } // Check the user session for the salt cache, if none is present we // create one Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME); if (csrfPreventionSaltCache == null) { if (tokenTimeout == -1) { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build(); } else { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build(); } httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache); String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom()); httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt); } // Generate the salt and store it in the users cache String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom()); String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME); SecurityInfo si = new SecurityInfo(saltNameAttr, salt); if (SecurityTokenFilter.checkReferer) { String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer")); logger.debug("doFilter: refHeader=" + refHeader); if (StringUtils.isNotBlank(refHeader)) { try { URL refUrl = new URL(refHeader); refHeader = refUrl.getHost(); } catch (MalformedURLException mex) { logger.debug("doFilter: parsing referer header failed", mex); } } si.setRefererHost(refHeader); } logger.debug("doFilter: si=" + si.toString()); csrfPreventionSaltCache.put(si, si); // Add the salt to the current request so it can be used // by the page rendered in this request httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si); // set CSRF cookie HttpSession session = httpReq.getSession(false); if (session != null && StringUtils.isNotBlank(csrfCookieName)) { if (logger.isDebugEnabled()) { Cookie[] cookies = httpReq.getCookies(); // boolean cookiePresent = false; for (Cookie c : cookies) { String name = c.getName(); logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value=" + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly=" + c.isHttpOnly()); // if (csrfCookieName.equals(name)) { // cookiePresent = true; // break; // } } } // if (!cookiePresent) { byte[] hashSalt = new byte[32]; SecureRandom sr = new SecureRandom(); sr.nextBytes(hashSalt); String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr); Cookie c = new Cookie(csrfCookieName, csrfHash); c.setMaxAge(1800); c.setSecure(false); c.setPath(httpReq.getContextPath()); c.setHttpOnly(false); httpRes.addCookie(c); // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM, // hashStr); // } } chain.doFilter(request, response); }
From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java
public AWS4SignatureBuilder canonicalQueryString(final String canonicalQueryString) { final String defaultString = StringUtils.defaultString(canonicalQueryString); // this way of parsing the query string is the only way to satisfy the // test-suite, therefore we do it with a matcher: final Matcher matcher = QUERY_STRING_MATCHING_PATTERN.matcher(defaultString); final List<KeyValue<String, String>> parameters = Lists.newLinkedList(); while (matcher.find()) { final String key = StringUtils.trim(matcher.group(1)); final String value = StringUtils.trim(matcher.group(2)); parameters.add(new DefaultKeyValue<>(key, value)); }/* www . j av a 2 s .com*/ this.canonicalQueryString = parameters.stream().sorted(Comparator.comparing(KeyValue::getKey)) .map(kv -> queryParameterEscape(kv.getKey()) + "=" + queryParameterEscape(kv.getValue())) .collect(Collectors.joining("&")); return this; }
From source file:com.netsteadfast.greenstep.bsc.util.BscReportSupportUtils.java
public static String getUrlIconBase(String mode, float target, float min, float score, String kpiCompareType, String kpiManagement, float kpiQuasiRange) throws Exception { String icon = ""; SysExpressionVO sysExpression = exprThreadLocal03.get(); if (null == sysExpression) { return icon; }/*from w ww . j a va2 s . com*/ Map<String, Object> parameters = new HashMap<String, Object>(); Map<String, Object> results = new HashMap<String, Object>(); parameters.put("mode", mode); parameters.put("target", target); parameters.put("min", min); parameters.put("score", score); parameters.put("compareType", kpiCompareType); parameters.put("management", kpiManagement); parameters.put("quasiRange", kpiQuasiRange); results.put("icon", " "); ScriptExpressionUtils.execute(sysExpression.getType(), sysExpression.getContent(), results, parameters); icon = (String) results.get("icon"); return StringUtils.defaultString(icon); }
From source file:com.sonicle.webtop.core.util.NotificationHelper.java
/** * Creates strings map for notification (simple body) template * @param locale//from www. ja v a 2 s . com * @param source * @param recipientEmail * @param bodyHeader * @param customBody * @param becauseString * @return */ public static Map<String, String> createCustomBodyTplStrings(Locale locale, String source, String recipientEmail, String bodyHeader, String customBody, String becauseString) { HashMap<String, String> map = new HashMap<>(); map.put("bodyHeader", StringUtils.defaultString(bodyHeader)); map.put("customBody", StringUtils.defaultString(customBody)); map.put("footerHeader", MessageFormat.format( WT.lookupResource(CoreManifest.ID, locale, CoreLocaleKey.TPL_NOTIFICATION_FOOTER_HEADER), source)); map.put("footerMessage", MessageFormat.format( WT.lookupResource(CoreManifest.ID, locale, CoreLocaleKey.TPL_NOTIFICATION_FOOTER_MESSAGE), recipientEmail, becauseString)); return map; }
From source file:com.netsteadfast.greenstep.base.model.CheckFieldHandler.java
public CheckFieldHandler single(String fieldsName, boolean checkResult, String message) { if (this.actionFieldsId == null) { this.actionFieldsId = new LinkedList<String>(); }//from w ww .j av a 2s . c o m if (this.actionFieldsMessage == null) { this.actionFieldsMessage = new HashMap<String, String>(); } if (!checkResult) { return this; } String name[] = fieldsName.replaceAll(" ", "").split("[|]"); for (int i = 0; i < name.length; i++) { if (StringUtils.isBlank(name[i])) { continue; } String idName = name[i].trim(); actionFieldsId.add(idName); /** * inputfieldNoticeMsgLabel ?? * <BR/> BaseSupportAction joinPageMessage <BR/> */ actionFieldsMessage.put(idName, message.replaceAll(Constants.HTML_BR, " ")); fieldsMessages.add(message); } msg.append(StringUtils.defaultString(message)).append(Constants.HTML_BR); return this; }
From source file:com.opencsv.bean.StatefulBeanToCsv.java
/** * Writes a bean out to the {@link java.io.Writer} provided to the * constructor.// www . jav a2 s. c o m * * @param bean A bean to be written to a CSV destination * @throws CsvDataTypeMismatchException If a field of the bean is * annotated improperly or an unsupported data type is supposed to be * written * @throws CsvRequiredFieldEmptyException If a field is marked as required, * but the source is null */ public void write(T bean) throws CsvDataTypeMismatchException, CsvRequiredFieldEmptyException { if (bean != null) { ++lineNumber; beforeFirstWrite(bean); List<String> contents = new ArrayList<String>(); int numColumns = mappingStrategy.findMaxFieldIndex(); if (mappingStrategy.isAnnotationDriven()) { BeanField beanField; for (int i = 0; i <= numColumns; i++) { beanField = mappingStrategy.findField(i); try { String s = beanField != null ? beanField.write(bean) : ""; contents.add(StringUtils.defaultString(s)); } // Combine to a multi-catch once we support Java 7 catch (CsvDataTypeMismatchException e) { e.setLineNumber(lineNumber); if (throwExceptions) { throw e; } else { capturedExceptions.add(e); } } catch (CsvRequiredFieldEmptyException e) { e.setLineNumber(lineNumber); if (throwExceptions) { throw e; } else { capturedExceptions.add(e); } } } } else { PropertyDescriptor desc; for (int i = 0; i <= numColumns; i++) { try { desc = mappingStrategy.findDescriptor(i); Object o = desc != null ? desc.getReadMethod().invoke(bean, (Object[]) null) : null; contents.add(ObjectUtils.toString(o, "")); // Once we support Java 7 // contents.add(Objects.toString(o, "")); } // Combine in a multi-catch with Java 7 catch (IntrospectionException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(bean, null, INTROSPECTION_ERROR); csve.initCause(e); throw csve; } catch (IllegalAccessException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(bean, null, INTROSPECTION_ERROR); csve.initCause(e); throw csve; } catch (InvocationTargetException e) { CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(bean, null, INTROSPECTION_ERROR); csve.initCause(e); throw csve; } } } csvwriter.writeNext(contents.toArray(new String[contents.size()])); } }
From source file:com.netsteadfast.greenstep.sys.GreenStepHessianUtils.java
public static Map<String, String> getDecAuthValue(String encValue) throws Exception { String value = EncryptorUtils.decrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(), SimpleUtils.deHex(encValue)); String val[] = StringUtils.defaultString(value).trim().split(Constants.ID_DELIMITER); if (val.length != 4) { return null; }//from ww w . java 2 s. c o m if (val[0].trim().length() < 1 || val[1].trim().length() != 8 || !NumberUtils.isNumber(val[2]) || !SimpleUtils.checkBeTrueOf_azAZ09(val[3])) { return null; } Map<String, String> data = new HashMap<String, String>(); data.put(CHECK_VALUE_PARAM_NAME, val[0].trim()); data.put(USER_ID_PARAM_NAME, val[3].trim()); return data; }
From source file:com.hypersocket.auth.AuthenticationState.java
public String getLastPrincipalName() { if (principal == null) { return StringUtils.defaultString(lastPrincipalName); } else {//from ww w.j av a 2 s. co m return principal.getPrincipalName(); } }