下面列出了org.apache.commons.lang3.StringUtils#isBlank ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void handleAgentHeartBeat(
final String streamId,
final AgentHeartBeat agentHeartBeat
) {
// Pull the record, if one exists
final AgentStreamRecord agentStreamRecord;
synchronized (activeStreamsMap) {
agentStreamRecord = activeStreamsMap.get(streamId);
}
final String claimedJobId = agentHeartBeat.getClaimedJobId();
if (agentStreamRecord == null) {
log.warn("Received heartbeat from an unknown stream");
} else if (StringUtils.isBlank(claimedJobId)) {
log.warn("Ignoring heartbeat lacking job id");
} else {
log.debug("Received heartbeat for job: {} (stream id: {})", claimedJobId, streamId);
final boolean isFirstHeartBeat = agentStreamRecord.updateRecord(claimedJobId);
if (isFirstHeartBeat) {
log.info("Received first heartbeat for job: {} (stream id: {})", claimedJobId, streamId);
}
this.agentConnectionTrackingService.notifyHeartbeat(streamId, claimedJobId);
}
}
private void updateConnectionTypeLabels(String newValue) {
GitSyncDetails newDetails = new GitSyncDetails(newValue, "", "");
if (newDetails.isSsh()) {
usernameLbl.setText("Ssh File");
username.setPromptText("insert id_rsa file here...");
if (StringUtils.isBlank(username.getText())) {
var id_rsa = Paths.get(System.getProperty("user.home"), ".ssh", "id_rsa");
if (id_rsa.toFile().exists()){
username.setText(id_rsa.toString());
}
}
passwordLbl.setText("Ssh File Password");
passwordOrToken.setPromptText("Enter Ssh File password or leave blank...");
} else {
usernameLbl.setText("Username");
username.setPromptText("enter username here...");
passwordLbl.setText("Password/Token");
passwordOrToken.setPromptText("Enter password or token here...");
}
}
public void startConnect() throws InterruptedException
{
if (StringUtils.isBlank(remoteSdp))
{
throw new NullPointerException(
"Please exchange sdp information with peer before start connect! ");
}
agent.startConnectivityEstablishment();
// agent.runInStunKeepAliveThread();
synchronized (listener)
{
listener.wait();
}
}
/**
* {@inheritDoc}
*/
@Override
public String getGoogleAuthenticationUrl() {
String clientId = sakaiProxy.getServerConfigurationParameter("profile2.integration.google.client-id", null);
if(StringUtils.isBlank(clientId)){
log.error("Google integration not properly configured. Please set the client id");
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("https://accounts.google.com/o/oauth2/auth?");
sb.append("client_id=");
sb.append(clientId);
sb.append("&redirect_uri=");
sb.append(ProfileConstants.GOOGLE_REDIRECT_URI);
sb.append("&response_type=code");
sb.append("&scope=");
sb.append(ProfileConstants.GOOGLE_DOCS_SCOPE);
return sb.toString();
}
private String readRequiredAttribute(XMLStreamReader reader, String localName) throws XMLStreamException {
String value = null;
for(int i = 0; i < reader.getAttributeCount(); i++) {
String attributeName = reader.getAttributeLocalName(i);
if(attributeName.equals(localName)) {
value = reader.getAttributeValue(i);
break;
}
}
if(StringUtils.isBlank(value)) {
throw new XMLStreamException("Required attribute " + localName + " is missing");
}
return value;
}
/**
* This function listens at endpoint "/api/ValidateTwitterFollowerCount". Two ways to invoke it using "curl" command in bash:
* 1. curl -d "HTTP Body" {your host}/api/ValidateTwitterFollowerCount
* 2. curl {your host}/api/ValidateTwitterFollowerCount?name=HTTP%20Query
*/
@FunctionName("ValidateTwitterFollowerCount")
public HttpResponseMessage run(
@HttpTrigger(name = "request", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
@SendGridOutput(name = "outputEmail",
apiKey = "SendGridAPIKey",
from = "[email protected]",
to = "your_email_address",
subject = "{Name} with {followersCount} followers has posted a tweet",
text = "{tweettext}") OutputBinding<Mail> outputEmail,
final ExecutionContext context) {
context.getLogger().info("Java HTTP trigger processed a request.");
TwitterMessage twitterMessage = null;
String json = request.getBody().orElse(null);
if (json != null) {
ObjectMapper mapper = new ObjectMapper();
try {
twitterMessage = mapper.readValue(json, TwitterMessage.class);
} catch (IOException e) {
twitterMessage = new TwitterMessage();
}
}
else {
twitterMessage = new TwitterMessage();
twitterMessage.setFollowersCount(Integer.parseInt(request.getQueryParameters().get("followersCount")));
twitterMessage.setTweetText(request.getQueryParameters().get("tweettext"));
twitterMessage.setName(request.getQueryParameters().get("Name"));
}
if (twitterMessage.getFollowersCount() == 0
|| StringUtils.isBlank(twitterMessage.getTweetText())
|| StringUtils.isBlank(twitterMessage.getName())) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
} else {
outputEmail.setValue(new Mail());
return request.createResponseBuilder(HttpStatus.OK).body("Success").build();
}
}
/**
* <p>Convert a <code>String</code> to a <code>BigDecimal</code>.</p>
*
* <p>Returns <code>null</code> if the string is <code>null</code>.</p>
*
* @param str a <code>String</code> to convert, may be null
* @return converted <code>BigDecimal</code> (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static BigDecimal createBigDecimal(String str) {
if (str == null) {
return null;
}
// handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
if (StringUtils.isBlank(str)) {
throw new NumberFormatException("A blank string is not a valid number");
}
// this is protection for poorness in java.lang.BigDecimal.
// it accepts this as a legal value, but it does not appear
// to be in specification of class. OS X Java parses it to
// a wrong value.
return new BigDecimal(str);
}
@RequiresPermissions("sys:menu:edit")
@PostMapping("edit")
@ResponseBody
@SysLog("保存编辑菜单数据")
public RestResponse edit(Menu menu){
if(menu.getId() == null){
return RestResponse.failure("菜单ID不能为空");
}
if (StringUtils.isBlank(menu.getName())) {
return RestResponse.failure("菜单名称不能为空");
}
Menu oldMenu = menuService.selectById(menu.getId());
if(!oldMenu.getName().equals(menu.getName())) {
if(menuService.getCountByName(menu.getName())>0){
return RestResponse.failure("菜单名称已存在");
}
}
if (StringUtils.isNotBlank(menu.getPermission())) {
if(!oldMenu.getPermission().equals(menu.getPermission())) {
if (menuService.getCountByPermission(menu.getPermission()) > 0) {
return RestResponse.failure("权限标识已经存在");
}
}
}
if(menu.getSort() == null){
return RestResponse.failure("排序值不能为空");
}
menuService.saveOrUpdateMenu(menu);
return RestResponse.success();
}
/**
*
* @param orgi
* @param agent
* @param p
* @param ps
* @return
*/
public static PageImpl<UKDataBean> aiidsearch(String orgi , String id){
BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
queryBuilder.must(termQuery("orgi", orgi)) ;
queryBuilder.must(termQuery("validresult", "valid")) ;
queryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAI.toString())) ;
StringBuffer strb = new StringBuffer();
if(!StringUtils.isBlank(id)) {
strb.append(id) ;
}else {
strb.append(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
}
queryBuilder.must(termQuery("id",strb.toString())) ;
return search(queryBuilder,0, 1);
}
/**
* Downloads an external resource and returns a Resource instance or null
* if the download has failed
* @param path
* @param mediaAttributeValue
* @return
*/
private boolean getExternalResourceAndAdapt(
String path,
@Nullable List<CSSMediaQuery> mediaList) {
if (StringUtils.isBlank(path)) {
return false;
}
// When an external css is found on the html, we start by getting the
// associated resource from the fetched Stylesheet and we populate the
// set of relatedExternalCssSet (needed to create the relation between the
// SSP and the css at the end of the adaptation)
StylesheetContent stylesheetContent = getExternalStylesheet(path);
if (stylesheetContent != null) {
if (stylesheetContent.getAdaptedContent() == null) {
Resource localResource;
localResource = new CSSResourceImpl(
stylesheetContent.getSource(),
0,
new ExternalRsrc());
currentLocalResourcePath = getCurrentResourcePath(path);
adaptContent(
stylesheetContent,
localResource,
currentLocalResourcePath,
mediaList);
}
relatedExternalCssSet.add(stylesheetContent);
LOGGER.debug("encountered external css : " +
path + " " +
relatedExternalCssSet.size() + " in " +getSSP().getURI());
return true;
}
return false;
}
public static List<Object> toList(String value, Supplier<List<Object>> defaultSuppler) {
if (StringUtils.isBlank(value)) {
return defaultSuppler.get();
}
try {
return toJavaObject(value, List.class);
} catch (Exception e) {
log.error("toList exception\n" + value, e);
}
return defaultSuppler.get();
}
@Override
public List<Bundle> getBundlesByBucket(final String bucketIdentifier) {
if (StringUtils.isBlank(bucketIdentifier)) {
throw new IllegalArgumentException("Bucket identifier cannot be null or blank");
}
final BucketEntity existingBucket = getBucketEntity(bucketIdentifier);
final List<BundleEntity> bundleEntities = metadataService.getBundlesByBucket(bucketIdentifier);
return bundleEntities.stream().map(b -> ExtensionMappings.map(existingBucket, b)).collect(Collectors.toList());
}
public static <T> List<T> toJavaObjectList(String value, Class<T> tClass, Supplier<List<T>> defaultSupplier) {
try {
if (StringUtils.isBlank(value)) {
return defaultSupplier.get();
}
JavaType javaType = OBJECT_MAPPER.get().getTypeFactory().constructParametricType(List.class, tClass);
return OBJECT_MAPPER.get().readValue(value, javaType);
} catch (Throwable e) {
log.error(String.format("toJavaObjectList exception \n%s\n%s", value, tClass), e);
}
return defaultSupplier.get();
}
public FileDetectorOption getFileDetectorOption() {
String fileDetectorString = getPropertyAsString(REMOTE_FILE_DETECTOR);
if (StringUtils.isBlank(fileDetectorString)) {
LOGGER.warn("No remote file detector configured, reverting to default of useless file detector");
return FileDetectorOption.USELESS;
}
return FileDetectorOption.valueOf(fileDetectorString);
}
private User createUserIfNotExist(UserProfile userProfile, String langKey, String providerId) {
String email = userProfile.getEmail();
String userName = userProfile.getUsername();
if (StringUtils.isBlank(email) && StringUtils.isBlank(userName)) {
log.error("Cannot create social user because email and login are null");
throw new IllegalArgumentException("Email and login cannot be null");
}
if (StringUtils.isBlank(email) && userRepository.findOneByLogin(userName).isPresent()) {
log.error("Cannot create social user because email is null and login already exist, login -> {}", userName);
throw new IllegalArgumentException("Email cannot be null with an existing login");
}
Optional<User> user = userRepository.findOneByEmail(email);
if (user.isPresent()) {
log.info("User already exist associate the connection to this account");
return user.get();
}
String login = getLoginDependingOnProviderId(userProfile, providerId);
String encryptedPassword = passwordEncoder.encode(RandomStringUtils.random(10));
Set<Authority> authorities = new HashSet<>(1);
authorities.add(authorityRepository.findOne("ROLE_USER"));
User newUser = new User();
newUser.setLogin(login);
newUser.setPassword(encryptedPassword);
newUser.setFirstName(userProfile.getFirstName());
newUser.setLastName(userProfile.getLastName());
newUser.setEmail(email);
newUser.setActivated(true);
newUser.setAuthorities(authorities);
newUser.setLangKey(langKey);
return userRepository.save(newUser);
}
public boolean hasContent(String value) {
return !StringUtils.isBlank(value);
}
@Override
public void execCmd(String[] args) throws ParseException, NodeException {
Options options = new Options();
options.addOption(ARG_TARGET, true, "Input target address");
options.addOption(ARG_CONSENTER, true, "Input consenter's IP and port");
options.addOption(ARG_GROUP_ID, true, "Input group id");
options.addOption(ARG_SC_NAME, true, "Input contract name");
options.addOption(ARG_INPUT, true, "Input contract parameter");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
String defaultValue = "";
String targetAddress = null;
if (cmd.hasOption(ARG_TARGET)) {
targetAddress = cmd.getOptionValue(ARG_TARGET, defaultValue);
log.info("TargetAddress: " + targetAddress);
}
//consenter信息
String consenter = null;
if (cmd.hasOption(ARG_CONSENTER)) {
consenter = cmd.getOptionValue(ARG_CONSENTER, defaultValue);
log.info("Consenter: " + consenter);
}
//群组信息
String groupId = null;
if (cmd.hasOption(ARG_GROUP_ID)) {
groupId = cmd.getOptionValue(ARG_GROUP_ID, defaultValue);
log.info("GroupId: " + groupId);
}
//解析出合约名称
String scName = null;
if (cmd.hasOption(ARG_SC_NAME)) {
scName = cmd.getOptionValue(ARG_SC_NAME, defaultValue);
log.info("Contract name: " + scName);
}
SmartContractPackage.SmartContractInput input = getSmartContractInput(cmd, ARG_INPUT, defaultValue);
//-----------------------------------校验入参--------------------------------//
if (StringUtils.isBlank(groupId)) {
log.error("GroupId should not be null, Please input it");
return;
}
if (StringUtils.isBlank(consenter)) {
log.error("Consenter should not be null, Please input it");
return;
}
if (StringUtils.isBlank(scName)) {
log.error("Smart contract's name should not be null, Please input it");
return;
}
String[] consenterHostPort = consenter.split(":");
if (consenterHostPort.length <= 1) {
log.error("Consenter is not valid");
return;
}
int consenterPort = 0;
try {
consenterPort = Integer.parseInt(consenterHostPort[1]);
} catch (NumberFormatException ex) {
log.error("Consenter's port is not valid");
return;
}
//invoke smart contract
if (StringUtils.isBlank(targetAddress)) {
log.info("TargetAddress is empty, use 127.0.0.1:7051");
nodeSmartContract.invoke(NodeConstant.DEFAULT_NODE_HOST, NodeConstant.DEFAULT_NODE_PORT,
consenterHostPort[0], consenterPort, groupId, scName, input);
} else {
try {
NetAddress targetNetAddress = new NetAddress(targetAddress);
nodeSmartContract.invoke(targetNetAddress.getHost(), targetNetAddress.getPort(), consenterHostPort[0]
, consenterPort, groupId, scName, input);
} catch (ValidateException e) {
log.error(e.getMessage(), e);
}
}
}
/**
* Filter the request.
* <br><br>LOGIN:<br>
* The first time this filter gets hit, it will redirect to the OP.
* Second time it will expect a code and state param to be set, and will exchange the code for an access token.
* Then it will request the UserInfo given the access token.
* <br>--
* Result: the OpenID Connect 1.0 flow.
* <br><br>LOGOUT:<br>
* When the filter is hit and according values for SSO logout are set, it will redirect to the OP logout resource.
* From there the request should be redirected "back" to a public portal page or the public portal home page.
*
* @param request the http request
* @param response the http response
* @param filterChain the filterchain
* @throws Exception according to interface.
* @return FilterResult, to be able to distinct between continuing the chain or breaking it.
*/
protected FilterResult processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain
filterChain) throws Exception {
OIDCConfiguration oidcConfiguration = liferay.getOIDCConfiguration(liferay.getCompanyId(request));
// If the plugin is not enabled, short circuit immediately
if (!oidcConfiguration.isEnabled()) {
liferay.trace("OpenIDConnectFilter not enabled for this virtual instance. Will skip it.");
return FilterResult.CONTINUE_CHAIN;
}
liferay.trace("In processFilter()...");
String pathInfo = request.getPathInfo();
if (null != pathInfo) {
if (pathInfo.contains("/portal/login")) {
if (!StringUtils.isBlank(request.getParameter(REQ_PARAM_CODE))
&& !StringUtils.isBlank(request.getParameter(REQ_PARAM_STATE))) {
if (!isUserLoggedIn(request)) {
// LOGIN: Second time it will expect a code and state param to be set, and will exchange the code for an access token.
liferay.trace("About to exchange code for access token");
exchangeCodeForAccessToken(request);
} else {
liferay.trace("subsequent run into filter during openid conversation, but already logged in." +
"Will not exchange code for token twice.");
}
} else {
// LOGIN: The first time this filter gets hit, it will redirect to the OP.
liferay.trace("About to redirect to OpenID Provider");
redirectToLogin(request, response, oidcConfiguration.clientId());
// no continuation of the filter chain; we expect the redirect to commence.
return FilterResult.BREAK_CHAIN;
}
}
else
if (pathInfo.contains("/portal/logout")) {
final String ssoLogoutUri = oidcConfiguration.ssoLogoutUri();
final String ssoLogoutParam = oidcConfiguration.ssoLogoutParam();
final String ssoLogoutValue = oidcConfiguration.ssoLogoutValue();
if (null != ssoLogoutUri && ssoLogoutUri.length
() > 0 && isUserLoggedIn(request)) {
liferay.trace("About to logout from SSO by redirect to " + ssoLogoutUri);
// LOGOUT: If Portal Logout URL is requested, redirect to OIDC Logout resource afterwards to globally logout.
// From there, the request should be redirected back to the Liferay portal home page.
request.getSession().invalidate();
redirectToLogout(request, response, ssoLogoutUri, ssoLogoutParam, ssoLogoutValue);
// no continuation of the filter chain; we expect the redirect to commence.
return FilterResult.BREAK_CHAIN;
}
}
}
// continue chain
return FilterResult.CONTINUE_CHAIN;
}
private String validateParameter(String parameter) {
if (StringUtils.isBlank(parameter)) {
throw new IllegalArgumentException("'" + taskParameterName + "' query parameter cannot be empty or blank. " + supportedValueMessage());
}
return parameter;
}
public void doMapper(Object sourceObject, Object targetObject, String mapperId) throws org.dozer.MappingException, ServiceException {
if (null==mapperId || StringUtils.isBlank(mapperId) ) {
throw new ServiceException(SysMessageUtil.get(GreenStepSysMsgConstants.DOZER_MAPPER_ID_BLANK));
}
this.mapper.map(sourceObject, targetObject, mapperId);
}