org.apache.commons.lang.StringUtils Java Examples

The following examples show how to use org.apache.commons.lang.StringUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReviewResponsibilityTypeServiceImpl.java    From rice with Educational Community License v2.0 7 votes vote down vote up
@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 #2
Source File: Base62.java    From youkefu with Apache License 2.0 7 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 #3
Source File: MongoResultPanel.java    From nosql4idea with Apache License 2.0 7 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 #4
Source File: DoctrineDbalQbGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 7 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 #5
Source File: MaintenanceUtils.java    From rice with Educational Community License v2.0 7 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 #6
Source File: AlipayTradePrecreateRequestBuilder.java    From wish-pay with Apache License 2.0 7 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 #7
Source File: UpmsUserRoleServiceImpl.java    From zheng with 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 #8
Source File: IdentityManagementGroupDocumentAction.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@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 #9
Source File: PriorYearOrganization.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #10
Source File: MessagingSource.java    From iaf with 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 #11
Source File: ServiceArgumentParameterHintsProvider.java    From idea-php-symfony2-plugin with 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 #12
Source File: YamlHelper.java    From idea-php-symfony2-plugin with 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 #13
Source File: DoctrineMetadataLineMarkerProvider.java    From idea-php-symfony2-plugin with 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 #14
Source File: PrincePdfExecutor.java    From website with 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 #15
Source File: HibernatePersistentObjectDAO.java    From document-management-software with 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 #16
Source File: TestCSVExcelStorage.java    From spork with 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 #17
Source File: BaseJobServlet.java    From pentaho-kettle with 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 #18
Source File: ExtractFunctionExecutor.java    From HtmlExtractor with 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 #19
Source File: VendorServiceImpl.java    From kfs with 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 #20
Source File: AtlasBuiltInTypes.java    From atlas with 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
Source File: ServerChallengeService.java    From identity-api-server with 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 #22
Source File: RCFileScanner.java    From incubator-tajo with 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 #23
Source File: LogSearchLdapAuthorityMapper.java    From ambari-logsearch with 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 #24
Source File: ISYBindingConfig.java    From openhab1-addons with 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 #25
Source File: MailService.java    From pacbot with 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 #26
Source File: AbstractIBatisOrientedRule.java    From cobarclient with Apache License 2.0 5 votes vote down vote up
public synchronized List<String> action() {
    if(CollectionUtils.isEmpty(dataSourceIds))
    {
        List<String> ids = new ArrayList<String>();
        for (String id : StringUtils.split(getAction(), getActionPatternSeparator())) {
            ids.add(StringUtils.trimToEmpty(id));
        }
        setDataSourceIds(ids);
    }
    return dataSourceIds;
}
 
Example #27
Source File: TaxConfigServiceImpl.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(final TaxConfig tc1, final TaxConfig tc2) {

    final String tc1country = StringUtils.isEmpty(tc1.getCountryCode()) ? null : tc1.getCountryCode();
    final String tc1state = StringUtils.isEmpty(tc1.getStateCode()) ? null : tc1.getStateCode();
    final String tc1product = StringUtils.isEmpty(tc1.getProductCode()) ? null : tc1.getProductCode();

    final String tc2country = StringUtils.isEmpty(tc2.getCountryCode()) ? null : tc2.getCountryCode();
    final String tc2state = StringUtils.isEmpty(tc2.getStateCode()) ? null : tc2.getStateCode();
    final String tc2product = StringUtils.isEmpty(tc2.getProductCode()) ? null : tc2.getProductCode();


    if (tc1product != null) { // product specific tax
        if (tc1state != null) { // product state specific tax
            return UP; // should be only 1 product state specific tax
        } else if (tc1country != null) { // product country specific tax
            // product state specific tax wins
            return tc2product != null && tc2state != null ? DOWN : UP;
        } // else product shop specific tax
        return tc2product != null && (tc2country != null || tc2state != null) ? DOWN : UP;
    } else if (tc1state != null) { // state specific tax
        if (tc2product != null) {
            return DOWN; // product specific tax is higher up
        }
        return UP; // should be only 1 state specific tax
    } else if (tc1country != null) { // country specific tax
        if (tc2product != null || tc2state != null) {
            return DOWN; // product specific or state specific tax is higher up
        }
        return UP;
    } // else shop specific (all nulls)
    return DOWN;
}
 
Example #28
Source File: SeventeenBroadcastService.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getBroadcastAddress(AccountInfo accountInfo) throws Exception {
    Map<String, String> requestHeader = buildRequestHeader(accountInfo);
    String rtmpJSON = HttpRequestUtil.downloadUrl(new URI(API_RTMP), null, "{\"streamType\":\"rtmp\",\"eventID\":-1,\"privateMsgThreshold\":0,\"privateMsgEnable\":false}", requestHeader, StandardCharsets.UTF_8);
    JSONObject rtmpObj = JSON.parseObject(rtmpJSON);
    String rtmpUrl = rtmpObj.getString("rtmpURL");
    if (StringUtils.isNotEmpty(rtmpUrl)) {
        return rtmpUrl;
    } else {
        accountInfo.setDisable(true);
        throw new RuntimeException("开启17Live直播间失败" + rtmpJSON);
    }
}
 
Example #29
Source File: BarcodeInventoryErrorAction.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
protected boolean validateGlobalReplaceFields(BarcodeInventoryErrorDocument document) {
    if (StringUtils.isBlank(document.getCurrentScanCode()) && StringUtils.isBlank(document.getCurrentCampusCode()) && StringUtils.isBlank(document.getCurrentBuildingNumber()) && StringUtils.isBlank(document.getCurrentRoom()) && StringUtils.isBlank(document.getCurrentSubroom()) && StringUtils.isBlank(document.getCurrentConditionCode()) && StringUtils.isBlank(document.getCurrentTagNumber())) {

        GlobalVariables.getMessageMap().putErrorForSectionId(CamsPropertyConstants.BCIE_GLOBAL_REPLACE_ERROR_SECTION_ID, CamsKeyConstants.BarcodeInventory.ERROR_GLOBAL_REPLACE_SEARCH_CRITERIA);
        return false;
    }
    return true;
}
 
Example #30
Source File: StopAllComponent.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * サービス停止(ALL)
 * @param farmNo ファーム番号
 * @param isStopInstance サーバ停止有無 true:サーバも停止、false:サービスのみ停止
 * @return StopComponentResponse
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public StopAllComponentResponse stopComponent(@QueryParam(PARAM_NAME_FARM_NO) String farmNo,
        @QueryParam(PARAM_NAME_IS_STOP_INSTANCE) String isStopInstance) {

    // 入力チェック
    // FarmNo
    ApiValidate.validateFarmNo(farmNo);
    // IsStopInstance
    ApiValidate.validateIsStopInstance(isStopInstance);

    // ファーム取得
    Farm farm = getFarm(Long.parseLong(farmNo));

    // 権限チェック
    checkAndGetUser(farm);

    // コンポーネント取得
    List<Component> components = componentDao.readByFarmNo(Long.parseLong(farmNo));
    List<Long> componentNos = new ArrayList<Long>();
    for (Component component : components) {
        if (BooleanUtils.isTrue(component.getLoadBalancer())) {
            //ロードバランサコンポーネントは対象外
            continue;
        }
        componentNos.add(component.getComponentNo());
    }

    // サービス停止設定
    if (StringUtils.isEmpty(isStopInstance)) {
        processService.stopComponents(Long.parseLong(farmNo), componentNos);
    } else {
        processService.stopComponents(Long.parseLong(farmNo), componentNos, Boolean.parseBoolean(isStopInstance));
    }

    StopAllComponentResponse response = new StopAllComponentResponse();

    return response;
}