Java Code Examples for org.apache.commons.lang.StringUtils

The following examples show how to use org.apache.commons.lang.StringUtils. These examples are extracted from open source projects.
Example 1
Project: wish-pay   File: AlipayTradePrecreateRequestBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate() {
    if (StringUtils.isEmpty(bizContent.outTradeNo)) {
        throw new NullPointerException("out_trade_no should not be NULL!");
    }
    if (StringUtils.isEmpty(bizContent.totalAmount)) {
        throw new NullPointerException("total_amount should not be NULL!");
    }
    if (StringUtils.isEmpty(bizContent.subject)) {
        throw new NullPointerException("subject should not be NULL!");
    }
    if (StringUtils.isEmpty(bizContent.storeId)) {
        throw new NullPointerException("store_id should not be NULL!");
    }
    return true;
}
 
Example 2
Project: ambari-logsearch   File: LogSearchLdapAuthorityMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
  if (!groupRoleMap.isEmpty() && !authorities.isEmpty()) {
    List<SimpleGrantedAuthority> newAuthorities = new ArrayList<>();
    for (GrantedAuthority authority : authorities) {
      String withoutRoleStringLowercase = StringUtils.removeStart(authority.toString(), ROLE_PREFIX).toLowerCase();
      String withoutRoleStringUppercase = StringUtils.removeStart(authority.toString(), ROLE_PREFIX).toUpperCase();
      String simpleRoleLowercaseString = authority.toString().toLowerCase();
      String simpleRoleUppercaseString = authority.toString().toUpperCase();
      if (addAuthoritiy(newAuthorities, withoutRoleStringLowercase))
        continue;
      if (addAuthoritiy(newAuthorities, withoutRoleStringUppercase))
        continue;
      if (addAuthoritiy(newAuthorities, simpleRoleLowercaseString))
        continue;
      addAuthoritiy(newAuthorities, simpleRoleUppercaseString);
    }
    return newAuthorities;
  }
  return authorities;
}
 
Example 3
Project: idea-php-symfony2-plugin   File: YamlHelper.java    License: MIT License 6 votes vote down vote up
/**
 * [ROLE_USER, FEATURE_ALPHA, ROLE_ALLOWED_TO_SWITCH]
 */
@NotNull
static public Collection<String> getYamlArrayValuesAsList(@NotNull YAMLSequence yamlArray) {
    Collection<String> keys = new ArrayList<>();

    for (YAMLSequenceItem yamlSequenceItem : yamlArray.getItems()) {
        YAMLValue value = yamlSequenceItem.getValue();
        if(!(value instanceof YAMLScalar)) {
            continue;
        }

        String textValue = ((YAMLScalar) value).getTextValue();
        if(StringUtils.isNotBlank(textValue)) {
            keys.add(textValue);
        }
    }

    return keys;
}
 
Example 4
Project: idea-php-symfony2-plugin   File: ServiceArgumentParameterHintsProvider.java    License: MIT License 6 votes vote down vote up
@Nullable
private Pair<String, Method> getParamater(@NotNull Project project, @NotNull String aClass, @NotNull java.util.function.Function<Void, Integer> function) {
    if(StringUtils.isNotBlank(aClass)) {
        PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(project, aClass);
        if(phpClass != null) {
            Method constructor = phpClass.getConstructor();
            if(constructor != null) {
                Integer argumentIndex = function.apply(null);
                if(argumentIndex >= 0) {
                    String s = attachMethodInstances(constructor, argumentIndex);
                    if(s == null) {
                        return null;
                    }

                    return Pair.create(s, constructor);
                }
            }
        }
    }

    return null;
}
 
Example 5
Project: idea-php-symfony2-plugin   File: DoctrineMetadataLineMarkerProvider.java    License: MIT License 6 votes vote down vote up
private void attachXmlRelationMarker(@NotNull PsiElement target, @NotNull XmlAttributeValue psiElement, @NotNull Collection<LineMarkerInfo> results) {
    String value = psiElement.getValue();
    if(StringUtils.isBlank(value)) {
        return;
    }

    Collection<PhpClass> classesInterface = DoctrineMetadataUtil.getClassInsideScope(psiElement, value);
    if(classesInterface.size() == 0) {
        return;
    }

    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.DOCTRINE_LINE_MARKER).
        setTargets(classesInterface).
        setTooltipText("Navigate to class");

    results.add(builder.createLineMarkerInfo(target));
}
 
Example 6
/**
 * Gets the organizationCountry attribute.
 *
 * @return Returns the organizationCountry.
 */
public CountryEbo getOrganizationCountry() {
    if ( StringUtils.isBlank(organizationCountryCode) ) {
        organizationCountry = null;
    } else {
        if ( organizationCountry == null || !StringUtils.equals( organizationCountry.getCode(),organizationCountryCode) ) {
            ModuleService moduleService = SpringContext.getBean(KualiModuleService.class).getResponsibleModuleService(CountryEbo.class);
            if ( moduleService != null ) {
                Map<String,Object> keys = new HashMap<String, Object>(1);
                keys.put(LocationConstants.PrimaryKeyConstants.CODE, organizationCountryCode);
                organizationCountry = moduleService.getExternalizableBusinessObject(CountryEbo.class, keys);
            } else {
                throw new RuntimeException( "CONFIGURATION ERROR: No responsible module found for EBO class.  Unable to proceed." );
            }
        }
    }
    return organizationCountry;
}
 
Example 7
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
       IdentityManagementGroupDocumentForm groupDocumentForm = (IdentityManagementGroupDocumentForm) form;
       if ( StringUtils.isBlank( groupDocumentForm.getGroupId() ) ) {
           String groupId = request.getParameter(KimConstants.PrimaryKeyConstants.GROUP_ID);
       	groupDocumentForm.setGroupId(groupId);
       }
	String kimTypeId = request.getParameter(KimConstants.PrimaryKeyConstants.KIM_TYPE_ID);
       setKimType(kimTypeId, groupDocumentForm);

       
	KualiTableRenderFormMetadata memberTableMetadata = groupDocumentForm.getMemberTableMetadata();
	if (groupDocumentForm.getMemberRows() != null) {
		memberTableMetadata.jumpToPage(memberTableMetadata.getViewedPageNumber(), groupDocumentForm.getMemberRows().size(), groupDocumentForm.getRecordsPerPage());
		// KULRICE-3972: need to be able to sort by column header like on lookups when editing large roles and groups
		memberTableMetadata.sort(groupDocumentForm.getMemberRows(), groupDocumentForm.getRecordsPerPage());
	}
	
	ActionForward forward = super.execute(mapping, groupDocumentForm, request, response);
	
	groupDocumentForm.setCanAssignGroup(validAssignGroup(groupDocumentForm.getGroupDocument()));
	return forward;
   }
 
Example 8
Project: website   File: PrincePdfExecutor.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public File execute(String htmlLocation, List<String> cssFiles) throws IOException, InterruptedException {
	Prince prince = new Prince(princePdfExecutableLocation);
	
	String newPdfFilename = getNewPdfFilename(htmlLocation);
	if (!StringUtils.startsWith(htmlLocation, "http")) {
		htmlLocation = FilenameUtils.concat(htmlFolder, htmlLocation);
		File f = new File(htmlLocation);
		if(!f.exists()) { 
			throw new IOException("File '" + htmlLocation + "' not found");
		}
		htmlLocation = "file://" + htmlLocation;
	}
	for (String cssFile : cssFiles) {
		prince.addStyleSheet(FilenameUtils.concat(htmlToPdfCssFolder, cssFile));
	}		
	prince.convert(htmlLocation, newPdfFilename);
	
       return new File(newPdfFilename);
}
 
Example 9
Project: document-management-software   File: HibernatePersistentObjectDAO.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<T> findByWhere(String where, Object[] values, String order, Integer max) throws PersistenceException {
	List<T> coll = new ArrayList<T>();
	try {
		String sorting = StringUtils.isNotEmpty(order) && !order.toLowerCase().contains("order by")
				? "order by " + order
				: order;
		String query = "from " + entityClass.getCanonicalName() + " _entity where _entity.deleted=0 "
				+ (StringUtils.isNotEmpty(where) ? " and (" + where + ") " : " ")
				+ (StringUtils.isNotEmpty(sorting) ? sorting : " ");
		coll = findByObjectQuery(query, values, max);
		return coll;
	} catch (Throwable e) {
		throw new PersistenceException(e);
	}
}
 
Example 10
Project: spork   File: TestCSVExcelStorage.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void load() throws IOException, ParseException {
    String schema = "i: int, l: long, f: float, d: double, c: chararray, b: bytearray";

    pig.registerQuery(
        "data = load '" + dataDir + testFile + "' " +
        "using org.apache.pig.piggybank.storage.CSVExcelStorage(',', 'YES_MULTILINE', 'UNIX', 'SKIP_INPUT_HEADER') " + 
        "AS (" + schema + ");"
    );

    Iterator<Tuple> data = pig.openIterator("data");
    String[] expected = {
        // a header in csv_excel_data.csv should be skipped due to 'SKIP_INPUT_HEADER' being set in test_csv_storage_load.pig
        "(1,10,2.718,3.14159,qwerty,uiop)",  // basic data types
        "(1,10,2.718,3.14159,,)",            // missing fields at end
        "(1,10,,3.15159,,uiop)",             // missing field in the middle
        "(1,10,,3.15159,,uiop)",             // extra field (input data has "moose" after "uiop")
        "(1,,2.718,,qwerty,uiop)",           // quoted regular fields (2.718, qwerty, and uiop in quotes)
        "(1,,,,\nqwe\nrty, uiop)",           // newlines in quotes
        "(1,,,,qwe,rty,uiop)",               // commas in quotes
        "(1,,,,q\"wert\"y, uiop)",           // quotes in quotes
        "(1,,,,qwerty,u\"io\"p)"             // quotes in quotes at the end of a line
    };

    Assert.assertEquals(StringUtils.join(expected, "\n"), StringUtils.join(data, "\n"));
}
 
Example 11
Project: rice   File: MaintenanceUtils.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * Returns the field templates defined in the maint dictionary xml files. Field templates are used in multiple value lookups.
 * When doing a MV lookup on a collection, the returned BOs are not necessarily of the same type as the elements of the
 * collection. Therefore, a means of mapping between the fields for the 2 BOs are necessary. The template attribute of
 * &lt;maintainableField&gt;s contained within &lt;maintainableCollection&gt;s tells us this mapping. Example: a
 * &lt;maintainableField name="collectionAttrib" template="lookupBOAttrib"&gt; definition means that when a list of BOs are
 * returned, the lookupBOAttrib value of the looked up BO will be placed into the collectionAttrib value of the BO added to the
 * collection
 *
 * @param sections       the sections of a document
 * @param collectionName the name of a collection. May be a nested collection with indices (e.g. collA[1].collB)
 * @return
 */
public static Map<String, String> generateMultipleValueLookupBOTemplate(List<MaintainableSectionDefinition> sections, String collectionName) {
    MaintainableCollectionDefinition definition = findMaintainableCollectionDefinition(sections, collectionName);
    if (definition == null) {
        return null;
    }
    Map<String, String> template = null;

    for (MaintainableFieldDefinition maintainableField : definition.getMaintainableFields()) {
        String templateString = maintainableField.getTemplate();
        if (StringUtils.isNotBlank(templateString)) {
            if (template == null) {
                template = new HashMap<String, String>();
            }
            template.put(maintainableField.getName(), templateString);
        }
    }
    return template;
}
 
Example 12
Project: HtmlExtractor   File: ExtractFunctionExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 删除子CSS路径的内容 使用方法:deleteChild(div.ep-source)
 * 括号内的参数为相对CSS路径的子路径,从CSS路径匹配的文本中删除子路径匹配的文本
 *
 * @param text CSS路径抽取出来的文本
 * @param doc 根文档
 * @param cssPath CSS路径对象
 * @param parseExpression 抽取函数
 * @return 抽取函数处理之后的文本
 */
public static String executeDeleteChild(String text, Document doc, CssPath cssPath, String parseExpression) {
    LOGGER.debug("deleteChild抽取函数之前:" + text);
    String parameter = parseExpression.replace("deleteChild(", "");
    parameter = parameter.substring(0, parameter.length() - 1);
    Elements elements = doc.select(cssPath.getCssPath() + " " + parameter);
    for (Element element : elements) {
        String t = element.text();
        if (StringUtils.isNotBlank(t)) {
            LOGGER.debug("deleteChild抽取函数删除:" + t);
            text = text.replace(t, "");
        }
    }
    LOGGER.debug("deleteChild抽取函数之后:" + text);
    return text;
}
 
Example 13
Project: idea-php-symfony2-plugin   File: DoctrineDbalQbGotoCompletionRegistrar.java    License: MIT License 6 votes vote down vote up
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {

    DoctrineMetadataModel model = DoctrineMetadataUtil.getMetadataByTable(getProject(), this.stringValue);
    if(model == null) {
        return Collections.emptyList();
    }

    Collection<LookupElement> elements = new ArrayList<>();
    for (DoctrineModelField field : model.getFields()) {
        String column = field.getColumn();

        // use "column" else fallback to field name
        if(column != null && StringUtils.isNotBlank(column)) {
            elements.add(LookupElementBuilder.create(column).withIcon(Symfony2Icons.DOCTRINE));
        } else {
            String name = field.getName();
            if(StringUtils.isNotBlank(name)) {
                elements.add(LookupElementBuilder.create(name).withIcon(Symfony2Icons.DOCTRINE));
            }
        }
    }

    return elements;
}
 
Example 14
Project: incubator-tajo   File: RCFileScanner.java    License: Apache License 2.0 6 votes vote down vote up
public RCFileScanner(final Configuration conf, final Schema schema, final TableMeta meta, final FileFragment fragment)
     throws IOException {
   super(conf, meta, schema, fragment);

   this.start = fragment.getStartKey();
   this.end = start + fragment.getEndKey();
   key = new LongWritable();
   column = new BytesRefArrayWritable();

   String nullCharacters = StringEscapeUtils.unescapeJava(this.meta.getOption(NULL));
   if (StringUtils.isEmpty(nullCharacters)) {
     nullChars = NullDatum.get().asTextBytes();
   } else {
     nullChars = nullCharacters.getBytes();
   }
}
 
Example 15
Project: nosql4idea   File: MongoResultPanel.java    License: Apache License 2.0 6 votes vote down vote up
private DBObject getSelectedMongoDocument() {
    TreeTableTree tree = resultTableView.getTree();
    NoSqlTreeNode treeNode = (NoSqlTreeNode) tree.getLastSelectedPathComponent();
    if (treeNode == null) {
        return null;
    }

    NodeDescriptor descriptor = treeNode.getDescriptor();
    if (descriptor instanceof MongoKeyValueDescriptor) {
        MongoKeyValueDescriptor keyValueDescriptor = (MongoKeyValueDescriptor) descriptor;
        if (StringUtils.equals(keyValueDescriptor.getKey(), "_id")) {
            return mongoDocumentOperations.getMongoDocument(keyValueDescriptor.getValue());
        }
    }

    return null;
}
 
Example 16
Project: openhab1-addons   File: ISYBindingConfig.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructor
 * 
 * @param item
 *            full item from openhab
 * @param type
 *            the node type in ISY, rough translation.
 * @param controller
 *            the address of the controller.
 * @param address
 *            the address of the item to monitor for changes. same as
 *            controller if not specified.
 * @param command
 *            the command the system is sending for this controller.
 */
public ISYBindingConfig(Item item, ISYNodeType type, String controller, String address, ISYControl command) {
    this.item = item;
    this.type = type;
    this.controller = controller;
    if (StringUtils.isNotBlank(address)) {
        this.address = address;
    } else {
        this.address = controller;
    }
    if (command != null) {
        this.controlCommand = command;
    } else {
        this.controlCommand = ISYControl.ST;
    }
}
 
Example 17
Project: youkefu   File: Base62.java    License: Apache License 2.0 6 votes vote down vote up
public static String encode(String str){ 
	    String md5Hex = DigestUtils.md5Hex(str);
	    // 6 digit binary can indicate 62 letter & number from 0-9a-zA-Z
	    int binaryLength = 6 * 6;
	    long binaryLengthFixer = Long.valueOf(StringUtils.repeat("1", binaryLength), BINARY);
	    for (int i = 0; i < 4;) {
	      String subString = StringUtils.substring(md5Hex, i * 8, (i + 1) * 8);
	      subString = Long.toBinaryString(Long.valueOf(subString, 16) & binaryLengthFixer);
	      subString = StringUtils.leftPad(subString, binaryLength, "0");
	      StringBuilder sbBuilder = new StringBuilder();
	      for (int j = 0; j < 6; j++) {
	        String subString2 = StringUtils.substring(subString, j * 6, (j + 1) * 6);
	        int charIndex = Integer.valueOf(subString2, BINARY) & NUMBER_61;
	        sbBuilder.append(DIGITS[charIndex]);
	      }
	      String shortUrl = sbBuilder.toString();
	      if(shortUrl!=null){
	    	  return shortUrl;
	      }
	    }
	    // if all 4 possibilities are already exists
	    return null;
}
 
Example 18
@Override
protected List<Responsibility> performResponsibilityMatches(
		Map<String, String> requestedDetails,
		List<Responsibility> responsibilitiesList) {
	// get the base responsibility matches based on the route level and document type
	List<Responsibility> baseMatches = super.performResponsibilityMatches(requestedDetails,
			responsibilitiesList);
	// now, if any of the responsibilities have the "qualifierResolverProvidedIdentifier" detail property
	// perform an exact match on the property with the requested details
	// if the property does not match or does not exist in the requestedDetails, remove
	// the responsibility from the list
	Iterator<Responsibility> respIter = baseMatches.iterator();
	while ( respIter.hasNext() ) {
		Map<String, String> respDetails = respIter.next().getAttributes();
		if ( respDetails.containsKey( KimConstants.AttributeConstants.QUALIFIER_RESOLVER_PROVIDED_IDENTIFIER ) && StringUtils.isNotBlank( respDetails.get(KimConstants.AttributeConstants.QUALIFIER_RESOLVER_PROVIDED_IDENTIFIER) ) ) {
			if ( !requestedDetails.containsKey( KimConstants.AttributeConstants.QUALIFIER_RESOLVER_PROVIDED_IDENTIFIER )
					|| !StringUtils.equals( respDetails.get(KimConstants.AttributeConstants.QUALIFIER_RESOLVER_PROVIDED_IDENTIFIER)
							, requestedDetails.get(KimConstants.AttributeConstants.QUALIFIER_RESOLVER_PROVIDED_IDENTIFIER))) {
				respIter.remove();
			}
		}
	}		
	return baseMatches;
}
 
Example 19
Project: identity-api-server   File: ServerChallengeService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete a challenge set
 *
 * @param challengeSetId challenge question set id to delete
 * @param locale
 * @return
 */
public boolean deleteQuestionSet(String challengeSetId, String locale) {

    if (StringUtils.isEmpty(locale)) {
        locale = StringUtils.EMPTY;
    }
    try {
        if (isChallengeSetExists(challengeSetId, ContextLoader.getTenantDomainFromContext())) {
            getChallengeQuestionManager()
                    .deleteChallengeQuestionSet(challengeSetId, locale, ContextLoader.getTenantDomainFromContext());
        }
    } catch (IdentityRecoveryException e) {
        throw handleIdentityRecoveryException(e,
                ChallengeConstant.ErrorMessage.ERROR_CODE_ERROR_DELETING_CHALLENGES);
    }
    return true;
}
 
Example 20
Project: atlas   File: AtlasBuiltInTypes.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isValidMap(Map map) {
    Object guid = map.get(AtlasObjectId.KEY_GUID);

    if (guid != null && StringUtils.isNotEmpty(guid.toString())) {
        return true;
    } else {
        Object typeName = map.get(AtlasObjectId.KEY_TYPENAME);
        if (typeName != null && StringUtils.isNotEmpty(typeName.toString())) {
            Object uniqueAttributes = map.get(AtlasObjectId.KEY_UNIQUE_ATTRIBUTES);

            if (uniqueAttributes instanceof Map && MapUtils.isNotEmpty((Map) uniqueAttributes)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 21
Project: kfs   File: VendorServiceImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @see org.kuali.kfs.vnd.document.service.VendorService#getVendorDetail(String)
 */
@Override
public VendorDetail getVendorDetail(String vendorNumber) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Entering getVendorDetail for vendorNumber: " + vendorNumber);
    }
    if (StringUtils.isBlank(vendorNumber)) {
        return null;
    }

    int dashInd = vendorNumber.indexOf('-');
    // make sure there's at least one char before and after '-'
    if (dashInd > 0 && dashInd < vendorNumber.length() - 1) {
        try {
            Integer headerId = new Integer(vendorNumber.substring(0, dashInd));
            Integer detailId = new Integer(vendorNumber.substring(dashInd + 1));
            return getVendorDetail(headerId, detailId);
        }
        catch (NumberFormatException e) {
            // in case of invalid number format
            return null;
        }
    }

    return null;
}
 
Example 22
Project: pentaho-kettle   File: BaseJobServlet.java    License: Apache License 2.0 6 votes vote down vote up
private void copyJobParameters( Job job, Map<String, String> params ) throws UnknownParamException {
  JobMeta jobMeta = job.getJobMeta();
  // Also copy the parameters over...
  job.copyParametersFrom( jobMeta );
  job.clearParameters();
  String[] parameterNames = job.listParameters();
  for ( String parameterName : parameterNames ) {
    // Grab the parameter value set in the job entry
    String thisValue = params.get( parameterName );
    if ( !StringUtils.isBlank( thisValue ) ) {
      // Set the value as specified by the user in the job entry
      jobMeta.setParameterValue( parameterName, thisValue );
    }
  }
  jobMeta.activateParameters();
}
 
Example 23
Project: zheng   File: UpmsUserRoleServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public int role(String[] roleIds, int id) {
    int result = 0;
    // 删除旧记录
    UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample();
    upmsUserRoleExample.createCriteria()
            .andUserIdEqualTo(id);
    upmsUserRoleMapper.deleteByExample(upmsUserRoleExample);
    // 增加新记录
    if (null != roleIds) {
        for (String roleId : roleIds) {
            if (StringUtils.isBlank(roleId)) {
                continue;
            }
            UpmsUserRole upmsUserRole = new UpmsUserRole();
            upmsUserRole.setUserId(id);
            upmsUserRole.setRoleId(NumberUtils.toInt(roleId));
            result = upmsUserRoleMapper.insertSelective(upmsUserRole);
        }
    }
    return result;
}
 
Example 24
Project: pacbot   File: MailService.java    License: Apache License 2.0 6 votes vote down vote up
private MimeMessagePreparator buildMimeMessagePreparator(String from, List<String> to, String subject, String mailContent , final String attachmentUrl) {
	MimeMessagePreparator messagePreparator = mimeMessage -> {
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
		messageHelper.setFrom(from);
		String[] toMailList = to.toArray(new String[to.size()]);
		messageHelper.setTo(toMailList);
		messageHelper.setSubject(subject);
		messageHelper.setText(mailContent, true);
		if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
			URL url = new URL(attachmentUrl);
			String filename = url.getFile();
			byte fileContent [] = getFileContent(url);
			messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
		}
	};
	return messagePreparator;
}
 
Example 25
Project: iaf   File: MessagingSource.java    License: Apache License 2.0 6 votes vote down vote up
protected Connection createConnection() throws JMSException {
	if (StringUtils.isNotEmpty(authAlias)) {
		CredentialFactory cf = new CredentialFactory(authAlias,null,null);
		if (log.isDebugEnabled()) log.debug("using userId ["+cf.getUsername()+"] to create Connection");
		if (useJms102()) {
			if (connectionFactory instanceof QueueConnectionFactory) {
				return ((QueueConnectionFactory)connectionFactory).createQueueConnection(cf.getUsername(),cf.getPassword());
			} else {
				return ((TopicConnectionFactory)connectionFactory).createTopicConnection(cf.getUsername(),cf.getPassword());
			}
		} else {
			return connectionFactory.createConnection(cf.getUsername(),cf.getPassword());
		}
	}
	if (useJms102()) {
		if (connectionFactory instanceof QueueConnectionFactory) {
			return ((QueueConnectionFactory)connectionFactory).createQueueConnection();
		} else {
			return ((TopicConnectionFactory)connectionFactory).createTopicConnection();
		}
	} else {
		return connectionFactory.createConnection();
	}
}
 
Example 26
Project: carbon-identity-framework   File: IdentityUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns whether the passed operation is supported by userstore or not
 *
 * @param userStoreManager User Store
 * @param operation        Operation name
 * @return true if the operation is supported by userstore. False if it doesnt
 */
public static boolean isSupportedByUserStore(UserStoreManager userStoreManager, String operation) {
    boolean isOperationSupported = true;
    if (userStoreManager != null) {
        String isOperationSupportedProperty = userStoreManager.getRealmConfiguration().getUserStoreProperty
                (operation);
        if (StringUtils.isNotBlank(isOperationSupportedProperty)) {
            isOperationSupported = Boolean.parseBoolean(isOperationSupportedProperty);
        }
    }
    return isOperationSupported;
}
 
Example 27
Project: atlas   File: ZipFileMigrationImporter.java    License: Apache License 2.0 5 votes vote down vote up
private int processZipFileStreamSizeComment(String comment) {
    if (StringUtils.isEmpty(comment)) {
        return 1;
    }

    Map map = AtlasType.fromJson(comment, Map.class);
    int entitiesCount = (int) map.get(ZIP_FILE_COMMENT_ENTITIES_COUNT);
    int totalCount = (int) map.get(ZIP_FILE_COMMENT_TOTAL_COUNT);
    LOG.info("ZipFileMigrationImporter: Zip file: Comment: streamSize: {}: total: {}", entitiesCount, totalCount);

    return entitiesCount;
}
 
Example 28
Project: youkefu   File: NoticeBusinessController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/detail")
  @Menu(type = "notice" , subtype = "noticebus" )
  public ModelAndView detail(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String msg, @Valid String sysmsmsg, @Valid String smsmsg, @Valid String mailmsg) throws SQLException {
if (!StringUtils.isBlank(id)) {
	Notice notice = noticeRes.findByIdAndOrgi(id, super.getOrgi(request));
	if (notice != null) {
		map.addAttribute("notice",notice) ;
	}
}
map.addAttribute("msg",msg) ;
map.addAttribute("sysmsmsg",sysmsmsg) ;
map.addAttribute("smsmsg",smsmsg) ;
map.addAttribute("mailmsg",mailmsg) ;
  	return request(super.createAppsTempletResponse("/apps/notice/detail"));
  }
 
Example 29
Project: zstack   File: CdRomBootOrderAllocator.java    License: Apache License 2.0 5 votes vote down vote up
private int setCdRomBootOrder(List<KVMAgentCommands.CdRomTO> cdRoms, int bootOrderNum) {
    for (KVMAgentCommands.CdRomTO cdRom : cdRoms) {
        if (!cdRom.isEmpty() && StringUtils.isNotEmpty(cdRom.getPath())) {
            cdRom.setBootOrder(++bootOrderNum);
        }
    }
    return bootOrderNum;
}
 
Example 30
Project: rice   File: LookupDefinition.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Sets title to the given value.
 *
 * @param title
 * @throws IllegalArgumentException if the given title is blank
 */
public void setTitle(String title) {
    if (StringUtils.isBlank(title)) {
        throw new IllegalArgumentException("invalid (blank) title");
    }
    this.title = title;
}
 
Example 31
Project: teaching   File: HTMLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取HTML内的文本,不包含标签
 *
 * @param html HTML 代码
 */
public static String getInnerText(String html) {
    if (StringUtils.isNotBlank(html)) {
        //去掉 html 的标签
        String content = html.replaceAll("</?[^>]+>", "");
        // 将多个空格合并成一个空格
        content = content.replaceAll("(&nbsp;)+", "&nbsp;");
        // 反向转义字符
        content = HtmlUtils.htmlUnescape(content);
        return content.trim();
    }
    return "";
}
 
Example 32
Project: rice   File: ImageField.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * PerformFinalize override - calls super, corrects the field's Label for attribute to point to this field's
 * content
 *
 * @param model the model
 * @param parent the parent component
 */
@Override
public void performFinalize(Object model, LifecycleElement parent) {
    super.performFinalize(model, parent);

    //determine what id to use for the for attribute of the label, if present
    if (this.getFieldLabel() != null && this.getImage() != null && StringUtils.isNotBlank(this.getImage().getId())) {
        this.getFieldLabel().setLabelForComponentId(this.getImage().getId());
    }
}
 
Example 33
Project: spacewalk   File: KickstartScript.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 *
 * @return interpreter for this script
 */
public String getPrettyInterpreter() {
    if (StringUtils.isBlank(this.interpreter)) {
        return BASH;
    }
    return interpreter;
}
 
Example 34
Project: flutter-intellij   File: FlutterOutline.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("[");
  builder.append("kind=");
  builder.append(kind + ", ");
  builder.append("offset=");
  builder.append(offset + ", ");
  builder.append("length=");
  builder.append(length + ", ");
  builder.append("codeOffset=");
  builder.append(codeOffset + ", ");
  builder.append("codeLength=");
  builder.append(codeLength + ", ");
  builder.append("label=");
  builder.append(label + ", ");
  builder.append("dartElement=");
  builder.append(dartElement + ", ");
  if (attributes != null) {
    builder.append("attributes=");
    builder.append(StringUtils.join(attributes, ", ") + ", ");
  }
  builder.append("className=");
  builder.append(className + ", ");
  builder.append("parentAssociationLabel=");
  builder.append(parentAssociationLabel + ", ");
  builder.append("variableName=");
  builder.append(variableName + ", ");
  if (children != null) {
    builder.append("children=");
    builder.append(StringUtils.join(children, ", "));
  }

  builder.append("]");
  return builder.toString();
}
 
Example 35
Project: primecloud-controller   File: LoadBalancerButtonsBottom.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void startButtonClick(ClickEvent event) {
    final LoadBalancerDto loadBalancer = (LoadBalancerDto) sender.loadBalancerPanel.loadBalancerTable.getValue();

    // AWSロードバランサでVPCの場合、サブネットを設定していることを確認
    if (PCCConstant.LOAD_BALANCER_ELB.equals(loadBalancer.getLoadBalancer().getType())) {
        if (BooleanUtils.isTrue(loadBalancer.getPlatform().getPlatformAws().getVpc())) {
            if (StringUtils.isEmpty(loadBalancer.getAwsLoadBalancer().getSubnetId())) {
                throw new AutoApplicationException("IUI-000111");
            }
        }
    }

    // 確認ダイアログを表示
    LoadBalancerStatus status = LoadBalancerStatus.fromStatus(loadBalancer.getLoadBalancer().getStatus());
    String code = status == LoadBalancerStatus.STOPPED ? "IUI-000057" : "IUI-000059";
    String message = ViewMessages.getMessage(code, loadBalancer.getLoadBalancer().getLoadBalancerName());
    DialogConfirm dialog = new DialogConfirm(ViewProperties.getCaption("dialog.confirm"), message,
            Buttons.OKCancel);
    dialog.setCallback(new DialogConfirm.Callback() {
        @Override
        public void onDialogResult(Result result) {
            if (result != Result.OK) {
                return;
            }

            start(loadBalancer.getLoadBalancer().getLoadBalancerNo());
        }
    });

    getApplication().getMainWindow().addWindow(dialog);
}
 
Example 36
Project: atlas   File: GlossaryTermUtils.java    License: Apache License 2.0 5 votes vote down vote up
private void createTermRelationships(AtlasGlossaryTerm storeObject, AtlasGlossaryTerm.Relation relation, Collection<AtlasRelatedTermHeader> terms) throws AtlasBaseException {
    if (CollectionUtils.isNotEmpty(terms)) {
        Map<String, AtlasRelatedTermHeader> existingRelations;
        if (Objects.nonNull(storeObject.getRelatedTerms()) && Objects.nonNull(storeObject.getRelatedTerms().get(relation))) {
            Map<String, AtlasRelatedTermHeader> map = new HashMap<>();
            for (AtlasRelatedTermHeader t : storeObject.getRelatedTerms().get(relation)) {
                AtlasRelatedTermHeader header = map.get(t.getTermGuid());
                if (header == null || (StringUtils.isEmpty(header.getRelationGuid()) && StringUtils.isNotEmpty(t.getRelationGuid()))) {
                    map.put(t.getTermGuid(), t);
                }
            }
            existingRelations = map;
        } else {
            existingRelations = Collections.emptyMap();
        }
        for (AtlasRelatedTermHeader term : terms) {
            if (existingRelations.containsKey(term.getTermGuid())) {
                if (DEBUG_ENABLED) {
                    LOG.debug("Skipping existing term relation termGuid={}", term.getTermGuid());
                }
                continue;
            }

            if (storeObject.getGuid().equals(term.getTermGuid())) {
                throw new AtlasBaseException(AtlasErrorCode.INVALID_TERM_RELATION_TO_SELF);
            }

            if (DEBUG_ENABLED) {
                LOG.debug("Creating new term relation = {}, terms = {}", relation, term.getDisplayText());
            }

            createRelationship(defineTermRelation(relation, storeObject.getGuid(), term));
        }
    }
}
 
Example 37
Project: aliyun-maxcompute-data-collectors   File: SqlManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String>
  getColumnTypeNamesForProcedure(String procedureName) {
  Map<String, String> ret = new TreeMap<String, String>();
  try {
    DatabaseMetaData metaData = this.getConnection().getMetaData();
    ResultSet results = metaData.getProcedureColumns(null, null,
      procedureName, null);
    if (null == results) {
      return null;
    }

    try {
      while (results.next()) {
        if (results.getInt("COLUMN_TYPE")
            != DatabaseMetaData.procedureColumnReturn
          && results.getInt("ORDINAL_POSITION") > 0) {
          // we don't care if we get several rows for the
          // same ORDINAL_POSITION (e.g. like H2 gives us)
          // as we'll just overwrite the entry in the map:
          ret.put(
            results.getString("COLUMN_NAME"),
            results.getString("TYPE_NAME"));
        }
      }
      LOG.debug("Columns returned = " + StringUtils.join(ret.keySet(), ","));
      LOG.debug(
        "Type names returned = " + StringUtils.join(ret.values(), ","));
      return ret.isEmpty() ? null : ret;
    } finally {
      results.close();
      getConnection().commit();
    }
  } catch (SQLException sqlException) {
    LoggingUtils.logAll(LOG, "Error reading primary key metadata: "
      + sqlException.toString(), sqlException);
    return null;
  }
}
 
Example 38
Project: ymate-platform-v2   File: RuntimeUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定名称的环境值
 *
 * @param envName 环境名,如果为空,返回null
 * @return 当指定名称为空或者对应名称环境变量不存在时返回空
 */
public static String getSystemEnv(String envName) {
    if (StringUtils.isNotBlank(envName)) {
        if (SYSTEM_ENV_MAP.isEmpty()) {
            initSystemEnvs();
        }
        return SYSTEM_ENV_MAP.get(envName);
    }
    return null;
}
 
Example 39
Project: BigDataPlatform   File: AEBaseController.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 前提条件: column为空<br/> 检查是否是group操作,即检查给定的groupBy参数是否在groups中出现,如果出现返回group_by。<br/> 否则返回all<br/>
 * 如果column不为空,直接返回原值
 */
protected String checkGroupByColumn(String column, String groupBy, Set<String> groups) {
  if (StringUtils.isBlank(column)) {
    if (groups.isEmpty() || !groups.contains(groupBy)) {
      return AEConstants.ALL;
    }
    return AEConstants.GROUP_BY;
  }
  return column.trim();
}
 
Example 40
public CustomerInvoiceDocument getCustomerInvoiceDocument() {
    if (ObjectUtils.isNull(customerInvoiceDocument) && StringUtils.isNotEmpty(financialDocumentReferenceInvoiceNumber)) {
        refreshReferenceObject("customerInvoiceDocument");
    }

    return customerInvoiceDocument;
}