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:de.blizzy.documentr.markdown.MarkdownProcessor.java
public String processNonCacheableMacros(String html, String projectName, String branchName, String path, Authentication authentication, String contextPath) { HtmlSerializerContext context = new HtmlSerializerContext(projectName, branchName, path, this, authentication, pageStore, systemSettingsStore, contextPath); String startMarkerPrefix = "__" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$ String endMarkerPrefix = "__/" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$ String bodyMarker = "__" + NON_CACHEABLE_MACRO_BODY_MARKER + "__"; //$NON-NLS-1$ //$NON-NLS-2$ for (;;) {//from w ww . j a v a 2 s. c om int start = html.indexOf(startMarkerPrefix); if (start < 0) { break; } start += startMarkerPrefix.length(); int end = html.indexOf('_', start); if (end < 0) { break; } String idx = html.substring(start, end); start = html.indexOf("__", start); //$NON-NLS-1$ if (start < 0) { break; } start += 2; end = html.indexOf(endMarkerPrefix + idx + "__", start); //$NON-NLS-1$ if (end < 0) { break; } String macroCallWithBody = html.substring(start, end); String macroCall = StringUtils.substringBefore(macroCallWithBody, bodyMarker); String body = StringUtils.substringAfter(macroCallWithBody, bodyMarker); String macroName = StringUtils.substringBefore(macroCall, " "); //$NON-NLS-1$ String params = StringUtils.substringAfter(macroCall, " "); //$NON-NLS-1$ IMacro macro = macroFactory.get(macroName); MacroContext macroContext = MacroContext.create(macroName, params, body, context, beanFactory); IMacroRunnable macroRunnable = macro.createRunnable(); html = StringUtils.replace(html, startMarkerPrefix + idx + "__" + macroCallWithBody + endMarkerPrefix + idx + "__", //$NON-NLS-1$ //$NON-NLS-2$ StringUtils.defaultString(macroRunnable.getHtml(macroContext))); MacroInvocation invocation = new MacroInvocation(macroName, params); html = cleanupHtml(html, Collections.singletonList(invocation), false); } return html; }
From source file:gtu.log.finder.ExceptionLogFinderUI.java
private void executeBtnAction() { try {/*from w ww . j a v a 2 s. co m*/ String srcFilePath = srcFilePathText.getText(); int preLine = 5; try { preLine = Integer.parseInt(preLineText.getText()); } catch (Exception ex) { JCommonUtil._jOptionPane_showMessageDialog_error("?"); return; } if (StringUtils.isBlank(srcFilePath)) { JCommonUtil._jOptionPane_showMessageDialog_error("log"); return; } File srcFile = new File(srcFilePath); String middleFileName = srcFile.getName().substring(0, srcFile.getName().lastIndexOf(".")); String searchStr = StringUtils.defaultString(searchText.getText()); String startStr = StringUtils.defaultString(startStrText.getText()); String endStr = StringUtils.defaultString(endStrText.getText()); Map<String, Object> valueMap = new HashMap<String, Object>(); valueMap.put("preLine", preLine); valueMap.put("middleFileName", middleFileName); valueMap.put("srcFile", srcFile); valueMap.put("searchStr", searchStr); valueMap.put("startStr", startStr); valueMap.put("endStr", endStr); if (isExceptionLogChkBox.isSelected()) { outputLogFile = ActionType.Exception.process(valueMap); } else if (StringUtils.isNotBlank(startStr) && StringUtils.isNotBlank(endStr)) { outputLogFile = ActionType.StartEnd.process(valueMap); } else { outputLogFile = ActionType.KeyWord.process(valueMap); } setParseFileText.setText(outputLogFile.getAbsolutePath()); JCommonUtil._jOptionPane_showMessageDialog_info( "??:" + outputLogFile.getName() + "\n:" + outputLogFile.getAbsolutePath()); } catch (Exception ex) { JCommonUtil.handleException(ex); } }
From source file:net.andydvorak.intellij.lessc.fs.LessFile.java
private static List<String> normalizePatterns(final String patterns) { final Set<String> normalized = new LinkedHashSet<String>(); for (String pattern : StringUtils.defaultString(patterns).split(";")) { if (StringUtils.isNotEmpty(pattern)) normalized.add(makePatternAbsolute(pattern)); }/*from w w w .j a v a2 s. c om*/ return new ArrayList<String>(normalized); }
From source file:com.netsteadfast.greenstep.base.model.SqlGenerateUtil.java
private static Map<String, Object> getField(Object entityObject) throws Exception { Map<String, Object> fieldMap = new HashMap<String, Object>(); Method[] methods = entityObject.getClass().getMethods(); for (int ix = 0; ix < methods.length; ix++) { Annotation[] annotations = methods[ix].getDeclaredAnnotations(); if (annotations == null) { continue; }// w w w . jav a 2 s . co m for (Annotation annotation : annotations) { if (annotation instanceof Column) { if (methods[ix].getName().indexOf("get") != 0) { continue; } String column = StringUtils.defaultString(((Column) annotation).name()); if ("".equals(column.trim())) { continue; } Object value = methods[ix].invoke(entityObject); fieldMap.put(column, value); } } } return fieldMap; }
From source file:net.andydvorak.intellij.lessc.fs.LessFile.java
/** * Resolves extensionless {@code @import} LESS filenames so that they always end with ".less". * <p>Examples:</p>//from w w w . j a v a 2 s . com * <pre>resolveImportFileName("main") = "main.less"</pre> * <pre>resolveImportFileName("main.less") = "main.less"</pre> * @param filename filename from a LESS {@code @import} that may or may not end with ".less" * @return the filename ending with ".less" */ private static String resolveImportFileName(@Nullable String filename) { filename = StringUtils.defaultString(filename); if (filename.endsWith(".less")) return filename; else return filename + ".less"; }
From source file:io.wcm.devops.maven.nodejsproxy.resource.MavenProxyResource.java
private String buildBinaryUrl(ArtifactType artifactType, String version, String os, String arch, String type) { String url;/*from w ww . j a v a 2s . com*/ switch (artifactType) { case NODEJS: if (StringUtils.equals(os, "windows")) { if (isVersion4Up(version)) { url = config.getNodeJsBinariesUrlWindows(); } else if (StringUtils.equals(arch, "x86")) { url = config.getNodeJsBinariesUrlWindowsX86Legacy(); } else { url = config.getNodeJsBinariesUrlWindowsX64Legacy(); } } else { url = config.getNodeJsBinariesUrl(); } break; case NPM: url = config.getNpmBinariesUrl(); break; default: throw new IllegalArgumentException("Illegal artifact type: " + artifactType); } url = config.getNodeJsBinariesRootUrl() + url; url = StringUtils.replace(url, "${version}", StringUtils.defaultString(version)); url = StringUtils.replace(url, "${os}", StringUtils.defaultString(os)); url = StringUtils.replace(url, "${arch}", StringUtils.defaultString(arch)); url = StringUtils.replace(url, "${type}", StringUtils.defaultString(type)); return url; }
From source file:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java
/** * Build and fill A OccurrenceViewModel based on a OccurrenceModel. * /*from ww w. j a v a 2s . com*/ * @param occModel * @return OccurrenceViewModel instance, never null */ public OccurrenceViewModel buildOccurrenceViewModel(OccurrenceModel occModel, DwcaResourceModel resourceModel, List<OccurrenceExtensionModel> occMultimediaExtModelList, Locale locale) { OccurrenceViewModel occViewModel = new OccurrenceViewModel(); ResourceBundle bundle = appConfig.getResourceBundle(locale); // handle multimedia first (priority over associatedmedia) if (occMultimediaExtModelList != null) { String multimediaFormat, multimediaLicense, multimediaReference, multimediaIdentifier, licenseShortname; boolean isImage; MultimediaViewModel multimediaViewModel; Map<String, String> extData; for (OccurrenceExtensionModel currMultimediaExt : occMultimediaExtModelList) { extData = currMultimediaExt.getExt_data(); multimediaFormat = StringUtils.defaultString(extData.get("format")); multimediaLicense = StringUtils.defaultString(extData.get("license")); multimediaIdentifier = extData.get("identifier"); // if reference is blank, use the identifier multimediaReference = StringUtils.defaultIfBlank(extData.get("references"), multimediaIdentifier); // check if it's an image isImage = multimediaFormat.startsWith("image"); licenseShortname = appConfig.getLicenseShortName(multimediaLicense); multimediaViewModel = new MultimediaViewModel(multimediaIdentifier, multimediaReference, extData.get("title"), multimediaLicense, extData.get("creator"), isImage, licenseShortname); occViewModel.addMultimediaViewModel(multimediaViewModel); } } // handle media (only if occMultimediaExtModelList was not provided) if ((occMultimediaExtModelList == null || occMultimediaExtModelList.isEmpty()) && StringUtils.isNotEmpty(occModel.getAssociatedmedia())) { // assumes that data are coming from harvester String[] media = occModel.getAssociatedmedia().split("; "); MultimediaViewModel multimediaViewModel; boolean isImage; String title; int imageNumber = 1, otherMediaNumber = 1; for (String currentMedia : media) { isImage = MIME_TYPE_MAP.getContentType(currentMedia).startsWith("image"); String image = bundle.getString("occ.image"); if (isImage) { title = image + " " + imageNumber; imageNumber++; } else { title = bundle.getString("occ.associatedmedia") + " " + otherMediaNumber; otherMediaNumber++; } multimediaViewModel = new MultimediaViewModel(currentMedia, currentMedia, title, null, null, isImage, null); occViewModel.addMultimediaViewModel(multimediaViewModel); } } // handle associated sequences handleAssociatedSequence(occModel, occViewModel); // handle data source page URL (url to the resource page) if (resourceModel != null) { if (StringUtils.contains(resourceModel.getArchive_url(), IPT_ARCHIVE_PATTERN)) { occViewModel.setDataSourcePageURL(StringUtils.replace(resourceModel.getArchive_url(), IPT_ARCHIVE_PATTERN, IPT_RESOURCE_PATTERN)); } } // handle Recommended Citation String datasourcePageUrl = occViewModel.getDataSourcePageURL(); if (datasourcePageUrl != null) occViewModel.setRecommendedCitation( Formatter.buildRecommendedCitation(occModel, datasourcePageUrl, bundle)); return occViewModel; }
From source file:com.netsteadfast.greenstep.base.model.SqlGenerateUtil.java
private static String getTableName(Object entityObject) throws Exception { String tableName = ""; Annotation annotations[] = entityObject.getClass().getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof Table) { tableName = StringUtils.defaultString(((Table) annotation).name()); }//from w w w . j a v a 2s. c om } return tableName; }
From source file:eionet.webq.web.controller.WebQProxyDelegation.java
/** * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used. * * @param uri the address to forward the request * @param fileId UserFile id stored in session * @param multipartRequest file part in multipart request * @return response from remote host/* w w w.j a v a2 s .c o m*/ * @throws URISyntaxException provide URI is incorrect * @throws IOException could not read file from request */ @RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8") @ResponseBody public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId, MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException { UserFile file = userFileHelper.getUserFile(fileId, multipartRequest); if (!multipartRequest.getFileNames().hasNext()) { throw new IllegalArgumentException("File not found in multipart request."); } Map<String, String[]> parameters = multipartRequest.getParameterMap(); // limit request to one file String fileName = multipartRequest.getFileNames().next(); MultipartFile multipartFile = multipartRequest.getFile(fileName); HttpHeaders authorization = new HttpHeaders(); if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) { authorization = envelopeService.getAuthorizationHeader(file); } HttpHeaders fileHeaders = new HttpHeaders(); fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename()); fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType())); MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>(); byte[] content = multipartFile.getBytes(); request.add("file", new HttpEntity<byte[]>(content, fileHeaders)); for (Map.Entry<String, String[]> parameter : parameters.entrySet()) { if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId") && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) { request.add(parameter.getKey(), new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0]))); } } HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>( request, authorization); LOGGER.info("/restProxyFileUpload [POST] uri=" + uri); return restTemplate.postForObject(uri, requestEntity, String.class); }
From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java
/** * Creates an <tt>HttpMethod</tt> instance according to the specified parameters. * @param webRequest the request//from w w w . j a v a2 s.c o m * @param httpClientBuilder the httpClientBuilder that will be configured * @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters * @throws IOException * @throws URISyntaxException */ @SuppressWarnings("deprecation") private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder) throws IOException, URISyntaxException { final String charset = webRequest.getCharset(); // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode // chars in the URL. final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset); // URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path // what shouldn't happen here URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), escapeQuery(url.getQuery()), null); if (getVirtualHost() != null) { uri = URI.create(getVirtualHost()); } final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri); setProxy(httpMethod, webRequest); if (!(httpMethod instanceof HttpEntityEnclosingRequest)) { // this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD if (!webRequest.getRequestParameters().isEmpty()) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query, null); httpMethod.setURI(uri); } } else { // POST as well as PUT and PATCH final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod; if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) { final HttpPost postMethod = (HttpPost) method; if (webRequest.getRequestBody() == null) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); final StringEntity urlEncodedEntity = new StringEntity(query, charset); urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); postMethod.setEntity(urlEncodedEntity); } else { final String body = StringUtils.defaultString(webRequest.getRequestBody()); final StringEntity urlEncodedEntity = new StringEntity(body, charset); urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); postMethod.setEntity(urlEncodedEntity); } } else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) { final Charset c = getCharset(charset, webRequest.getRequestParameters()); final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode(); builder.setCharset(c); for (final NameValuePair pair : webRequest.getRequestParameters()) { if (pair instanceof KeyDataPair) { buildFilePart((KeyDataPair) pair, builder); } else { builder.addTextBody(pair.getName(), pair.getValue(), ContentType.create("text/plain", charset)); } } method.setEntity(builder.build()); } else { // for instance a PUT or PATCH request final String body = webRequest.getRequestBody(); if (body != null) { method.setEntity(new StringEntity(body, charset)); } } } configureHttpProcessorBuilder(httpClientBuilder, webRequest); // Tell the client where to get its credentials from // (it may have changed on the webClient since last call to getHttpClientFor(...)) final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider(); // if the used url contains credentials, we have to add this final Credentials requestUrlCredentials = webRequest.getUrlCredentials(); if (null != requestUrlCredentials && webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) { final URL requestUrl = webRequest.getUrl(); final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort()); // updating our client to keep the credentials for the next request credentialsProvider.setCredentials(authScope, requestUrlCredentials); httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE); } // if someone has set credentials to this request, we have to add this final Credentials requestCredentials = webRequest.getCredentials(); if (null != requestCredentials) { final URL requestUrl = webRequest.getUrl(); final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort()); // updating our client to keep the credentials for the next request credentialsProvider.setCredentials(authScope, requestCredentials); httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE); } httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER); return httpMethod; }