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.xpn.xwiki.objects.classes.DBTreeListClass.java
/** * <p>/*from w ww . ja v a 2 s. c om*/ * Computes the query corresponding to the current XProperty. The query is either manually specified by the XClass * creator in the <tt>sql</tt> field, or, if the query field is blank, constructed using the <tt>classname</tt>, * <tt>idField</tt>, <tt>valueField</tt> and <tt>parentField</tt> properties. The query is constructed according to * the following rules: * </p> * <ul> * <li>If no classname, id and value fields are selected, return a query that return no rows, as the parent is not * enough to make a query.</li> * <li>If no parent field is provided, use the document "parent" medatada.</li> * <li>If only the classname is provided, select all document names which have an object of that type, preserving * the hierarchy defined by the parent field.</li> * <li>If only one of id and value is provided, use it for both columns.</li> * <li>If no classname is provided, assume the fields are document properties.</li> * <li>If the document is not used at all, don't put it in the query.</li> * <li>If the object is not used at all, don't put it in the query.</li> * </ul> * <p> * The generated query always selects 3 columns, the first one is used as the stored value, the second one as the * displayed value, and the third one defines the "parent" of the current value. * </p> * * @param context The current {@link XWikiContext context}. * @return The HQL query corresponding to this property. */ @Override public String getQuery(XWikiContext context) { // First, get the hql query entered by the user. String sql = getSql(); // If the query field is blank, construct a query using the classname, idField, // valueField and parentField properties. if (StringUtils.isBlank(sql)) { if (context.getWiki().getHibernateStore() != null) { // Extract the 3 properties in non-null variables. String classname = StringUtils.defaultString(getClassname()); String idField = StringUtils.defaultString(getIdField()); String valueField = StringUtils.defaultString(getValueField()); String parentField = StringUtils.defaultString(getParentField()); // Check if the properties are specified or not. boolean hasClassname = !StringUtils.isBlank(classname); boolean hasIdField = !StringUtils.isBlank(idField); boolean hasValueField = !StringUtils.isBlank(valueField); boolean hasParentField = !StringUtils.isBlank(parentField); if (!(hasIdField || hasValueField)) { // If only the classname is specified, return a query that selects all the // document names which have an object of that type, and the hierarchy is // defined by the document "parent" property (unless a parent property is // specified). if (hasClassname) { sql = "select distinct doc.fullName, doc.fullName, " + (hasParentField ? parentField : "doc.parent") + " from XWikiDocument as doc, BaseObject as obj" + " where doc.fullName=obj.name and obj.className='" + classname + "'"; } else { // If none of the first 3 properties is specified, return a query that // always returns no rows (only with the parent field no query can be made) sql = DEFAULT_QUERY; } return sql; } // If only one of the id and value fields is specified, use it for both columns. if (!hasIdField && hasValueField) { idField = valueField; } else if (hasIdField && !hasValueField) { valueField = idField; } // If no parent field was specified, use the document "parent" metadata if (!hasParentField) { parentField = "doc.parent"; } // Check if the document and object are needed or not. // The object is needed if there is a classname, or if at least one of the selected // columns is an object property. boolean usesObj = hasClassname || idField.startsWith("obj.") || valueField.startsWith("obj.") || parentField.startsWith("obj."); // The document is needed if one of the selected columns is a document property, or // if there is no classname specified and at least one of the selected columns is // not an object property. boolean usesDoc = idField.startsWith("doc.") || valueField.startsWith("doc.") || parentField.startsWith("doc."); if ((!idField.startsWith("obj.") || !valueField.startsWith("obj.") || !parentField.startsWith("obj.")) && !hasClassname) { usesDoc = true; } // Build the query in this variable. StringBuffer select = new StringBuffer("select distinct "); // These will hold the components of the from and where parts of the query. ArrayList<String> fromStatements = new ArrayList<String>(); ArrayList<String> whereStatements = new ArrayList<String>(); // Add the document to the query only if it is needed. if (usesDoc) { fromStatements.add("XWikiDocument as doc"); if (usesObj) { whereStatements.add("doc.fullName=obj.name"); } } // Add the object to the query only if it is needed. if (usesObj) { fromStatements.add("BaseObject as obj"); if (hasClassname) { whereStatements.add("obj.className='" + classname + "'"); } } // Add the first column to the query. if (idField.startsWith("doc.") || idField.startsWith("obj.")) { select.append(idField); } else if (!hasClassname) { select.append("doc." + idField); } else { select.append("idprop.value"); fromStatements.add("StringProperty as idprop"); whereStatements.add("obj.id=idprop.id.id and idprop.id.name='" + idField + "'"); } // Add the second column to the query. if (valueField.startsWith("doc.") || valueField.startsWith("obj.")) { select.append(", ").append(valueField); } else if (!hasClassname) { select.append(", doc." + valueField); } else { if (valueField.equals(idField)) { select.append(", idprop.value"); } else { select.append(", valueprop.value"); fromStatements.add("StringProperty as valueprop"); whereStatements.add("obj.id=valueprop.id.id and valueprop.id.name='" + valueField + "'"); } } // Add the third column to the query. if (parentField.startsWith("doc.") || parentField.startsWith("obj.")) { select.append(", ").append(parentField); } else if (!hasClassname) { select.append(", doc." + parentField); } else { if (parentField.equals(idField)) { select.append(", idprop.value"); } else if (parentField.equals(valueField)) { select.append(", valueprop.value"); } else { select.append(", parentprop.value"); fromStatements.add("StringProperty as parentprop"); whereStatements.add("obj.id=parentprop.id.id and parentprop.id.name='" + parentField + "'"); } } // Let's create the complete query select.append(" from "); select.append(StringUtils.join(fromStatements.iterator(), ", ")); if (whereStatements.size() > 0) { select.append(" where "); select.append(StringUtils.join(whereStatements.iterator(), " and ")); } sql = select.toString(); } else { // TODO: query plugin impl. // We need to generate the right query for the query plugin } } // Parse the query, so that it can contain velocity scripts, for example to use the // current document name, or the current username. try { sql = context.getWiki().parseContent(sql, context); } catch (Exception e) { LOGGER.error("Failed to parse SQL script [" + sql + "]. Continuing with non-rendered script.", e); } return sql; }
From source file:de.bund.bfr.fskml.MetadataDocument.java
/** * @param template FSK model metadata/*from w w w . j av a 2 s . c om*/ */ private void addDocumentAnnotation(final FskMetaData template) { // null is replaces with empty string String givenName = StringUtils.defaultString(template.creator); String familyName = StringUtils.defaultString(template.familyName); String contact = StringUtils.defaultString(template.contact); String createdDate = template.createdDate == null ? "" : FskMetaData.dateFormat.format(template.createdDate); String modifiedDate = template.modifiedDate == null ? "" : FskMetaData.dateFormat.format(template.modifiedDate); String type = template.type == null ? "" : template.type.name(); String rights = StringUtils.defaultString(template.rights); String referenceDescription = StringUtils.defaultString(template.referenceDescription); String referenceDescriptionLink = StringUtils.defaultString(template.referenceDescriptionLink); Annotation annotation = new MetadataAnnotation(givenName, familyName, contact, createdDate, modifiedDate, type, rights, referenceDescription, referenceDescriptionLink).annotation; this.doc.setAnnotation(annotation); }
From source file:com.norconex.commons.lang.io.FileUtil.java
/** * Returns the specified number of lines starting from the end * of a text file.//from w w w .jav a 2 s.c o m * @param file the file to read lines from * @param encoding the file encoding * @param numberOfLinesToRead the number of lines to read * @param stripBlankLines whether to return blank lines or not * @param filter InputStream filter * @return array of file lines * @throws IOException i/o problem */ public static String[] tail(File file, String encoding, final int numberOfLinesToRead, boolean stripBlankLines, IInputStreamFilter filter) throws IOException { assertFile(file); assertNumOfLinesToRead(numberOfLinesToRead); LinkedList<String> lines = new LinkedList<String>(); BufferedReader reader = new BufferedReader( new InputStreamReader(new ReverseFileInputStream(file), encoding)); int remainingLinesToRead = numberOfLinesToRead; String line = StringUtils.EMPTY; while (line != null && remainingLinesToRead-- > 0) { line = StringUtils.defaultString(reader.readLine()); char[] chars = line.toCharArray(); for (int j = 0, k = chars.length - 1; j < k; j++, k--) { char temp = chars[j]; chars[j] = chars[k]; chars[k] = temp; } String newLine = new String(chars); if (!stripBlankLines || StringUtils.isNotBlank(line)) { if (filter != null && filter.accept(newLine)) { lines.addFirst(newLine); } else { remainingLinesToRead++; } } else { remainingLinesToRead++; } } reader.close(); return lines.toArray(ArrayUtils.EMPTY_STRING_ARRAY); }
From source file:de.micromata.genome.gwiki.page.impl.GWikiPropsEditorArtefakt.java
public void renderViaDescriptor(GWikiContext ctx) { boolean hasAnyDescription = false; for (GWikiPropsDescriptorValue d : propDescriptor.getDescriptors()) { if (StringUtils.isNotBlank(d.getDescription()) == true) { hasAnyDescription = true;/*from w w w. j a v a2 s.c o m*/ break; } } // TODO Title rendering // XmlElement table = Html.table(Xml.attrs("width", "100%", "class", "gwikiProperties"), // // Html.tr( // // Html.th(Xml.attrs("width", "70", "align", "left"), Xml.code(ctx.getTranslated("gwiki.propeditor.title.key"))), // // Html.th(Xml.attrs("width", "300", "align", "left"), Xml.code(ctx.getTranslated("gwiki.propeditor.title.value"))), // // Html.th(Xml.attrs("width", "16", "align", "left"), Xml.code(" ")), // // Html.th(Xml.attrs("align", "left"), Xml.code(hasAnyDescription == false ? "" : ctx // .getTranslated("gwiki.propeditor.title.description"))))); Object o = ctx.getRequest().getAttribute("form"); String metaTemplateId = null; if (o instanceof GWikiEditPageActionBean) { GWikiEditPageActionBean bean = ((GWikiEditPageActionBean) ctx.getRequest().getAttribute("form")); metaTemplateId = bean.getMetaTemplate().getPageId(); } // String metaTemplateId = el.getMetaTemplate().getPageId(); List<Pair<GWikiPropsGroupDescriptor, List<GWikiPropsDescriptorValue>>> pl = getGroupedProps(metaTemplateId); for (Pair<GWikiPropsGroupDescriptor, List<GWikiPropsDescriptorValue>> p : pl) { ctx.append("<fieldset"); if (p.getFirst().isCollabsable() == true) { if (p.getFirst().isClosed() == true) { ctx.append(" class=\"startClosed\""); } else { ctx.append(" class=\"collapsible\""); } } ctx.append("><legend class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">")// .append(ctx.getTranslatedProp(p.getFirst().getTitle())).append("</legend><div>"); for (GWikiPropsDescriptorValue d : p.getSecond()) { PropsEditContext pctx = createPropContext(ctx, d); if (pctx.isDisplayable() == false) { continue; } String nested = onRender(pctx); String label = d.getKey(); if (d.getLabel() != null) { label = ctx.getTranslatedProp(d.getLabel()); } ctx.append("<div style=\"clear:left; margin-top:0.5em\">"); ctx.append("<label style=\"float:left; width:10em;\">").appendEscText(label).append("</label>"); ctx.append("<div style=\"float:left; width:23em\">").append(nested).append("</div>"); ctx.append("<span style=\"float:left; margin-left:1em; width:2em; height:28px\">") .append(renderHelpLink(d, ctx)).append("</span>"); ctx.append("<span>").append(StringUtils.defaultString(ctx.getTranslatedProp(d.getDescription()))) .append("</span>\n"); ctx.append("</div>"); // // table.add( // // Html.tr( // // Html.td(Xml.code(label)), // // Html.td(Xml.code(nested)), // // Html.td(Xml.code(renderHelpLink(d, ctx))), // // Html.td(Xml.code(StringUtils.defaultString(ctx.getTranslatedProp(d.getDescription())))))); // } ctx.append("</div></fieldset>\n"); } // for (GWikiPropsDescriptorValue d : propDescriptor.getDescriptors()) { // if (isForThisElement(d, metaTemplateId) == false) // continue; // PropsEditContext pctx = createPropContext(ctx, d); // if (pctx.isDisplayable() == false) { // continue; // } // String nested = onRender(pctx); // String label = d.getKey(); // if (d.getLabel() != null) { // label = ctx.getTranslatedProp(d.getLabel()); // } // table.add( // // Html.tr( // // Html.td(Xml.code(label)), // // Html.td(Xml.code(nested)), // // Html.td(Xml.code(renderHelpLink(d, ctx))), // // Html.td(Xml.code(StringUtils.defaultString(ctx.getTranslatedProp(d.getDescription())))))); // } // ctx.append(table.toString()); }
From source file:com.willwinder.universalgcodesender.GrblController.java
@Override public ControlState getControlState() { if (!this.capabilities.hasCapability(GrblCapabilitiesConstants.REAL_TIME)) { return super.getControlState(); }// w w w . ja v a 2s.co m String state = this.controllerStatus == null ? "" : StringUtils.defaultString(this.controllerStatus.getStateString()); switch (state.toLowerCase()) { case "jog": case "run": return ControlState.COMM_SENDING; case "hold": case "door": case "queue": return ControlState.COMM_SENDING_PAUSED; case "idle": if (isStreaming()) { return ControlState.COMM_SENDING_PAUSED; } else { return ControlState.COMM_IDLE; } case "alarm": return ControlState.COMM_IDLE; case "check": if (isStreaming() && comm.isPaused()) { return ControlState.COMM_SENDING_PAUSED; } else if (isStreaming() && !comm.isPaused()) { return ControlState.COMM_SENDING; } else { return COMM_CHECK; } default: return ControlState.COMM_IDLE; } }
From source file:com.pidoco.juri.JURI.java
/** * <pre>/*from ww w. j a va 2s.co m*/ * "".addRawPath("") -> "" * "/".addRawPath("") -> "/" * "".addRawPath("/") -> "/" * "a".addRawPath("") -> "a/" * "a".addRawPath("b") -> "a/b" * "/".addRawPath("/") -> "/" * </pre> */ public JURI addRawPath(CharSequence toAdd) { String currentRawPath = StringUtils.defaultString(getRawPath()); setRawPath(concatRawPaths(currentRawPath, toAdd)); return this; }
From source file:eionet.webq.web.controller.WebQProxyDelegation.java
/** * Fetches XML file from given xmlUri and applies XSLT conversion with xsltUri. * The resulting xml is converted to json, if format parameter equals 'json'. * Applies authorisation information to fetch XML request, if it is available through UserFile. * * @param xmlUri remote xml file URI/*from w w w. ja v a 2 s . co m*/ * @param fileId WebQ session file ID to be used for applying authorisation info * @param xsltUri remote xslt file URI * @param format optional response format. Only json is supported, default is xml * @param request standard HttpServletRequest * @param response standard HttpServletResponse * @return converted XML content * @throws UnsupportedEncodingException Cannot convert xml to UTF-8 * @throws URISyntaxException xmlUri or xsltUri is incorrect * @throws FileNotAvailableException xml or xslt file is not available * @throws TransformerException error when applying xslt transformation on xml */ @RequestMapping(value = "/proxyXmlWithConversion", method = RequestMethod.GET, produces = "text/html;charset=utf-8") @ResponseBody public byte[] proxyXmlWithConversion(@RequestParam("xmlUri") String xmlUri, @RequestParam(required = false) Integer fileId, @RequestParam("xsltUri") String xsltUri, @RequestParam(required = false) String format, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, URISyntaxException, FileNotAvailableException, TransformerException { byte[] xml = null; UserFile file = userFileHelper.getUserFile(fileId, request); if (file != null && ProxyDelegationHelper.isCompanyIdParameterValidForBdrEnvelope(request.getRequestURI(), file.getEnvelope())) { xml = restProxyGetWithAuth(xmlUri, fileId, request).getBytes("UTF-8"); } else { xml = new RestTemplate().getForObject(new URI(xmlUri), byte[].class); } byte[] xslt = new RestTemplate().getForObject(new URI(xsltUri), byte[].class); Source xslSource = new StreamSource(new ByteArrayInputStream(xslt)); ByteArrayOutputStream xmlResultOutputStream = new ByteArrayOutputStream(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource); for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) { if (!parameter.getKey().equals("xmlUri") && !parameter.getKey().equals("fileId") && !parameter.getKey().equals("xsltUri") && !parameter.getKey().equals("format")) { transformer.setParameter(parameter.getKey(), StringUtils.defaultString(parameter.getValue()[0])); } } transformer.transform(new StreamSource(new ByteArrayInputStream(xml)), new StreamResult(xmlResultOutputStream)); } catch (TransformerException e1) { LOGGER.error("Unable to transform xml uri=" + xmlUri + " with stylesheet=" + xsltUri); e1.printStackTrace(); throw e1; } byte[] result; if (StringUtils.isNotEmpty(format) && format.equals("json")) { result = jsonXMLConverter.convertXmlToJson(xmlResultOutputStream.toByteArray()); response.setContentType(String.valueOf(MediaType.APPLICATION_JSON)); } else { result = xmlResultOutputStream.toByteArray(); response.setContentType(String.valueOf(MediaType.APPLICATION_XML)); } LOGGER.info("Converted xml uri=" + xmlUri + " with stylesheet=" + xsltUri); response.setCharacterEncoding("utf-8"); return result; }
From source file:de.blizzy.backup.settings.SettingsDialog.java
private void addFolder(ILocation location) { @SuppressWarnings("unchecked") Set<ILocation> locations = (Set<ILocation>) foldersViewer.getInput(); // is the new folder a child of any folder in the backup? if so, display error message for (ILocation oldLocation : locations) { if (Utils.isParent(oldLocation.getRootFolder(), location.getRootFolder())) { MessageDialog.openError(getShell(), Messages.Title_FolderCannotBeAdded, NLS.bind(Messages.ParentFolderInBackup, Utils.getSimpleName(location.getRootFolder()))); return; }/* w w w.j a v a 2 s. c o m*/ } // is the new folder the parent of the output folder? if so, display error message String outputFolder = StringUtils.defaultString(outputFolderText.getText()); if (StringUtils.isNotBlank(outputFolder) && Utils.isParent(location.getRootFolder(), new FileSystemFileOrFolder(new File(outputFolder)))) { MessageDialog.openError(getShell(), Messages.Title_FolderCannotBeAdded, NLS.bind(Messages.FolderIsParentOfBackupFolder, Utils.getSimpleName(location.getRootFolder()))); return; } // is the new folder the same as the output folder? if so, display error message if (StringUtils.isNotBlank(outputFolder) && location.getRootFolder().equals(new FileSystemFileOrFolder(new File(outputFolder)))) { MessageDialog.openError(getShell(), Messages.Title_FolderCannotBeAdded, NLS.bind(Messages.FolderIsOutputFolder, Utils.getSimpleName(location.getRootFolder()))); return; } // is the new folder a child of the output folder? if so, display error message if (StringUtils.isNotBlank(outputFolder) && Utils.isParent(new FileSystemFileOrFolder(new File(outputFolder)), location.getRootFolder())) { MessageDialog.openError(getShell(), Messages.Title_FolderCannotBeAdded, NLS.bind(Messages.FolderIsChildOfOutputFolder, Utils.getSimpleName(location.getRootFolder()))); return; } // is the new folder the parent of any folder in the backup? if so, remove those folders for (ILocation oldLocation : new HashSet<>(locations)) { if (Utils.isParent(location.getRootFolder(), oldLocation.getRootFolder())) { locations.remove(oldLocation); foldersViewer.remove(oldLocation); } } if (locations.add(location)) { foldersViewer.add(location); } }
From source file:com.mirth.connect.server.controllers.DefaultUserController.java
@Override public Properties getUserPreferences(Integer userId, Set<String> names) { logger.debug("retrieving preferences: user id=" + userId); Properties properties = new Properties(); try {//from www. j av a2 s .co m List<KeyValuePair> result = SqlConfig.getSqlSessionManager().selectList("User.selectPreferencesForUser", userId); for (KeyValuePair pair : result) { if (CollectionUtils.isEmpty(names) || names.contains(pair.getKey())) { properties.setProperty(pair.getKey(), StringUtils.defaultString(pair.getValue())); } } } catch (Exception e) { logger.error("Could not retrieve preferences: user id=" + userId, e); } return properties; }
From source file:com.jxt.web.service.FilteredMapServiceImpl.java
private void addNodeFromSpanEvent(SpanBo span, TimeWindow window, LinkDataDuplexMap linkDataDuplexMap, Map<Long, SpanBo> transactionSpanMap) { /**/*from ww w. ja va 2 s . c o m*/ * add span event statistics */ final List<SpanEventBo> spanEventBoList = span.getSpanEventBoList(); if (CollectionUtils.isEmpty(spanEventBoList)) { return; } final Application srcApplication = applicationFactory.createApplication(span.getApplicationId(), span.getApplicationServiceType()); LinkDataMap sourceLinkDataMap = linkDataDuplexMap.getSourceLinkDataMap(); for (SpanEventBo spanEvent : spanEventBoList) { ServiceType destServiceType = registry.findServiceType(spanEvent.getServiceType()); if (!destServiceType.isRecordStatistics()) { // internal method continue; } // convert to Unknown if destServiceType is a rpc client and there is no acceptor. // acceptor exists if there is a span with spanId identical to the current spanEvent's next spanId. // logic for checking acceptor if (destServiceType.isRpcClient()) { if (!transactionSpanMap.containsKey(spanEvent.getNextSpanId())) { destServiceType = ServiceType.UNKNOWN; } } String dest = spanEvent.getDestinationId(); if (dest == null) { dest = "Unknown"; } final Application destApplication = this.applicationFactory.createApplication(dest, destServiceType); final short slotTime = getHistogramSlotTime(spanEvent, destServiceType); // FIXME final long spanEventTimeStamp = window .refineTimestamp(span.getStartTime() + spanEvent.getStartElapsed()); if (logger.isTraceEnabled()) { logger.trace("spanEvent src:{} {} -> dest:{} {}", srcApplication, span.getAgentId(), destApplication, spanEvent.getEndPoint()); } // endPoint may be null final String destinationAgentId = StringUtils.defaultString(spanEvent.getEndPoint()); sourceLinkDataMap.addLinkData(srcApplication, span.getAgentId(), destApplication, destinationAgentId, spanEventTimeStamp, slotTime, 1); } }