List of usage examples for org.apache.commons.lang3 StringUtils defaultIfBlank
public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr)
Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null , the value of defaultStr .
StringUtils.defaultIfBlank(null, "NULL") = "NULL" StringUtils.defaultIfBlank("", "NULL") = "NULL" StringUtils.defaultIfBlank(" ", "NULL") = "NULL" StringUtils.defaultIfBlank("bat", "NULL") = "bat" StringUtils.defaultIfBlank("", null) = null
From source file:org.structr.web.importer.Importer.java
private Linkable downloadFile(final String downloadAddress, final URL base) { URL downloadUrl = null;/*ww w . j a v a2 s. c o m*/ try { downloadUrl = new URL(base, downloadAddress); } catch (MalformedURLException ex) { logger.error("Could not resolve address {}", address != null ? address.concat("/") : ""); return null; } final String alreadyDownloadedKey = downloadUrl.getPath(); // Don't download the same file twice if (alreadyDownloaded.containsKey(alreadyDownloadedKey)) { return alreadyDownloaded.get(alreadyDownloadedKey); } long size; long checksum; String contentType; java.io.File tmpFile; try { // create temporary file on disk final Path tmpFilePath = Files.createTempFile("structr", "download"); tmpFile = tmpFilePath.toFile(); } catch (IOException ioex) { logger.error("Unable to create temporary file for download, aborting."); return null; } try { logger.info("Starting download from {}", downloadUrl); copyURLToFile(downloadUrl.toString(), tmpFile); } catch (IOException ioe) { if (originalUrl == null || address == null) { logger.info("Cannot download from {} without base address", downloadAddress); return null; } logger.warn("Unable to download from {} {}", new Object[] { originalUrl, downloadAddress }); try { // Try alternative baseUrl with trailing "/" if (address.endsWith("/")) { // don't append a second slash! logger.info("Starting download from alternative URL {} {} {}", new Object[] { originalUrl, address, downloadAddress }); downloadUrl = new URL(new URL(originalUrl, address), downloadAddress); } else { // append a slash logger.info("Starting download from alternative URL {} {} {}", new Object[] { originalUrl, address.concat("/"), downloadAddress }); downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress); } copyURLToFile(downloadUrl.toString(), tmpFile); } catch (MalformedURLException ex) { logger.error("Could not resolve address {}", address.concat("/")); return null; } catch (IOException ex) { logger.warn("Unable to download from {}", address.concat("/")); return null; } logger.info("Starting download from alternative URL {}", downloadUrl); } //downloadAddress = StringUtils.substringBefore(downloadAddress, "?"); final String downloadName = cleanFileName(downloadUrl.getFile()); final String fileName = PathHelper.getName(downloadName); if (StringUtils.isBlank(fileName)) { logger.warn("Can't figure out filename from download address {}, aborting.", downloadAddress); return null; } // TODO: Add security features like null/integrity/virus checking before copying it to // the files repo try { contentType = FileHelper.getContentMimeType(tmpFile, fileName); checksum = FileHelper.getChecksum(tmpFile); size = tmpFile.length(); } catch (IOException ioe) { logger.warn("Unable to determine MIME type, size or checksum of {}", tmpFile); return null; } logger.info("Download URL: {}, address: {}, cleaned address: {}, filename: {}", new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName }); String relativePath = StringUtils.substringAfter(downloadUrl.toString(), StringUtils.substringBeforeLast(address, "/")); if (StringUtils.isBlank(relativePath)) { relativePath = downloadAddress; } final String path; final String httpPrefix = "http://"; final String httpsPrefix = "https://"; final String flexiblePrefix = "//"; if (downloadAddress.startsWith(httpsPrefix)) { path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, httpsPrefix)), "/"); } else if (downloadAddress.startsWith(httpPrefix)) { path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, httpPrefix)), "/"); } else if (downloadAddress.startsWith(flexiblePrefix)) { path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, flexiblePrefix)), "/"); } else { path = StringUtils.substringBeforeLast(relativePath, "/"); } logger.info("Relative path: {}, final path: {}", relativePath, path); if (contentType.equals("text/plain")) { contentType = StringUtils.defaultIfBlank( contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain"); } try { final String fullPath = path + "/" + fileName; File fileNode = fileExists(fullPath, checksum); if (fileNode == null) { if (ImageHelper.isImageType(fileName)) { fileNode = createImageNode(fullPath, contentType, size, checksum); } else { fileNode = createFileNode(fullPath, contentType, size, checksum); } final java.io.File imageFile = fileNode.getFileOnDisk(false); final Path imagePath = imageFile.toPath(); // rename / move file to final location Files.move(tmpFile.toPath(), imagePath); if (contentType.equals("text/css")) { processCssFileNode(fileNode, downloadUrl); } // set export flag according to user preference fileNode.setProperty(StructrApp.key(File.class, "includeInFrontendExport"), includeInExport); } else { tmpFile.delete(); } alreadyDownloaded.put(alreadyDownloadedKey, fileNode); return fileNode; } catch (final FrameworkException | IOException ex) { logger.warn("Could not create file node.", ex); } return null; }
From source file:org.structr.web.Importer.java
private Linkable downloadFile(String downloadAddress, final URL base) { final String uuid = UUID.randomUUID().toString().replaceAll("[\\-]+", ""); String contentType;//w w w . j av a2 s .c o m // Create temporary file with new uuid // FIXME: This is much too dangerous! final String relativeFilePath = File.getDirectoryPath(uuid) + "/" + uuid; final String filePath = FileHelper.getFilePath(relativeFilePath); final java.io.File fileOnDisk = new java.io.File(filePath); fileOnDisk.getParentFile().mkdirs(); long size; long checksum; URL downloadUrl; try { downloadUrl = new URL(base, downloadAddress); logger.log(Level.INFO, "Starting download from {0}", downloadUrl); copyURLToFile(downloadUrl.toString(), fileOnDisk); } catch (IOException ioe) { if (originalUrl == null || address == null) { logger.log(Level.INFO, "Cannot download from {0} without base address", downloadAddress); return null; } logger.log(Level.WARNING, "Unable to download from {0} {1}", new Object[] { originalUrl, downloadAddress }); ioe.printStackTrace(); try { // Try alternative baseUrl with trailing "/" if (address.endsWith("/")) { // don't append a second slash! logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}", new Object[] { originalUrl, address, downloadAddress }); downloadUrl = new URL(new URL(originalUrl, address), downloadAddress); } else { // append a slash logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}", new Object[] { originalUrl, address.concat("/"), downloadAddress }); downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress); } copyURLToFile(downloadUrl.toString(), fileOnDisk); } catch (MalformedURLException ex) { ex.printStackTrace(); logger.log(Level.SEVERE, "Could not resolve address {0}", address.concat("/")); return null; } catch (IOException ex) { ex.printStackTrace(); logger.log(Level.WARNING, "Unable to download from {0}", address.concat("/")); return null; } logger.log(Level.INFO, "Starting download from alternative URL {0}", downloadUrl); } downloadAddress = StringUtils.substringBefore(downloadAddress, "?"); final String fileName = PathHelper.getName(downloadAddress); if (StringUtils.isBlank(fileName)) { logger.log(Level.WARNING, "Can't figure out filename from download address {0}, aborting.", downloadAddress); return null; } // TODO: Add security features like null/integrity/virus checking before copying it to // the files repo try { contentType = FileHelper.getContentMimeType(fileOnDisk, fileName); size = fileOnDisk.length(); checksum = FileUtils.checksumCRC32(fileOnDisk); } catch (IOException ioe) { logger.log(Level.WARNING, "Unable to determine MIME type, size or checksum of {0}", fileOnDisk); return null; } String httpPrefix = "http://"; logger.log(Level.INFO, "Download URL: {0}, address: {1}, cleaned address: {2}, filename: {3}", new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName }); String relativePath = StringUtils.substringAfter(downloadUrl.toString(), StringUtils.substringBeforeLast(address, "/")); if (StringUtils.isBlank(relativePath)) { relativePath = downloadAddress; } final String path = StringUtils.substringBefore( ((downloadAddress.contains(httpPrefix)) ? StringUtils.substringAfter(downloadAddress, "http://") : relativePath), fileName); logger.log(Level.INFO, "Relative path: {0}, final path: {1}", new Object[] { relativePath, path }); if (contentType.equals("text/plain")) { contentType = StringUtils.defaultIfBlank( contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain"); } final String ct = contentType; try { FileBase fileNode = fileExists(fileName, checksum); if (fileNode == null) { if (ImageHelper.isImageType(fileName)) { fileNode = createImageNode(uuid, fileName, ct, size, checksum); } else { fileNode = createFileNode(uuid, fileName, ct, size, checksum); } if (fileNode != null) { Folder parent = FileHelper.createFolderPath(securityContext, path); if (parent != null) { fileNode.setProperty(File.parent, parent); } if (contentType.equals("text/css")) { processCssFileNode(fileNode, downloadUrl); } if (!fileNode.validatePath(securityContext, null)) { fileNode.setProperty(AbstractNode.name, fileName.concat("_").concat(FileHelper.getDateString())); } } return fileNode; } else { fileOnDisk.delete(); return fileNode; } } catch (FrameworkException | IOException fex) { logger.log(Level.WARNING, "Could not create file node.", fex); } return null; }
From source file:org.thelq.pircbotx.commands.ModeCommands.java
protected void setChannelMode(@NonNull GenericEvent event, Channel channel, @NonNull User user, char modeLetter, boolean enabled, boolean channelMode, @NonNull String arg) throws Exception { if (channel == null) { if (StringUtils.isBlank(arg)) { user.send().notice("Unknown channel, must run command in channel or in PM"); return; }/*from www . j av a 2 s .c o m*/ if (!event.getBot().getUserChannelDao().containsChannel(arg)) { user.send().notice("Unknown channel " + arg); return; } channel = event.getBot().getUserChannelDao().getChannel(arg); arg = ""; } if (enabled && channelMode && StringUtils.split(channel.getMode(), ' ')[0].contains(String.valueOf(modeLetter))) { user.send().notice("Channel is already at +" + modeLetter); } WaitForQueue queue = new WaitForQueue(event.getBot()); //Need op rights Set<UserLevel> ourLevels = event.getBot().getUserChannelDao().getLevels(channel, event.getBot().getUserBot()); if (!ourLevels.contains(UserLevel.OP)) { user.send().notice("Acquiring op from chanserv"); event.getBot().sendRaw() .rawLineNow("CHANSERV OP " + channel.getName() + " " + event.getBot().getNick()); while (true) { OpEvent opEvent = queue.waitFor(OpEvent.class, 20, TimeUnit.SECONDS); if (opEvent == null) { throw new Exception(Utils.format("Timeout waiting for op in channel {} requested by user {}", channel.getName(), user.getNick())); } log.trace("Received op " + opEvent); if (opEvent.getChannel() == channel && opEvent.getRecipient() == opEvent.getBot().getUserBot()) break; } log.debug("Sucesfully opped, waiting for mode set to succeed"); } //Change mode String modeChange = (enabled ? "+" : "-") + modeLetter + StringUtils.defaultIfBlank(" " + arg, ""); String modeSetRemove = enabled ? "set" : "removed"; event.getBot().sendRaw().rawLineNow("MODE " + channel.getName() + " " + modeChange); while (true) { ModeEvent modEvent = queue.waitFor(ModeEvent.class, 20, TimeUnit.SECONDS); if (modEvent == null) { throw new Exception(Utils.format("Timeout waiting for {} in channel {} requested by user {}", modeChange, channel.getName(), user.getNick())); } log.trace("Received mode " + modEvent); if (modEvent.getChannel() == channel && modEvent.getUser() == modEvent.getBot().getUserBot()) break; } log.debug("Mode change {} succeeded", modeChange); String unModeChange = CommandCall.PREFIX + (enabled ? "-" : "") + modeChange.substring(1); user.send().notice(Utils.format("Mode {} {}, use '/msg {} {} {}' to undo", modeChange, modeSetRemove, event.getBot().getNick(), unModeChange, channel.getName())); }
From source file:org.thelq.pircbotx.commands.NewYearsCommand.java
protected static String getExtendedNames(Collection<DateTimeZone> tzList) { if (tzList.isEmpty()) return null; //Prebuild long form of timezones long nowTime = System.currentTimeMillis(); Set<String> tzExtendedSet = Sets.newHashSet(); for (DateTimeZone curTz : tzList) { if (StringUtils.startsWithIgnoreCase(curTz.getID(), "Etc/")) continue; tzExtendedSet.add(curTz.getName(nowTime) + "(" + curTz.getShortName(nowTime) + ")"); }/* w w w .j av a 2 s. c o m*/ return StringUtils.defaultIfBlank(StringUtils.join(tzExtendedSet, ", "), null); }
From source file:org.thelq.pircbotx.commands.NewYearsCommand.java
protected static String getShortNames(Collection<DateTimeZone> tzList) { //Prebuild long form of timezones long nowTime = System.currentTimeMillis(); Set<String> tzShortSet = Sets.newHashSet(); for (DateTimeZone curTz : tzList) { if (StringUtils.startsWithIgnoreCase(curTz.getID(), "Etc/")) continue; tzShortSet.add(curTz.getShortName(nowTime)); }//from w w w .ja va 2 s . com return StringUtils.defaultIfBlank(StringUtils.join(tzShortSet, ", "), null); }
From source file:org.xenei.bloomgraph.SerializableNode.java
/** * Extract the node from the buffer./* w ww . j a va 2 s .com*/ */ protected Node extractNode() throws IOException { Node lnode = null; byte type = getType(); switch (type & 0x0F) { case _ANON: lnode = NodeFactory.createAnon(AnonId.create(decodeString(getData()))); break; case _LIT: InputStream bais = new ByteArrayInputStream(getData()); DataInputStream is = new DataInputStream(new BufferedInputStream(bais)); String lex = read(is); String lang = StringUtils.defaultIfBlank(read(is), null); String dtURI = read(is); is.close(); RDFDatatype dtype = StringUtils.isEmpty(dtURI) ? null : TypeMapper.getInstance().getTypeByName(dtURI); LiteralLabel ll = LiteralLabelFactory.create(lex, lang, dtype); lnode = NodeFactory.createLiteral(ll); break; case _URI: lnode = NodeFactory.createURI(decodeString(getData())); break; case _VAR: lnode = NodeFactory.createVariable(decodeString(getData())); break; case _ANY: lnode = Node.ANY; break; default: throw new RuntimeException(String.format("Unable to parse node: %0o", type)); } return lnode; }
From source file:org.xenei.compressedgraph.SerializableNode.java
@Override protected Node extractNode() throws IOException { Node lnode = null;/* w w w. j av a2s. co m*/ byte type = getType(); switch (type & 0x0F) { case _ANON: lnode = NodeFactory.createAnon(AnonId.create(decodeString(getData()))); break; case _LIT: InputStream bais = new ByteArrayInputStream(getData()); DataInputStream is = new DataInputStream(new BufferedInputStream(bais)); String lex = read(is); String lang = StringUtils.defaultIfBlank(read(is), null); String dtURI = read(is); is.close(); RDFDatatype dtype = StringUtils.isEmpty(dtURI) ? null : TypeMapper.getInstance().getTypeByName(dtURI); LiteralLabel ll = LiteralLabelFactory.create(lex, lang, dtype); lnode = NodeFactory.createLiteral(ll); break; case _URI: lnode = NodeFactory.createURI(decodeString(getData())); break; case _VAR: lnode = NodeFactory.createVariable(decodeString(getData())); break; case _ANY: lnode = Node.ANY; break; default: throw new RuntimeException(String.format("Unable to parse node: %0o", type)); } return lnode; }
From source file:org.xenei.jdbc4sparql.sparql.SparqlQueryBuilder.java
/** * Adds the the expression as a variable to the query. As a variable the * result will be returned from the query. * * @param expr//from w ww . j a v a2 s .co m * The expression that defines the variable * @param name * the alias for the expression, if null no alias is used. */ public void addVar(final Expr expr, final String name) { if (LOG.isDebugEnabled()) { SparqlQueryBuilder.LOG.debug("Adding Var {} as {}", expr, name); } checkBuilt(); final NodeValue nv = expr.getConstant(); if ((name != null) || (nv == null) || !nv.asNode().isVariable()) { final String s = StringUtils.defaultString(expr.getVarName()); if (StringUtils.isNotEmpty(s) && s.equals(StringUtils.defaultIfBlank(name, s))) { query.addResultVar(s); } else { if (name != null) { query.addResultVar(name, expr); } else { query.addResultVar(nv.asNode()); } } } else { query.addResultVar(nv.asNode()); } query.getResultVars(); }
From source file:org.xwiki.contrib.maven.MavenPackagerUtils.java
public Extension toExtension(Artifact artifact, Collection<Exclusion> exclusions) throws MojoExecutionException { MavenProject project = getMavenProject(artifact); Model model = project.getModel();/*from w w w .jav a 2 s . co m*/ DefaultLocalExtension extension = new DefaultLocalExtension(null, new ExtensionId(artifact.getGroupId() + ':' + artifact.getArtifactId(), artifact.getBaseVersion()), artifact.getType()); extension.setName(getPropertyString(model, PackageExtensionsMojo.MPNAME_NAME, model.getName())); extension .setSummary(getPropertyString(model, PackageExtensionsMojo.MPNAME_SUMMARY, model.getDescription())); extension.setWebsite(getPropertyString(model, PackageExtensionsMojo.MPNAME_WEBSITE, model.getUrl())); // authors for (Developer developer : model.getDevelopers()) { URL authorURL = null; if (developer.getUrl() != null) { try { authorURL = new URL(developer.getUrl()); } catch (MalformedURLException e) { // TODO: log ? } } extension.addAuthor(new DefaultExtensionAuthor( StringUtils.defaultIfBlank(developer.getName(), developer.getId()), authorURL)); } // licenses if (!model.getLicenses().isEmpty()) { for (License license : model.getLicenses()) { extension.addLicense(getExtensionLicense(license)); } } // features String featuresString = getProperty(model, PackageExtensionsMojo.MPNAME_FEATURES); if (StringUtils.isNotBlank(featuresString)) { featuresString = featuresString.replaceAll("[\r\n]", ""); extension.setFeatures(converter.<Collection<String>>convert(List.class, featuresString)); } // dependencies for (Dependency mavenDependency : model.getDependencies()) { if (!mavenDependency.isOptional() && (mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) { boolean excluded = false; for (Exclusion exclusion : exclusions) { if (mavenDependency.getArtifactId().equals(exclusion.getArtifactId()) && mavenDependency.getGroupId().equals(exclusion.getGroupId())) { excluded = true; break; } } if (!excluded) { extension.addDependency(new DefaultExtensionDependency( mavenDependency.getGroupId() + ':' + mavenDependency.getArtifactId(), new DefaultVersionConstraint(mavenDependency.getVersion()))); } } } extension.setFile(artifact.getFile()); return extension; }
From source file:org.xwiki.extension.internal.converter.ExtensionConverter.java
private MavenExtension convertToExtension(Model model) { Properties properties = (Properties) model.getProperties().clone(); String version = resolveVersion(model.getVersion(), model, false); String groupId = resolveGroupId(model.getGroupId(), model, false); DefaultMavenExtension extension = new DefaultMavenExtension(null, groupId, model.getArtifactId(), version, MavenUtils.packagingToType(model.getPackaging())); extension.setName(getPropertyString(properties, MavenUtils.MPNAME_NAME, true, model.getName())); extension/*from w ww . ja v a 2 s . c o m*/ .setSummary(getPropertyString(properties, MavenUtils.MPNAME_SUMMARY, true, model.getDescription())); extension.setWebsite(getPropertyString(properties, MavenUtils.MPNAME_WEBSITE, true, model.getUrl())); // authors for (Developer developer : model.getDevelopers()) { URL authorURL = null; if (developer.getUrl() != null) { try { authorURL = new URL(developer.getUrl()); } catch (MalformedURLException e) { // TODO: log ? } } extension.addAuthor(new DefaultExtensionAuthor( StringUtils.defaultIfBlank(developer.getName(), developer.getId()), authorURL)); } // licenses for (License license : model.getLicenses()) { extension.addLicense(getExtensionLicense(license)); } // scm Scm scm = model.getScm(); if (scm != null && (scm.getConnection() != null || scm.getDeveloperConnection() != null || scm.getUrl() != null)) { ExtensionScmConnection connection = MavenUtils.toExtensionScmConnection(scm.getConnection()); ExtensionScmConnection developerConnection = MavenUtils .toExtensionScmConnection(scm.getDeveloperConnection()); extension.setScm(new DefaultExtensionScm(scm.getUrl(), connection, developerConnection)); } // issue management IssueManagement issueManagement = model.getIssueManagement(); if (issueManagement != null && issueManagement.getUrl() != null) { extension.setIssueManagement( new DefaultExtensionIssueManagement(issueManagement.getSystem(), issueManagement.getUrl())); } // features String featuresString = getProperty(properties, MavenUtils.MPNAME_FEATURES, true); if (StringUtils.isNotBlank(featuresString)) { featuresString = featuresString.replaceAll("[\r\n]", ""); extension.setFeatures(this.converter.<Collection<String>>convert(List.class, featuresString)); } // category String categoryString = getProperty(properties, MavenUtils.MPNAME_CATEGORY, true); if (StringUtils.isNotBlank(categoryString)) { extension.setCategory(categoryString); } // repositories List<ExtensionRepositoryDescriptor> repositories; List<Repository> mavenRepositories = model.getRepositories(); if (!mavenRepositories.isEmpty()) { repositories = new ArrayList<>(mavenRepositories.size()); for (Repository mavenRepository : mavenRepositories) { try { repositories.add(new DefaultExtensionRepositoryDescriptor(mavenRepository.getId(), "maven", new URI(mavenRepository.getUrl()))); } catch (URISyntaxException e) { // TODO: log ? } } } else { repositories = null; } extension.setRepositories(repositories); // dependencies for (Dependency mavenDependency : model.getDependencies()) { if (!mavenDependency.isOptional() && (mavenDependency.getScope() == null || mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) { String dependencyGroupId = resolveGroupId(mavenDependency.getGroupId(), model, true); String dependencyArtifactId = mavenDependency.getArtifactId(); String dependencyClassifier = mavenDependency.getClassifier(); String dependencyVersion = resolveVersion(mavenDependency.getVersion(), model, true); DefaultExtensionDependency extensionDependency = new DefaultMavenExtensionDependency( MavenUtils.toExtensionId(dependencyGroupId, dependencyArtifactId, dependencyClassifier), new DefaultVersionConstraint(dependencyVersion), mavenDependency); extension.setRepositories(repositories); extension.addDependency(extensionDependency); } } // various properties extension.putProperty(MavenUtils.PKEY_MAVEN_MODEL, model); for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); if (key.startsWith("xwiki.extension.")) { extension.putProperty(key, entry.getValue()); } } return extension; }