List of usage examples for org.apache.commons.lang3 StringUtils isNoneBlank
public static boolean isNoneBlank(final CharSequence... css)
Checks if none of the CharSequences are blank ("") or null and whitespace only..
StringUtils.isNoneBlank(null) = false StringUtils.isNoneBlank(null, "foo") = false StringUtils.isNoneBlank(null, null) = false StringUtils.isNoneBlank("", "bar") = false StringUtils.isNoneBlank("bob", "") = false StringUtils.isNoneBlank(" bob ", null) = false StringUtils.isNoneBlank(" ", "bar") = false StringUtils.isNoneBlank("foo", "bar") = true
From source file:com.sludev.mssqlapplylog.MSSQLApplyLog.java
@Override public Integer call() throws Exception { Integer res = 0;// w w w . j a v a 2s. co m String backupDirStr = config.getBackupDirStr(); String fullBackupPathStr = config.getFullBackupPathStr(); String fullBackupDatePatternStr = config.getFullBackupDatePatternStr(); String laterThanStr = config.getLaterThanStr(); String fullBackupPatternStr = config.getFullBackupPatternStr(); String logBackupPatternStr = config.getLogBackupPatternStr(); String logBackupDatePatternStr = config.getLogBackupDatePatternStr(); String sqlHost = config.getSqlHost(); String sqlDb = config.getSqlDb(); String sqlUser = config.getSqlUser(); String sqlPass = config.getSqlPass(); String sqlURL = config.getSqlUrl(); String sqlProcessUser = config.getSqlProcessUser(); boolean useLogFileLastMode = BooleanUtils.isTrue(config.getUseLogFileLastMode()); boolean doFullRestore = BooleanUtils.isTrue(config.getDoFullRestore()); boolean monitorLogBackupDir = BooleanUtils.isTrue(config.getMonitorLogBackupDir()); Path backupsDir = null; Instant laterThan = null; Path fullBackupPath = null; // Validate the Log Backup Directory if (StringUtils.isBlank(backupDirStr)) { LOGGER.error("Invalid blank/empty backup directory"); return 1; } try { backupsDir = Paths.get(backupDirStr); } catch (Exception ex) { LOGGER.error(String.format("Error parsing Backup Directory '%s'", backupDirStr), ex); return 1; } if (Files.notExists(backupsDir)) { LOGGER.error(String.format("Invalid non-existant backup directory '%s'", backupsDir)); return 1; } if (StringUtils.isBlank(logBackupPatternStr)) { LOGGER.warn(String.format( "\"Log Backup Pattern\" cannot be empty. Defaulting to " + "%s regex in backup directory", DEFAULT_LOG_FILE_PATTERN_STR)); logBackupPatternStr = DEFAULT_LOG_FILE_PATTERN_STR; } if (StringUtils.isNoneBlank(fullBackupPathStr)) { fullBackupPath = Paths.get(fullBackupPathStr); if (Files.notExists(fullBackupPath) || Files.isRegularFile(fullBackupPath) == false) { LOGGER.error(String.format("Invalid Full Backup file '%s'", backupDirStr)); return 1; } } if (StringUtils.isNoneBlank(fullBackupDatePatternStr) && StringUtils.isBlank(laterThanStr) && fullBackupPath != null) { // Retrieve the "Later Than" date from the full backup file name laterThan = FSHelper.getTimestampFromFilename(fullBackupPatternStr, fullBackupDatePatternStr, 1, fullBackupPath); if (laterThan == null) { LOGGER.error("'Later Than' cannot be null"); return 1; } } else { // Use the "Later Than" timestamp from the command line or properties // file. try { laterThan = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(laterThanStr)); } catch (Exception ex) { LOGGER.error(String.format("Error parsing 'Later Than' time '%s'", laterThanStr), ex); } } try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); } catch (ClassNotFoundException ex) { LOGGER.error("Error loading SQL Server driver [ net.sourceforge.jtds.jdbc.Driver ]", ex); return 1; } if (StringUtils.isBlank(sqlURL)) { // Build the SQL URL sqlURL = String.format("jdbc:jtds:sqlserver://%s;DatabaseName=master", sqlHost); } Properties props = new Properties(); props.setProperty("user", sqlUser); props.setProperty("password", sqlPass); try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) { if (conn == null) { LOGGER.error("Connection to MSSQL failed."); return 1; } if (doFullRestore) { LOGGER.info(String.format("\nStarting full restore of '%s'...", fullBackupPathStr)); StopWatch sw = new StopWatch(); sw.start(); String strDevice = fullBackupPathStr; String query = String.format("RESTORE DATABASE %s FROM DISK='%s' WITH NORECOVERY, REPLACE", sqlDb, strDevice); Statement stmt = null; try { stmt = conn.createStatement(); } catch (SQLException ex) { LOGGER.debug("Error creating statement", ex); return 1; } try { boolean sqlRes = stmt.execute(query); } catch (SQLException ex) { LOGGER.error(String.format("Error executing...\n'%s'", query), ex); return 1; } sw.stop(); LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString())); } } catch (SQLException ex) { LOGGER.error("SQL Exception restoring the full backup", ex); } // Filter the log files. // Loop multiple times to catch new logs that have been transferred // while we process. List<Path> files = null; do { try { files = FSHelper.listLogFiles(backupsDir, laterThan, useLogFileLastMode, logBackupPatternStr, logBackupDatePatternStr, files); } catch (IOException ex) { LOGGER.error("Log Backup file filter/sort failed", ex); return 1; } if (files == null || files.isEmpty()) { LOGGER.debug("No Log Backup files found this iteration."); continue; } StringBuilder msg = new StringBuilder(); for (Path file : files) { msg.append(String.format("file : '%s'\n", file)); } LOGGER.debug(msg.toString()); // Restore all log files try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) { for (Path p : files) { try { MSSQLHelper.restoreLog(p, sqlProcessUser, sqlDb, conn); } catch (SQLException ex) { LOGGER.error(String.format("SQL Exception restoring the log backup '%s'", p), ex); } } } catch (SQLException ex) { LOGGER.error("SQL Exception restoring the log backup", ex); } } while (files != null && files.isEmpty() == false); if (monitorLogBackupDir) { // Watch for new log files List<Path> paths = new ArrayList(); paths.add(backupsDir); final Watch watch; final String currSQLDb = sqlDb; final String currSQLProcUser = sqlProcessUser; final String currSQLURL = sqlURL; final String currLogBackupPatternStr = logBackupPatternStr; try { watch = Watch.from(paths); watch.processEvents((WatchEvent<Path> event, Path path) -> { int watchRes = 0; if (event.kind() != StandardWatchEventKinds.ENTRY_CREATE) { return watchRes; } Pattern fileMatcher = Pattern.compile(currLogBackupPatternStr); if (fileMatcher.matcher(path.getFileName().toString()).matches()) { try (Connection conn = MSSQLHelper.getConn(currSQLURL, props)) { MSSQLHelper.restoreLog(path, currSQLProcUser, currSQLDb, conn); } catch (SQLException ex) { // There's really no recovering from a failed log backup LOGGER.error("SQL Exception restoring the log backup", ex); System.exit(1); } } return watchRes; }); } catch (IOException | FileCheckException ex) { LOGGER.error(String.format("Error watching backup directory...\n'%s'", backupsDir), ex); return 1; } catch (InterruptedException ex) { LOGGER.info(String.format("Interrupted watching backup directory...\n'%s'", backupsDir), ex); } } return res; }
From source file:com.cisco.oss.foundation.message.HornetQMessageProducer.java
@Override public void sendMessage(byte[] message, Map<String, Object> messageHeaders) { String groupIdentifier = null; if (StringUtils.isNoneBlank(groupId) && messageHeaders.get(groupId) != null) { groupIdentifier = messageHeaders.get(groupId).toString(); }/*from w w w. j a v a2 s . c o m*/ try { ClientMessage clientMessage = getClientMessage(messageHeaders, groupIdentifier); clientMessage.setExpiration(System.currentTimeMillis() + expiration); clientMessage.getBodyBuffer().writeBytes(message); getProducer(groupIdentifier).send(clientMessage); } catch (Exception e) { LOGGER.error("can't send message: {}", e, e); throw new QueueException(e); } }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
public void saveAttachment(HttpServletRequest request, String user_id, int main_id, JpaAttachment.Type file_type, String description) throws BusinessException { try {/*from w w w . ja va 2 s.c om*/ CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null && !file.isEmpty()) { String oriFileName = file.getOriginalFilename(); String fn = file.getName(); if (StringUtils.isNoneBlank(oriFileName)) { String storeName = GlobalMethods .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes()); Pair<String, String> p = FileHelper.getUploadFileName(path, storeName += FileHelper.getFileExtension(oriFileName, true)); File localFile = new File(p.getLeft()); file.transferTo(localFile); AttachmentExample example = new AttachmentExample(); AttachmentExample.Criteria criteria = example.createCriteria(); criteria.andMainIdEqualTo(main_id); criteria.andUserIdEqualTo(user_id); criteria.andTypeEqualTo(JpaAttachment.Type.user_qualifi.ordinal()); List<Attachment> attachments = attachmentMapper.selectByExample(example); if (attachments.size() > 0) { Attachment t = attachments.get(0); t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); } else { Attachment t = new Attachment(); if (StringUtils.isNotBlank(description)) { t.setDescription(description); } t.setMainId(main_id); if (StringUtils.equals(fn, "licensefile")) { t.setType(JpaAttachment.Type.license.ordinal()); } else if (fn.indexOf("qua") != -1) { t.setType(JpaAttachment.Type.u_fj.ordinal()); } else if (StringUtils.equals(fn, "taxfile")) { t.setType(JpaAttachment.Type.tax.ordinal()); } else if (StringUtils.equals(fn, "taxpayerfile")) { t.setType(JpaAttachment.Type.taxpayer.ordinal()); } else if (StringUtils.equals(fn, "user_license")) { t.setType(JpaAttachment.Type.user_license.ordinal()); } else if (StringUtils.equals(fn, "user_code")) { t.setType(JpaAttachment.Type.user_code.ordinal()); } else if (StringUtils.equals(fn, "user_tax")) { t.setType(JpaAttachment.Type.user_tax.ordinal()); } else { t.setType(file_type.ordinal()); } t.setCreated(new Date()); t.setUpdated(t.getCreated()); t.setName(oriFileName); t.setUrl(p.getRight()); t.setUserId(user_id); attachmentMapper.insert(t); } } } } } } catch (Exception e) { log.error("saveAttachment", e); throw new BusinessException("saveAttachment-error", e); } }
From source file:cz.lbenda.dataman.db.sql.SQLEditorController.java
/** Return text which will be executed. * @param onCaretPosition return executed text on caret position */ public String[] getExecutedText(boolean onCaretPosition) { CodeArea codeArea = textEditor.getCodeArea(); String text = textEditor.getSelectedText(); if (text == null || "".equals(text)) { text = textEditor.getText();//www . j a v a 2s . c o m if (onCaretPosition) { int caretPosition = codeArea.caretPositionProperty().getValue(); String bf = "", af = ""; if (caretPosition > 0) { bf = text.substring(0, caretPosition); } if (caretPosition < text.length()) { af = text.substring(caretPosition, text.length()); } String[] bfs = bf.split("\n"); String[] afs = af.split("\n"); StringBuilder sb = new StringBuilder(); boolean rowStart = caretPosition == 0 || bf.charAt(bf.length() - 1) == '\n'; boolean skipBf = caretPosition == 0; if (!skipBf && rowStart) { int prevRecord = bf.substring(0, bf.length() - 1).lastIndexOf("\n"); if (prevRecord >= 0) { skipBf = StringUtils.isBlank(bf.substring(prevRecord, bf.length() - 1)); } } if (!skipBf) { for (int i = bfs.length - 1; i >= 0 && StringUtils.isNoneBlank(bfs[i]); i--) { if (i == bfs.length - 1 && !rowStart) { sb.insert(0, bfs[i]); } else { sb.insert(0, bfs[i] + "\n"); } } } for (int i = 0; i < afs.length && StringUtils.isNoneBlank(afs[i]); i++) { sb.append(afs[i]).append("\n"); } text = sb.toString(); } } return SQLSExecutor.splitSQLS(text); }
From source file:in.hatimi.nosh.support.CommandExecutor.java
private String createSyntax() { StringBuilder sb = new StringBuilder(); sb.append(names[0]);/*www . j a va2s. c o m*/ for (int i = 1; i < names.length; i++) { sb.append('|').append(names[i]); } if (StringUtils.isNoneBlank(syntax)) { sb.append(' ').append(syntax); } return sb.toString(); }
From source file:cop.raml.processor.rest.SpringRestImpl.java
private static String getClassRequestPath(TypeElement classElement) { if (classElement == null || classElement.getKind() != ElementKind.CLASS) return null; RestController annotation = classElement.getAnnotation(RestController.class); return annotation != null && StringUtils.isNoneBlank(annotation.value()) ? annotation.value() : null; }
From source file:edu.sampleu.main.AgendaEditorAddRuleAft.java
protected void addRulePropositionInfo(String childIndex, String description, String category, String propTerm, String propComparison, String propositionValue) throws Exception { String propTreeRootPath = NEW_DATA_OBJ_PATH + "agendaItemLine.rule.propositionTree.rootElement."; String propTreeChildPath = propTreeRootPath + "children[" + childIndex + "]."; String propositionPath = propTreeChildPath + "data.proposition."; if (StringUtils.isNoneBlank(description)) { waitAndTypeByName(propositionPath + "description", description); }// www .j a va 2 s . c o m if (StringUtils.isNoneBlank(category)) { waitAndSelectByName(propositionPath + "categoryId", category); } if (StringUtils.isNoneBlank(propTerm)) { waitAndSelectByName(propositionPath + "parameters[0].value", propTerm); } if (StringUtils.isNoneBlank(propComparison)) { waitAndSelectByName(propositionPath + "parameters[2].value", propComparison); unfocusElement(); Thread.sleep(3000); // need time for next input to be reloaded } if (StringUtils.isNoneBlank(propositionValue)) { waitAndTypeByName(propositionPath + "parameters[1].value", propositionValue); } }
From source file:com.cisco.oss.foundation.message.HornetQMessageConsumer.java
private String createQueueIfNeeded() { Configuration subset = configuration.subset(consumerName); queueName = subset.getString("queue.name"); String filter = subset.getString("queue.filter", ""); boolean isDurable = subset.getBoolean("queue.isDurable", true); boolean isSubscription = subset.getBoolean("queue.isSubscription", false); String subscribedTo = isSubscription ? subset.getString("queue.subscribedTo", "") : queueName; if (isSubscription) { if (StringUtils.isBlank(subscribedTo)) { throw new QueueException( "Check Configuration - missing required subscribedTo name for consumerThreadLocal[" + consumerName + "] as it is marked as isSubscription=true"); }/* w ww. j ava2 s . com*/ // subscribedTo = "foundation." + subscribedTo; } if (StringUtils.isBlank(queueName)) { String rpmSoftwareName = System.getenv("_RPM_SOFTWARE_NAME"); String artifactId = System.getenv("_ARTIFACT_ID"); String componentName = ""; if (StringUtils.isNoneBlank(rpmSoftwareName)) { componentName = rpmSoftwareName; } else { if (StringUtils.isNoneBlank(artifactId)) { componentName = artifactId; } } if (StringUtils.isNoneBlank(componentName)) { queueName = componentName + "_" + subscribedTo; } if (StringUtils.isBlank(queueName)) { throw new QueueException( "Check Configuration - missing required queue name for consumerThreadLocal: " + consumerName); } } String realQueueName = /*"foundation." + */queueName; boolean queueExists = false; for (Pair<ClientSession, SessionFailureListener> clientSessionSessionFailureListenerPair : HornetQMessagingFactory .getSession(FoundationQueueConsumerFailureListener.class)) { ClientSession clientSession = clientSessionSessionFailureListenerPair.getLeft(); try { queueExists = clientSession.queueQuery(new SimpleString(realQueueName)).isExists(); if (!queueExists) { clientSession.createQueue(isSubscription ? subscribedTo : realQueueName, realQueueName, filter, isDurable); } } catch (HornetQException e) { try { clientSession.createQueue(isSubscription ? subscribedTo : realQueueName, realQueueName, filter, isDurable); } catch (HornetQException e1) { throw new QueueException("Can't create queue: " + realQueueName + ". Error: " + e1, e1); } } } return realQueueName; }
From source file:io.github.robwin.swagger2markup.builder.document.OverviewDocument.java
/** * Builds the document header of the swagger model */// w w w. jav a 2 s . c o m private void overview() { Info info = swagger.getInfo(); this.markupDocBuilder.documentTitle(info.getTitle()); this.markupDocBuilder.sectionTitleLevel1(OVERVIEW); if (StringUtils.isNotBlank(info.getDescription())) { this.markupDocBuilder.textLine(info.getDescription()); this.markupDocBuilder.newLine(); } if (StringUtils.isNotBlank(info.getVersion())) { this.markupDocBuilder.sectionTitleLevel2(CURRENT_VERSION); this.markupDocBuilder.textLine(VERSION + info.getVersion()); this.markupDocBuilder.newLine(); } Contact contact = info.getContact(); if (contact != null) { this.markupDocBuilder.sectionTitleLevel2(CONTACT_INFORMATION); if (StringUtils.isNotBlank(contact.getName())) { this.markupDocBuilder.textLine(CONTACT_NAME + contact.getName()); } if (StringUtils.isNotBlank(contact.getEmail())) { this.markupDocBuilder.textLine(CONTACT_EMAIL + contact.getEmail()); } this.markupDocBuilder.newLine(); } License license = info.getLicense(); if (license != null && (StringUtils.isNotBlank(license.getName()) || StringUtils.isNotBlank(license.getUrl()))) { this.markupDocBuilder.sectionTitleLevel2(LICENSE_INFORMATION); if (StringUtils.isNotBlank(license.getName())) { this.markupDocBuilder.textLine(LICENSE + license.getName()); } if (StringUtils.isNotBlank(license.getUrl())) { this.markupDocBuilder.textLine(LICENSE_URL + license.getUrl()); } this.markupDocBuilder.newLine(); } if (StringUtils.isNotBlank(info.getTermsOfService())) { this.markupDocBuilder.textLine(TERMS_OF_SERVICE + info.getTermsOfService()); this.markupDocBuilder.newLine(); } this.markupDocBuilder.sectionTitleLevel2(URI_SCHEME); if (StringUtils.isNotBlank(swagger.getHost())) { this.markupDocBuilder.textLine(HOST + swagger.getHost()); } if (StringUtils.isNotBlank(swagger.getBasePath())) { this.markupDocBuilder.textLine(BASE_PATH + swagger.getBasePath()); } if (CollectionUtils.isNotEmpty(swagger.getSchemes())) { List<String> schemes = new ArrayList<>(); for (Scheme scheme : swagger.getSchemes()) { schemes.add(scheme.toString()); } this.markupDocBuilder.textLine(SCHEMES + StringUtils.join(schemes, ", ")); } this.markupDocBuilder.newLine(); if (CollectionUtils.isNotEmpty(swagger.getTags())) { this.markupDocBuilder.sectionTitleLevel2(TAGS); List<String> tags = new ArrayList<>(); for (Tag tag : swagger.getTags()) { String name = tag.getName(); String description = tag.getDescription(); if (StringUtils.isNoneBlank(description)) { tags.add(name + ": " + description); } tags.add(name); } this.markupDocBuilder.unorderedList(tags); this.markupDocBuilder.newLine(); } if (CollectionUtils.isNotEmpty(swagger.getConsumes())) { this.markupDocBuilder.sectionTitleLevel2(CONSUMES); this.markupDocBuilder.unorderedList(swagger.getConsumes()); this.markupDocBuilder.newLine(); } if (CollectionUtils.isNotEmpty(swagger.getProduces())) { this.markupDocBuilder.sectionTitleLevel2(PRODUCES); this.markupDocBuilder.unorderedList(swagger.getProduces()); this.markupDocBuilder.newLine(); } }
From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProvider.java
/** * Create FileSystem event hook//from w w w .ja va 2s . co m * * @param rootName * @param fileSystemOptions * @return * @throws FileSystemException */ @Override protected FileSystem doCreateFileSystem(FileName rootName, FileSystemOptions fileSystemOptions) throws FileSystemException { SS3FileSystem fileSystem = null; GenericFileName genRootName = (GenericFileName) rootName; AWSCredentials storageCreds; AmazonS3Client client; FileSystemOptions currFSO; UserAuthenticator ua; if (fileSystemOptions == null) { currFSO = getDefaultFileSystemOptions(); ua = SS3FileSystemConfigBuilder.getInstance().getUserAuthenticator(currFSO); } else { currFSO = fileSystemOptions; ua = DefaultFileSystemConfigBuilder.getInstance().getUserAuthenticator(currFSO); } UserAuthenticationData authData = null; try { authData = ua.requestAuthentication(AUTHENTICATOR_TYPES); String currAcct = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(genRootName.getUserName()))); String currKey = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(genRootName.getPassword()))); storageCreds = new BasicAWSCredentials(currAcct, currKey); client = new AmazonS3Client(storageCreds); if (StringUtils.isNoneBlank(endpoint)) { client.setEndpoint(endpoint); } if (region != null) { client.setRegion(region); } fileSystem = new SS3FileSystem(genRootName, client, fileSystemOptions); } finally { UserAuthenticatorUtils.cleanup(authData); } return fileSystem; }