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

The following are top voted examples for showing how to use org.apache.commons.lang.StringUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: aliyun-maxcompute-data-collectors   File: TestMerge.java   Source Code and License 7 votes vote down vote up
protected void createTable(List<List<Integer>> records) throws SQLException {
  PreparedStatement s = conn.prepareStatement("DROP TABLE \"" + TABLE_NAME + "\" IF EXISTS");
  try {
    s.executeUpdate();
  } finally {
    s.close();
  }

  s = conn.prepareStatement("CREATE TABLE \"" + TABLE_NAME
      + "\" (id INT NOT NULL PRIMARY KEY, val INT, LASTMOD timestamp)");
  try {
    s.executeUpdate();
  } finally {
    s.close();
  }

  for (List<Integer> record : records) {
    final String values = StringUtils.join(record, ", ");
    s = conn
        .prepareStatement("INSERT INTO \"" + TABLE_NAME + "\" VALUES (" + values + ", now())");
    try {
      s.executeUpdate();
    } finally {
      s.close();
    }
  }

  conn.commit();
}
 
Example 2
Project: bdf2   File: SyncRefreshSecurityCache.java   Source Code and License 7 votes vote down vote up
public void doAfter(Class<?> objectClass, Method method,Object[] arguments, Object returnValue) throws Exception {
	DataRequest req=new DataRequest();
	req.setBeanId("bdf2.roleMaintain");
	req.setMethodName(method.getName());
	String suffix="dorado/webservice/SpringBeanRPC";
	if(StringUtils.isEmpty(remoteServerUsernamePassword)){
		IUser user=ContextHolder.getLoginUser();
		this.username=user.getUsername();
		this.password=user.getPassword();
	}
	for(String url:remoteServerUrls.split(",")){
		if(url.endsWith("/")){
			url=url+suffix;
		}else{
			url=url+"/"+suffix;				
		}
		WebServiceClient client=new WebServiceClient(url);
		client.setUsernameToken(username, password, true);
		client.setMarshallerClasses(new Class<?>[]{DataRequest.class,DataResponse.class});
		DataResponse res=(DataResponse)client.sendAndReceive(req);
		if(!res.isSuccessful()){
			throw new RuntimeException(res.getReturnValue());
		}
	}
}
 
Example 3
Project: otter-G   File: ActionProtectedImpl.java   Source Code and License 7 votes vote down vote up
public boolean check(String action, String method) {
    if (!StringUtil.isBlank(action)) {
        PatternMatcher matcher = new Perl5Matcher();
        Iterator<ActionPatternHolder> iter = actionPatternList.iterator();
        while (iter.hasNext()) {
            ActionPatternHolder holder = (ActionPatternHolder) iter.next();
            if (StringUtils.isNotEmpty(action) && matcher.matches(action, holder.getActionPattern())
                && StringUtils.isNotEmpty(method) && matcher.matches(method, holder.getMethodPattern())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Candidate is: '" + action + "|" + method + "'; pattern is "
                                 + holder.getActionName() + "|" + holder.getMethodName() + "; matched=true");
                }
                return true;
            }
        }
    }

    return false;
}
 
Example 4
Project: ProjectAres   File: SidebarMatchModule.java   Source Code and License 7 votes vote down vote up
public SidebarMatchModule(Match match, BaseComponent title) {
    super(match);
    this.legacyTitle = StringUtils.left(
        ComponentRenderers.toLegacyText(
            new Component(title, ChatColor.AQUA),
            NullCommandSender.INSTANCE
        ),
        32
    );
}
 
Example 5
Project: Hydrograph   File: OutputConverter.java   Source Code and License 7 votes vote down vote up
/**
 * Caches the parameter value for later substitution in engine xml.
 * @param propertyName
 * @return
 */
protected TypeTrueFalse getTrueFalse(String propertyName) {
	logger.debug("Getting TrueFalse Value for {}={}", new Object[] {propertyName, properties.get(propertyName) });
	TypeTrueFalse typeTrueFalse = new TypeTrueFalse();
	if (StringUtils.isNotBlank((String) properties.get(propertyName))) {
		try{
			Object object = properties.get(propertyName);
			typeTrueFalse.setValue(TrueFalse.fromValue(StringUtils.lowerCase((String)object)));
		}
		catch(IllegalArgumentException exception){
			ComponentXpath.INSTANCE.getXpathMap().put((ComponentXpathConstants.COMPONENT_XPATH_BOOLEAN.value()
						.replace(ID, componentName))
						.replace(Constants.PARAM_PROPERTY_NAME,	propertyName),
							new ComponentsAttributeAndValue(null, properties.get(propertyName).toString()));
			typeTrueFalse.setValue(TrueFalse.TRUE);
		}
	}
	return typeTrueFalse;
}
 
Example 6
Project: goobi-viewer-indexer   File: MetadataHelper.java   Source Code and License 7 votes vote down vote up
/**
 * 
 * @param pi
 * @return
 * @throws FatalIndexerException
 * @should trim identifier
 * @should apply replace rules
 * @should replace spaces with underscores
 * @should replace commas with underscores
 */
public static String applyIdentifierModifications(String pi) throws FatalIndexerException {
    if (StringUtils.isEmpty(pi)) {
        return pi;
    }
    String ret = pi.trim();
    // Apply replace rules defined for the field PI
    List<FieldConfig> configItems = Configuration.getInstance().getMetadataConfigurationManager().getConfigurationListForField(SolrConstants.PI);
    if (configItems != null && !configItems.isEmpty()) {
        Map<Object, String> replaceRules = configItems.get(0).getReplaceRules();
        if (replaceRules != null && !replaceRules.isEmpty()) {
            ret = MetadataHelper.applyReplaceRules(ret, replaceRules);
        }
    }
    ret = ret.replace(" ", "_");
    ret = ret.replace(",", "_");
    ret = ret.replace(":", "_");

    return ret;
}
 
Example 7
Project: bdf2   File: ActionFilter.java   Source Code and License 7 votes vote down vote up
public void filter(String url, Component component, UserAuthentication authentication) throws Exception {
	Action action = (Action) component;
	boolean authority = true;
	String id = action.getId();
	if (StringUtils.isNotEmpty(id)) {
		authority = SecurityUtils.checkComponent(authentication, AuthorityType.read, url, id);
	}
	if (!authority) {
		action.setIgnored(true);
		return;
	}
	if (StringUtils.isNotEmpty(id)) {
		authority = SecurityUtils.checkComponent(authentication, AuthorityType.write, url, id);
	}
	if (!authority) {
		action.setDisabled(true);
		return;
	}
}
 
Example 8
Project: Hydrograph   File: CategoriesDialogSourceComposite.java   Source Code and License 6 votes vote down vote up
private boolean isJarPresentInLibFolder(IPath path) {
	String currentProjectName = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject().getName();
	if (StringUtils.equals(currentProjectName, path.segment(0))
			&& StringUtils.equals(PathConstant.PROJECT_LIB_FOLDER, path.segment(1)))
		return true;
	return false;
}
 
Example 9
Project: Hydrograph   File: MouseHoverOnSchemaGridListener.java   Source Code and License 6 votes vote down vote up
private String setToolTipForGenerateRecordGridRow(GenerateRecordSchemaGridRow generateRecordSchemaGridRow, String componentType){
	
	String tooltip = null;
	
	if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeFrom())
			|| StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeTo())){
		tooltip = setToolTipForSchemaRange(generateRecordSchemaGridRow);			
	}
	
	if (tooltip != null){
		return tooltip;
	}else if(StringUtils.equalsIgnoreCase(generateRecordSchemaGridRow.getDataTypeValue(), JAVA_UTIL_DATE) 
			&& StringUtils.isBlank(generateRecordSchemaGridRow.getDateFormat())){
		return setToolTipForDateFormatIfBlank(generateRecordSchemaGridRow);
	}else if((StringUtils.equalsIgnoreCase(generateRecordSchemaGridRow.getDataTypeValue(), JAVA_MATH_BIG_DECIMAL))){
		return setToolTipForBigDecimal(generateRecordSchemaGridRow, componentType);			
	}
	
	return "";
}
 
Example 10
Project: atlas   File: SimpleLocalCache.java   Source Code and License 6 votes vote down vote up
@Override
public boolean fetchFile(String type, String key, File localFile, boolean folder) throws FileCacheException {

    if (StringUtils.isEmpty(key)) {
        throw new FileCacheException("cache key is empty ");
    }

    File cacheFile = getLocalCacheFile(type, key);

    try {
        if (cacheFile.exists() && cacheFile.length() > 0) {
            if (cacheFile.isDirectory()) {
                FileUtils.copyDirectory(cacheFile, localFile);
            } else {
                FileUtils.copyFile(cacheFile, localFile);
            }
        }
    } catch (IOException e) {
        throw new FileCacheException(e.getMessage(), e);
    }

    return true;
}
 
Example 11
Project: wish-pay   File: AlipayTradePrecreateRequestBuilder.java   Source Code and License 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 12
Project: Reer   File: ProjectReportTask.java   Source Code and License 6 votes vote down vote up
private void render(final Project project, GraphRenderer renderer, boolean lastChild,
                    final StyledTextOutput textOutput) {
    renderer.visit(new Action<StyledTextOutput>() {
        public void execute(StyledTextOutput styledTextOutput) {
            styledTextOutput.text(StringUtils.capitalize(project.toString()));
            if (GUtil.isTrue(project.getDescription())) {
                textOutput.withStyle(Description).format(" - %s", project.getDescription());
            }
        }
    }, lastChild);
    renderer.startChildren();
    List<Project> children = getChildren(project);
    for (Project child : children) {
        render(child, renderer, child == children.get(children.size() - 1), textOutput);
    }
    renderer.completeChildren();
}
 
Example 13
Project: xxl-api   File: XxlApiUserController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/add")
@ResponseBody
   @PermessionLimit(superUser = true)
public ReturnT<String> add(XxlApiUser xxlApiUser) {
	// valid
	if (StringUtils.isBlank(xxlApiUser.getUserName())) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“登录账号”");
	}
	if (StringUtils.isBlank(xxlApiUser.getPassword())) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, "请输入“登录密码”");
	}

	// valid
	XxlApiUser existUser = xxlApiUserDao.findByUserName(xxlApiUser.getUserName());
	if (existUser != null) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, "“登录账号”重复,请更换");
	}

	int ret = xxlApiUserDao.add(xxlApiUser);
	return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
}
 
Example 14
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   Source Code and License 6 votes vote down vote up
/**
 * Gets a HashMap representation of metadata for an entry or set of entries associated with a given container
 * (since each kaltura entry can have multiple permissions related to each collection)
 * NOTE: this will always return a map which is the same size as the input array of entries
 * 
 * OPTIMIZATION method (fetch lots of metadata at once)
 * 
 * @param containerId the id of the container (typically this will be the collection id or site id)
 * @param entryId the id of the entry (can be 1 or many values)
 * @return Map of the {entryId -> Map of metadata {key -> value} }
 */
protected Map<String, Map<String, String>> getMetadataForEntry(String containerId, String... entryIds) {
    if (StringUtils.isEmpty(containerId)) {
        throw new IllegalArgumentException("container id must be set");
    }
    if (entryIds == null || entryIds.length == 0) {
        throw new IllegalArgumentException("entry ids must be set and not empty");
    }
    if (log.isDebugEnabled()) log.debug("getMetadataForEntry(containerId="+containerId+", entryId="+ArrayUtils.toString(entryIds)+")");
    Map<String, Map<String, String>> metadata = new LinkedHashMap<String, Map<String, String>>(entryIds.length);
    // generate the default set of metadata permissions for when they do not exist
    Map<String, String> defaultMetadata = decodeMetadataPermissions(null, false);
    HashSet<String> containerIds = new HashSet<String>(1);
    containerIds.add(containerId);
    // get a set of metadata entries (only includes the entries which have metadata)
    Map<String, Map<String, String>> entriesMetadata = getMetadataForContainersEntries(containerIds, entryIds).get(containerId);
    // construct a map with all entries and fill in any missing metadata with default metadata (to ensure every input entry id is returned)
    for (String entryId : entryIds) {
        if (entriesMetadata.containsKey(entryId)) {
            metadata.put(entryId, entriesMetadata.get(entryId));
        } else {
            metadata.put(entryId, defaultMetadata);
        }
    }
    return metadata;
}
 
Example 15
Project: uckefu   File: TopicRepositoryImpl.java   Source Code and License 6 votes vote down vote up
@Override
public FacetedPage<Topic> findByCon(NativeSearchQueryBuilder searchQueryBuilder,  String q , final int p , final int ps) {
	FacetedPage<Topic> pages  = null ;
	if(!StringUtils.isBlank(q)){
	   	searchQueryBuilder.withQuery(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
	}
   	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps));
    if(elasticsearchTemplate.indexExists(Topic.class)){
    	if(!StringUtils.isBlank(q)){
    		pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class  , new UKResultMapper());
    	}else{
    		pages = elasticsearchTemplate.queryForPage(searchQuery, Topic.class);
    	}
    }
    return pages ; 
}
 
Example 16
Project: lams   File: LanguageUtil.java   Source Code and License 6 votes vote down vote up
/**
    * Returns server default locale; if invalid, uses en_AU.
    */
   public static SupportedLocale getDefaultLocale() {
String localeName = Configuration.get(ConfigurationKeys.SERVER_LANGUAGE);
String langIsoCode = LanguageUtil.DEFAULT_LANGUAGE;
String countryIsoCode = LanguageUtil.DEFAULT_COUNTRY;
if (StringUtils.isNotBlank(localeName) && (localeName.length() > 2)) {
    langIsoCode = localeName.substring(0, 2);
    countryIsoCode = localeName.substring(3);
}

SupportedLocale locale = null;
locale = LanguageUtil.getSupportedLocaleOrNull(langIsoCode, countryIsoCode);
if (locale == null) {
    locale = LanguageUtil.getSupportedLocaleOrNull(LanguageUtil.DEFAULT_LANGUAGE, LanguageUtil.DEFAULT_COUNTRY);
}

return locale;
   }
 
Example 17
Project: ditb   File: IntegrationTestIngestWithACL.java   Source Code and License 6 votes vote down vote up
@Override
protected void processOptions(CommandLine cmd) {
  super.processOptions(cmd);
  if (cmd.hasOption(OPT_SUPERUSER)) {
    superUser = cmd.getOptionValue(OPT_SUPERUSER);
  }
  if (cmd.hasOption(OPT_USERS)) {
    userNames = cmd.getOptionValue(OPT_USERS);
  }
  if (User.isHBaseSecurityEnabled(getConf())) {
    boolean authFileNotFound = false;
    if (cmd.hasOption(OPT_AUTHN)) {
      authnFileName = cmd.getOptionValue(OPT_AUTHN);
      if (StringUtils.isEmpty(authnFileName)) {
        authFileNotFound = true;
      }
    } else {
      authFileNotFound = true;
    }
    if (authFileNotFound) {
      super.printUsage();
      System.exit(EXIT_FAILURE);
    }
  }
}
 
Example 18
Project: netty-socketio-demo   File: WebUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 向url添加新参数
 * 
 * @param targetUrl
 *            目标url
 * @param key
 * @param value
 * @return
 */
public static String addParamToUrl(String targetUrl, String key, String value) {
    if (StringUtils.isBlank(targetUrl)) {
        return StringUtils.EMPTY;
    }
    StringBuffer sb = new StringBuffer();
    int index = targetUrl.indexOf(PARAM_SEPARATOR_QUESTION_MARK);
    if (index == -1) {// 没有问号
        sb.append(targetUrl);
        sb.append(PARAM_SEPARATOR_QUESTION_MARK);
        sb.append(key);
        sb.append(PARAM_SEPARATOR_EQUAL);
        sb.append(value);
    } else {
        sb.append(targetUrl.substring(0, index + 1));
        sb.append(key);
        sb.append(PARAM_SEPARATOR_EQUAL);
        sb.append(value);
        if (index != (targetUrl.length() - 1)) {// 问号不在最末尾
            sb.append(PARAM_SEPARATOR_AND);
            sb.append(targetUrl.substring(index + 1));
        }
    }
    return sb.toString();
}
 
Example 19
Project: uflo   File: HistoryProcessVariableQueryImpl.java   Source Code and License 6 votes vote down vote up
private void buildCriteria(Criteria criteria,boolean queryCount){
	if(!queryCount && firstResult>0){
		criteria.setFirstResult(firstResult);			
	}
	if(!queryCount && maxResults>0){
		criteria.setMaxResults(maxResults);			
	}
	if(historyProcessInstanceId>0){
		criteria.add(Restrictions.eq("historyProcessInstanceId",historyProcessInstanceId));
	}
	if(StringUtils.isNotEmpty(key)){
		criteria.add(Restrictions.eq("key", key));
	}
	
	if(!queryCount){
		for(String ascProperty:ascOrders){
			criteria.addOrder(Order.asc(ascProperty));
		}
		for(String descProperty:descOrders){
			criteria.addOrder(Order.desc(descProperty));
		}
	}
}
 
Example 20
Project: lams   File: AuthoringAction.java   Source Code and License 6 votes vote down vote up
/**
    * Get units from <code>HttpRequest</code>
    *
    * @param request
    */
   private TreeSet<AssessmentUnit> getUnitsFromRequest(HttpServletRequest request, boolean isForSaving) {
Map<String, String> paramMap = splitRequestParameter(request, AssessmentConstants.ATTR_UNIT_LIST);

int count = NumberUtils.toInt(paramMap.get(AssessmentConstants.ATTR_UNIT_COUNT));
TreeSet<AssessmentUnit> unitList = new TreeSet<AssessmentUnit>(new SequencableComparator());
for (int i = 0; i < count; i++) {
    String unitStr = paramMap.get(AssessmentConstants.ATTR_UNIT_UNIT_PREFIX + i);
    if (StringUtils.isBlank(unitStr) && isForSaving) {
	continue;
    }

    AssessmentUnit unit = new AssessmentUnit();
    String sequenceId = paramMap.get(AssessmentConstants.ATTR_UNIT_SEQUENCE_ID_PREFIX + i);
    unit.setSequenceId(NumberUtils.toInt(sequenceId));
    unit.setUnit(unitStr);
    float multiplier = Float.valueOf(paramMap.get(AssessmentConstants.ATTR_UNIT_MULTIPLIER_PREFIX + i));
    unit.setMultiplier(multiplier);
    unitList.add(unit);
}

return unitList;
   }
 
Example 21
Project: Uranium   File: CraftIpBanList.java   Source Code and License 6 votes vote down vote up
@Override
public org.bukkit.BanEntry addBan(String target, String reason, Date expires, String source) {
    Validate.notNull(target, "Ban target cannot be null");

    IPBanEntry entry = new IPBanEntry(target, new Date(),
            StringUtils.isBlank(source) ? null : source, expires,
            StringUtils.isBlank(reason) ? null : reason);

    list.func_152687_a(entry);

    try {
        list.func_152678_f();
    } catch (IOException ex) {
        MinecraftServer.getLogger().error("Failed to save banned-ips.json, " + ex.getMessage());
    }

    return new CraftIpBanEntry(target, entry, list);
}
 
Example 22
Project: Hydrograph   File: TextBoxWithLabelWidget.java   Source Code and License 6 votes vote down vote up
private void updateAbsoluteXPathIfChanged(List<AbstractWidget> widgetList,String previousValue) {
 if(!textBox.getText().equals(previousValue)){
	 ELTSchemaGridWidget eltSchemaGridWidget = getSchemaWidget(widgetList);
	 List<GridRow> gridRows=eltSchemaGridWidget.getSchemaGridRowList();
	 if(StringUtils.isNotBlank(textBox.getText())){
		 for(GridRow gridRow:gridRows){
			 if(gridRow instanceof XPathGridRow){
				 XPathGridRow xPathGridRow=(XPathGridRow)gridRow;
				 xPathGridRow.setAbsolutexPath(xPathGridRow.getXPath());
				 if(!xPathGridRow.getAbsolutexPath().startsWith(textBox.getText())){
					 xPathGridRow.setAbsolutexPath(textBox.getText()+Path.SEPARATOR+xPathGridRow.getAbsolutexPath());
				 }
			 }
		 }
	 }
	 eltSchemaGridWidget.showHideErrorSymbol(widgetList);
	 
 }

}
 
Example 23
Project: Dragonfly   File: PieceState.java   Source Code and License 6 votes vote down vote up
public boolean offerProducer(String cid) {
    if (StringUtils.isBlank(cid)) {
        return false;
    }
    if (superCid == null && cid.startsWith(Constants.SUPER_NODE_CID)) {
        superCid = cid;
    } else {
        synchronized (pieceContainer) {
            if (!pieceContainer.contains(cid)) {
                if (pieceContainer.offer(cid)) {
                    distributedCount++;
                }
            } else {
                logger.warn("cid:{} is already in queue", cid);
            }
        }
    }
    return true;
}
 
Example 24
Project: Recreator   File: Configurable.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("all")
public static Object colorzine(Object o) {
    if (o instanceof String) {
        return StringUtils.replaceChars((String) o, '&', '§');
    }
    if (o instanceof List) {
        List list = (List) o;
        for (Object obj : list) {
            if (obj instanceof String) {
                list.set(list.indexOf(obj), StringUtils.replaceChars((String) obj, '&', '§'));
            }
        }
        return list;
    }
    return o;
}
 
Example 25
Project: lams   File: EventNotificationService.java   Source Code and License 6 votes vote down vote up
@Override
   public void unsubscribe(String scope, String name, Long eventSessionId, Integer userId,
    AbstractDeliveryMethod deliveryMethod) throws InvalidParameterException {
if (scope == null) {
    throw new InvalidParameterException("Scope should not be null.");
}
if (StringUtils.isBlank(name)) {
    throw new InvalidParameterException("Name should not be blank.");
}
if (userId == null) {
    throw new InvalidParameterException("User ID should not be null.");
}
if (deliveryMethod == null) {
    throw new InvalidParameterException("Delivery nethod should not be null.");
}
Event event = eventDAO.getEvent(scope, name, eventSessionId);
if (event == null) {
    throw new InvalidParameterException("An event with the given parameters does not exist.");
}
unsubscribe(event, userId, deliveryMethod);
   }
 
Example 26
Project: uflo   File: ForeachParser.java   Source Code and License 6 votes vote down vote up
public Object parse(Element element, long processId, boolean parseChildren) {
	ForeachNode node=new ForeachNode();
	node.setProcessId(processId);
	parseNodeCommonInfo(element, node);
	node.setSequenceFlows(parseFlowElement(element,processId,parseChildren));
	String type=element.attributeValue("foreach-type");
	if(StringUtils.isNotEmpty(type)){
		node.setForeachType(ForeachType.valueOf(type));			
	}
	node.setVariable(unescape(element.attributeValue("var")));
	if(StringUtils.isNotBlank(element.attributeValue("process-variable"))){
		node.setProcessVariable(unescape(element.attributeValue("process-variable")));			
	}else{
		node.setProcessVariable(unescape(element.attributeValue("in")));						
	}
	node.setHandlerBean(unescape(element.attributeValue("handler-bean")));
	NodeDiagram diagram=parseDiagram(element);
	diagram.setIcon("/icons/foreach.svg");
	diagram.setShapeType(ShapeType.Circle);
	diagram.setBorderWidth(1);
	node.setDiagram(diagram);
	return node;
}
 
Example 27
Project: -Spring-SpringMVC-Mybatis-   File: CmsCommentController.java   Source Code and License 6 votes vote down vote up
@ApiOperation(value = "评论列表")
@RequiresPermissions("cms:comment:read")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public Object list(
		@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
		@RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
		@RequestParam(required = false, value = "sort") String sort,
		@RequestParam(required = false, value = "order") String order) {
	CmsCommentExample cmsCommentExample = new CmsCommentExample();
	if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
		cmsCommentExample.setOrderByClause(sort + " " + order);
	}
	List<CmsComment> rows = cmsCommentService.selectByExampleWithBLOBsForOffsetPage(cmsCommentExample, offset, limit);
	long total = cmsCommentService.countByExample(cmsCommentExample);
	Map<String, Object> result = new HashMap<>();
	result.put("rows", rows);
	result.put("total", total);
	return result;
}
 
Example 28
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   Source Code and License 6 votes vote down vote up
/**
 * parses an XSD data file from src/main/resources
 * 
 * @param xsdFileName the name of the XSD file
 * @return string representation of the XSD file content OR null if file not found
 * @throws RuntimeException if file cannot be read
 */
private String parseXsdDataFile(String xsdFileName) {
    if (StringUtils.isEmpty(xsdFileName)) {
        throw new IllegalArgumentException("XSD file name is invalid");
    }
    String xsdData = null;
    // read the metadata XSD, load it into a string variable
    try {
        InputStream xmlStream = this.getClass().getClassLoader().getResourceAsStream(xsdFileName);
        if (xmlStream != null) {
            long length = xmlStream.available();
            byte[] bytes = new byte[(int) length];
            xmlStream.read(bytes);
            xsdData = new String(bytes);
        }
    } catch (Exception e) {
        throw new RuntimeException("Error reading XSD schema file: " + xsdFileName + " :: " + e);
    }
    return xsdData;
}
 
Example 29
Project: lams   File: EventNotificationService.java   Source Code and License 6 votes vote down vote up
@Override
   public void unsubscribe(String scope, String name, Long eventSessionId, Integer userId)
    throws InvalidParameterException {
if (scope == null) {
    throw new InvalidParameterException("Scope should not be null.");
}
if (StringUtils.isBlank(name)) {
    throw new InvalidParameterException("Name should not be blank.");
}
if (userId == null) {
    throw new InvalidParameterException("User ID should not be null.");
}
Event event = eventDAO.getEvent(scope, name, eventSessionId);
if (event == null) {
    throw new InvalidParameterException("An event with the given parameters does not exist.");
}
unsubscribe(event, userId);
   }
 
Example 30
Project: filter   File: PreRequestVerificationServiceImpl.java   Source Code and License 5 votes vote down vote up
private void tokenCheck(String url,String token) throws VerificationException{
    if (!filterZuulCheckHelper.needUrlTokenCheck(url)) {
        if (StringUtils.isNotEmpty(token)) {
            String tokenValue = tokenService.getToken(token);
            if (StringUtils.isEmpty(tokenValue)) {
                throw new VerificationException(VerificationState.STATE_TOKEN_ERROR);
            }
        } else {
            throw new VerificationException(VerificationState.STATE_TOKEN_ERROR);
        }
    }
}
 
Example 31
Project: Spring-Boot-Server   File: AppUserMessgeRestful.java   Source Code and License 5 votes vote down vote up
/**
 * 添加推送表(在推送的时候添加。。消息中心内不处理)
 * @return
 */
@RequestMapping(value = "/addPushMessage")
@ResponseBody
public PageData addPushMessage(@RequestBody PageData pd) throws Exception {
	if (StringUtils.isBlank(pd.getString("M_GOAL")) || StringUtils.isBlank(pd.getString("M_TYPE")) || StringUtils.isBlank(pd.getString("M_STATE"))) {
		return WebResult.requestFailed(10001, "参数缺失!", null);
	}
	else {
		appUserMessageMapper.addPushMessage(pd);
		return WebResult.requestSuccess();
	}
}
 
Example 32
Project: kaltura-ce-sakai-extension   File: MediaService.java   Source Code and License 5 votes vote down vote up
/**
 * This will fill in data in the media item which is not available in the model,
 * the collection should ideally be set, checks permissions and fails if not allowed
 * 
 * This will NOT fetch the item data from the DB OR fetch kaltura data from the server
 * 
 * @param item the item to populate
 * @throws SecurityException if not allowed
 */
public void populateMediaItemData(MediaItem item) {
    if (StringUtils.isNotBlank(item.getOwnerId()) && item.getAuthor() == null) {
        item.indicateAuthor( external.getUser(item.getOwnerId()) );
    }
    // no need to check if the current user id is set because check was already done
    if (item.getCurrentUsername() == null) {
        checkPermControlMI(item); // populate security data
    }
    this.kalturaAPIService.populateMediaItemKalturaData(item);
}
 
Example 33
Project: bdf2   File: AnnotationPackagesBeanParser.java   Source Code and License 5 votes vote down vote up
@Override
protected void doParse(Element element, ParserContext parserContext,BeanDefinitionBuilder builder) {
	String packages=element.getAttribute("packages");
	List<String> list=new ArrayList<String>();
	for(String p:packages.split(",")){
		list.add(p);
	}
	builder.addPropertyValue("scanPackages", list);
	String dataSourceRegisterName=element.getAttribute("dataSourceRegisterName");
	if(StringUtils.isNotEmpty(dataSourceRegisterName)){
		builder.addPropertyValue("dataSourceRegisterName", dataSourceRegisterName);
	}
}
 
Example 34
Project: Hydrograph   File: RunSQLConverter.java   Source Code and License 5 votes vote down vote up
private void setDatabasePassword(RunSQL runSQL) {
	RunSQL.DbPassword databasePassword = new RunSQL.DbPassword();
	String databasePasswordValue = (String) properties.get(Constants.PASSWORD_WIDGET_NAME);
	if(StringUtils.isNotBlank(databasePasswordValue)){
		databasePassword.setPassword(databasePasswordValue);
		runSQL.setDbPassword(databasePassword);
	}
}
 
Example 35
Project: logistimo-web-service   File: NotificationBuilder.java   Source Code and License 5 votes vote down vote up
private JSONObject buildNotifyOptions(NotificationsConfigModel model) throws ServiceException {
  JSONObject jsonNotify = new JSONObject();
  if (model.co) {
    putJsonObject(jsonNotify, "customers", model.cot, null);
  }
  if (model.vn) {
    putJsonObject(jsonNotify, "vendors", model.vnt, null);
  }
  if (model.ad) {
    putJsonObject(jsonNotify, "admins", model.adt, null);
  }
  if (model.cr) {
    putJsonObject(jsonNotify, "creator", model.crt, null);
  }
  if (model.usr) {
    if (StringUtils.isNotEmpty(model.uid)) {
      putJsonObject(jsonNotify, "users", model.ust, model.uid);
    }

    if (StringUtils.isNotEmpty(model.usrTgs)) {
      putJsonObject(jsonNotify, "user_tags", model.ust, model.usrTgs);
    }
  }
  if (model.au) {
    putJsonObject(jsonNotify, "asset_users", model.aut, null);
  }
  return jsonNotify;
}
 
Example 36
Project: alfresco-remote-api   File: ResourceLookupDictionary.java   Source Code and License 5 votes vote down vote up
/**
 * Locates a resource by URI path and wraps it in an invoker
 * 
 * This will probably get refactored later when we work out what we 
 * are doing with the discoverability model.  It shouldn't create
 * a new instance every time.
 */
@Override
public ResourceWithMetadata locateResource(Api api,Map<String, String> templateVars, HttpMethod httpMethod)
{
    String collectionName = templateVars.get(COLLECTION_RESOURCE);
    String entityId = templateVars.get(ENTITY_ID);
    String resourceName = templateVars.get(RELATIONSHIP_RESOURCE);
    String property =  templateVars.get(PROPERTY);

    if (StringUtils.isNotBlank(property))
    {
        return locateRelationPropertyResource(api,collectionName ,resourceName, property,httpMethod);
    }
    if (StringUtils.isNotBlank(resourceName))
    {
        return locateRelationResource(api,collectionName ,resourceName,httpMethod);
    }
    if (StringUtils.isNotBlank(entityId))
    {
        return locateEntityResource(api,collectionName,httpMethod);
    }
    if (StringUtils.isNotBlank(collectionName))
    {
        return locateEntityResource(api,collectionName,httpMethod);
    }
    if (logger.isDebugEnabled())
    {
        logger.debug("Unable to locate a resource for "+templateVars);
    }
    throw new NotFoundException();

}
 
Example 37
Project: Hydrograph   File: LookupMapDialog.java   Source Code and License 5 votes vote down vote up
private LookupMapProperty getMappingTableItem(List<LookupMapProperty> mappingTableItemListClone, String fieldName) {
	for(LookupMapProperty row:mappingTableItemListClone){
		if(StringUtils.equals(fieldName, row.getOutput_Field())){
			return row;
		}
	}
	return null;
}
 
Example 38
Project: lambo   File: UpmsPermissionController.java   Source Code and License 5 votes vote down vote up
@ApiOperation(value = "权限列表")
@RequiresPermissions("upms:permission:read")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public Object list(
        @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
        @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
        @RequestParam(required = false, defaultValue = "", value = "search") String search,
        @RequestParam(required = false, defaultValue = "0", value = "type") int type,
        @RequestParam(required = false, defaultValue = "0", value = "systemId") int systemId,
        @RequestParam(required = false, value = "sort") String sort,
        @RequestParam(required = false, value = "order") String order) {
    UpmsPermissionExample upmsPermissionExample = new UpmsPermissionExample();
    UpmsPermissionExample.Criteria criteria = upmsPermissionExample.createCriteria();
    if (0 != type) {
        criteria.andTypeEqualTo((byte) type);
    }
    if (0 != systemId) {
        criteria.andSystemIdEqualTo(systemId);
    }
    if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
        upmsPermissionExample.setOrderByClause(sort + " " + order);
    }
    if (StringUtils.isNotBlank(search)) {
        upmsPermissionExample.or()
                .andNameLike("%" + search + "%");
    }
    List<UpmsPermission> rows = upmsPermissionService.selectByExampleForOffsetPage(upmsPermissionExample, offset, limit);
    long total = upmsPermissionService.countByExample(upmsPermissionExample);
    Map<String, Object> result = new HashMap<>();
    result.put("rows", rows);
    result.put("total", total);
    return result;
}
 
Example 39
Project: Hydrograph   File: XPathSchemaGridCellModifier.java   Source Code and License 5 votes vote down vote up
private boolean isResetNeeded(XPathGridRow xPathGridRow, String property) {
	if(XPathSchemaGridWidget.DATATYPE.equals(property) && StringUtils.isNotBlank(xPathGridRow.getDataTypeValue())){
		if(DataType.INTEGER_CLASS.equals(xPathGridRow.getDataTypeValue()) 
				||DataType.LONG_CLASS.equals(xPathGridRow.getDataTypeValue())
				||DataType.STRING_CLASS.equals(xPathGridRow.getDataTypeValue())
				||DataType.SHORT_CLASS.equals(xPathGridRow.getDataTypeValue())
				||DataType.BOOLEAN_CLASS.equals(xPathGridRow.getDataTypeValue())
				||DataType.FLOAT_CLASS.equals(xPathGridRow.getDataTypeValue())
				||DataType.DOUBLE_CLASS.equals(xPathGridRow.getDataTypeValue())
				||DataType.DATE_CLASS.equals(xPathGridRow.getDataTypeValue())){
			return true;
		}	
	}
	return false;
}
 
Example 40
Project: Hydrograph   File: InputAdditionalParametersDialog.java   Source Code and License 5 votes vote down vote up
/**
 * Create the dialog.
 * 
 * @param parentShell
 * @param windowTitle
 * @param propertyDialogButtonBar
 * @param schemaFields
 * @param initialMap
 * @param cursor 
 */
public InputAdditionalParametersDialog(Shell parentShell, String windowTitle,
		PropertyDialogButtonBar propertyDialogButtonBar, List<String> schemaFields,
		Map<String, Object> initialMap, Cursor cursor) {
	super(parentShell);
	setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.WRAP | SWT.APPLICATION_MODAL | SWT.RESIZE);
	if (StringUtils.isNotBlank(windowTitle))
		windowLabel = windowTitle;
	else
		windowLabel = Messages.ADDITIONAL_PARAMETERS_FOR_DB_WINDOW_LABEL;
	this.propertyDialogButtonBar = propertyDialogButtonBar;
	this.schemaFields = schemaFields;
	this.additionalParameterValue = initialMap;
	this.cursor = cursor;
}
 
Example 41
Project: atlas   File: LocalSignedJarBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Closes the Jar archive by creating the manifest, and signing the archive.
 *
 * @throws IOException
 * @throws SigningException
 */
public void close() throws IOException, SigningException {
    if (mManifest != null) {
        // write the manifest to the jar file
        mOutputJar.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
        mManifest.write(mOutputJar);

        try {
            // CERT.SF
            Signature signature = Signature.getInstance("SHA1with" + mKey.getAlgorithm());
            signature.initSign(mKey);
            if (StringUtils.isBlank(mSignFile)) {
                mOutputJar.putNextEntry(new JarEntry("META-INF/CERT.SF"));
            } else {
                mOutputJar.putNextEntry(new JarEntry("META-INF/" + mSignFile + ".SF"));
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            writeSignatureFile(baos);
            byte[] signedData = baos.toByteArray();
            mOutputJar.write(signedData);

            if (StringUtils.isBlank(mSignFile)) {
                mOutputJar.putNextEntry(new JarEntry("META-INF/CERT." + mKey.getAlgorithm()));
            } else {
                mOutputJar.putNextEntry(new JarEntry("META-INF/" +
                                                             mSignFile +
                                                             "." +
                                                             mKey.getAlgorithm()));
            }
            // CERT.*
            writeSignatureBlock(new CMSProcessableByteArray(signedData), mCertificate, mKey);
        } catch (Exception e) {
            throw new SigningException(e);
        }
    }

    mOutputJar.close();
    mOutputJar = null;
}
 
Example 42
Project: Hydrograph   File: DataViewerFileManager.java   Source Code and License 5 votes vote down vote up
private String getFileName(String csvDebugFileAbsolutePath) {
	
	if (StringUtils.isNotBlank(csvDebugFileAbsolutePath)) {
	String	debugFileName = csvDebugFileAbsolutePath
				.substring(csvDebugFileAbsolutePath.lastIndexOf("/") + 1, csvDebugFileAbsolutePath.length())
				.replace(DEBUG_DATA_FILE_EXTENTION, "").trim();
		if (debugFileName != null) {
			return getDataViewerDebugFile(debugFileName);
		}
	}
	return null;
}
 
Example 43
Project: bdf2   File: AutoFormHandler.java   Source Code and License 5 votes vote down vote up
public void handle(IComponentService componentService, Object control,
		String assignTargetId,Map<String,ComponentInfo> mapInCache) {
	AutoForm autoForm=this.getControl(control);
	String controlId=autoForm.getId();
	if(StringUtils.isNotEmpty(controlId)){
		setControlPropertiesAndEvents(componentService, assignTargetId,autoForm, controlId,"AutoForm",mapInCache);
	}
	List<Control> controls=autoForm.getElements();
	if(controls==null)return;
	for(Control con:controls){
		String id=con.getId();
		if(con instanceof AutoFormElement){
			if(StringUtils.isEmpty(id)){
				AutoFormElement element=(AutoFormElement)con;
				id=element.getId();
				if(StringUtils.isEmpty(id)){
					id=element.getName();
				}
				if(StringUtils.isEmpty(id)){
					id=element.getProperty();
				}
			}
		}
		if(StringUtils.isNotEmpty(id)){
			setControlPropertiesAndEvents(componentService, assignTargetId,con,id,"AutoFormElement",mapInCache);				
		}
		if(con==null || !(con instanceof Container) || StringUtils.isEmpty(id))continue;
		Container container=(Container)con;
		sortChildControls(componentService, assignTargetId,id,con.getClass().getSimpleName(),container.getChildren(),mapInCache);
	}
	sortChildControls(componentService, assignTargetId,controlId,"AutoForm",controls,mapInCache);
}
 
Example 44
Project: Hydrograph   File: ELTSchemaGridWidget.java   Source Code and License 5 votes vote down vote up
private void schemaFromConnectedLinks() {
 Schema schema=null;
 Map<String,Schema> oldSchemaMap=new TreeMap<>();
 if (StringUtils.equalsIgnoreCase(getComponent().getCategory(), Constants.OUTPUT))
	 for (Link link : getComponent().getTargetConnections()) {
		 if(SchemaPropagation.INSTANCE.checkUnusedSocketAsSourceTerminal(link)){
			 String unusedSocketId=link.getSourceTerminal();
			 for(Link innerLink:link.getSource().getTargetConnections()){
				 if(innerLink.getTargetTerminal().equals(SchemaPropagation.INSTANCE.getInSocketForUnusedSocket(unusedSocketId))){
					 schema=SubjobUtility.INSTANCE.getSchemaFromPreviousComponentSchema(getComponent(), innerLink); 
					 break;
				 }
			}
		 }
		 else{
			 schema=SubjobUtility.INSTANCE.getSchemaFromPreviousComponentSchema(getComponent(), link);
		 }		 
		 if(schema!=null)
		 {	 
			List<FixedWidthGridRow> fixedWidthGridRows=
					SchemaPropagation.INSTANCE.convertGridRowsSchemaToFixedSchemaGridRows(schema.getGridRow());
			 if (this.properties != null && this.schemaGridRowList != null && !this.schemaGridRowList.isEmpty()) {
			 if (isAnyUpdateAvailableOnPropagatedSchema(schema)) {
				 this.properties = getPropagatedSchema(fixedWidthGridRows);
			 } else {
					showMessage();
			 }
		 } else {
			 this.properties = getPropagatedSchema(fixedWidthGridRows);
		 }
			 oldSchemaMap.put(link.getTargetTerminal(),schema );	
		 }
	 }
 getComponent().getProperties().put(Constants.PREVIOUS_COMPONENT_OLD_SCHEMA, oldSchemaMap);
}
 
Example 45
Project: urule   File: NotNullAssertor.java   Source Code and License 5 votes vote down vote up
public boolean eval(Object left, Object right,Datatype datatype) {
	if(left!=null && StringUtils.isNotBlank(left.toString())){
		return true;
	}else{
		return false;
	}
}
 
Example 46
Project: Spring-Boot-Server   File: AppUserAuthRestful.java   Source Code and License 5 votes vote down vote up
/**
 * 不足4位不足4位
 * @param code
 * @return
 */
public String fillVCode(String code){
	if(!StringUtils.isBlank(code)){
		for (int i = code.length();i<4;i++){
			code = "0"+code;
		}
	}
	return code;
}
 
Example 47
Project: cas-modules   File: X509CredentialsToPrincipalResolver.java   Source Code and License 5 votes vote down vote up
public static String getDistinguishedNameField(String certificateSubject, String fieldName) {
   String fieldValue = substringAfter(certificateSubject, fieldName + "=");
   // If serial number contains ',' then it is not the last value
   if (StringUtils.contains(fieldValue, ',')) {
      fieldValue = substringBefore(fieldValue, ",");
   }
   if (log.isDebugEnabled()) {
      log.debug("Parsed " + fieldName + " =" + fieldValue);
   }
   return trimToNull(fieldValue);
}
 
Example 48
Project: otter-G   File: LogRecordTab.java   Source Code and License 5 votes vote down vote up
public void execute(@Param("pageIndex") int pageIndex, @Param("searchKey") String searchKey,
                    @Param("pipelineId") Long pipelineId, Context context) throws Exception {

    @SuppressWarnings("unchecked")
    Map<String, Object> condition = new HashMap<String, Object>();
    if ("请输入关键字(目前支持log内容关键字搜索)".equals(searchKey)) {
        searchKey = "";
    }

    condition.put("pipelineId", pipelineId);
    condition.put("searchKey", searchKey);

    int count = logRecordService.getCount(condition);
    Paginator paginator = new Paginator();
    paginator.setItems(count);
    paginator.setPage(pageIndex);

    condition.put("offset", paginator.getOffset());
    condition.put("length", paginator.getLength());

    List<LogRecord> logRecords = logRecordService.listByCondition(condition);
    for (LogRecord logRecord : logRecords) {
        if (!StringUtils.isEmpty(logRecord.getMessage())) {
            logRecord.setMessage(logRecord.getMessage().replaceAll("\n\t", "<br/>"));
        }
    }

    context.put("logRecords", logRecords);
    context.put("paginator", paginator);
    context.put("searchKey", searchKey);
    context.put("pipelineId", pipelineId);
    Channel channel = channelService.findByPipelineId(pipelineId);
    context.put("channel", channel);
}
 
Example 49
Project: DBus   File: CommandCtrl.java   Source Code and License 5 votes vote down vote up
private static String getTopologyId(String stormUIAddr, String topologyName){
    String url = "http://"+stormUIAddr+"/api/v1/topology/summary";
    List<TopologySummary> lstTopo = new ArrayList<TopologySummary>();
    String topoId = null;
    try{
        String resp =HttpRequest.getInstance().doGet(url, "utf-8");
        if(StringUtils.isNotBlank(resp)){
            ObjectMapper mapper = JsonUtil.getObjectMapper();
            JsonNode node = mapper.readTree(resp);
            JsonNode topoNode = node.get("topologies");
            if(topoNode!=null){
                String topoStr = topoNode.toString();
                if(StringUtils.isNotBlank(topoStr)){
                    JavaType javaType = getCollectionType(ArrayList.class, TopologySummary.class);
                    lstTopo = mapper.readValue(topoStr, javaType);
                }
            }
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    for(TopologySummary topoSumm : lstTopo){
        if(topoSumm.getTopologyName()!=null && topoSumm.getTopologyName().equals(topologyName)){
            topoId = topoSumm.getTopologyId();
            break;
        }
    }
    return topoId;
}
 
Example 50
Project: canal-elasticsearch   File: IPAddressUtil.java   Source Code and License 5 votes vote down vote up
public static boolean isAddress(String address) {
    if (!StringUtils.isEmpty(address)) {
        String[] hostPort = address.trim().split(":");
        if (hostPort.length == 2) {
            String ip = hostPort[0];
            String portStr = hostPort[1];
            if (sun.net.util.IPAddressUtil.isIPv4LiteralAddress(ip) && StringUtils.isNumeric(portStr)) {
                Integer port = Integer.valueOf(portStr);
                return 0 < port && port < 65535;
            }
        }
    }
    return false;
}
 
Example 51
Project: logistimo-web-service   File: AssetManagementServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getVendorIdsForReports(String did) {
  PersistenceManager pm = PMF.get().getPersistenceManager();
  Query query;
  StringBuilder vidQuery = new StringBuilder();
  StringBuilder vids =  new StringBuilder("");
  if (StringUtils.isNotEmpty(did)) {
    vidQuery
        .append("SELECT DISTINCT VID FROM ASSET WHERE KID IN (")
        .append("SELECT KIOSKID FROM KIOSK K ,KIOSK_DOMAINS KD WHERE ")
        .append("K.KIOSKID = KD.KIOSKID_OID AND KD.DOMAIN_ID = ").append(did)
        .append(CharacterConstants.C_BRACKET);
  }
  query = pm.newQuery("javax.jdo.query.SQL", vidQuery.toString());
  try{
  List<String> result = (List) query.execute();
  for(int i=0;i<result.size();i++){
      if(i!=0){
          vids.append(CharacterConstants.COMMA);
      }
      vids.append(CharacterConstants.S_QUOTE).append(result.get(i))
              .append(CharacterConstants.S_QUOTE);
  }
  return vids.toString();
  } catch (Exception e){
    xLogger.warn("Error while fetching vendor ids for reports", e);
  } finally {
      if(query != null) {
          query.closeAll();
      }
      pm.close();
  }
  return null;
}
 
Example 52
Project: soundwave   File: EsBulkResponseSummary.java   Source Code and License 5 votes vote down vote up
public String getFailedMessage(int max) {
  int count = 0;
  StringBuilder stringBuilder = new StringBuilder();
  for (Map.Entry<String, String> entry : failed.entrySet()) {
    if (StringUtils.indexOf(entry.getValue(), "VersionConflictEngineException") < 0) {
      stringBuilder.append(String.format("id:%s error:%s", entry.getKey(), entry.getValue()));
      count++;
      if (count >= max) {
        break;
      }
    }
  }
  return stringBuilder.toString();
}
 
Example 53
Project: lams   File: ImportService.java   Source Code and License 5 votes vote down vote up
@Override
   public boolean isUserSpreadsheet(FormFile fileItem) throws IOException {
HSSFSheet sheet = getSheet(fileItem);
HSSFRow row = sheet.getRow(sheet.getFirstRowNum());
String string = parseStringCell(row.getCell(ImportService.PASSWORD));
return (StringUtils.equals(string, "* password")) ? true : false;
   }
 
Example 54
Project: easycms   File: LoginServlet.java   Source Code and License 5 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("login doGet");
	String username = request.getParameter("username");
	if (StringUtils.isEmpty(username)) {
		request.setAttribute("msg", "请输入账号!");
		request.getRequestDispatcher("/login.jsp").forward(request, response);
		return;
	}
	String password = request.getParameter("password");
	if (StringUtils.isEmpty(password)) {
		request.setAttribute("msg", "请输入密码!");
		request.getRequestDispatcher("/login.jsp").forward(request, response);
		return;
	}
	Subject currentUser = SecurityUtils.getSubject();
	UsernamePasswordToken token = new UsernamePasswordToken(username, password);
	try {
		currentUser.login(token);
		System.out.println("认证成功");
		response.sendRedirect("cms");
	} catch (AuthenticationException e) {
		e.printStackTrace();
		System.out.println("认证失败");
		request.setAttribute("msg", "账号密码错误!");
		request.getRequestDispatcher("/login.jsp").forward(request, response);
		return;
	}
}
 
Example 55
Project: Hydrograph   File: SelectionDatabaseWidget.java   Source Code and License 5 votes vote down vote up
/**
	 * Extracts the details from MetaStore for DB components
	 * @param oracleDatabaseValues
	 * @param host
	 * @param port_no
	 */
	private void extractOracleMetaStoreDetails(List<String> oracleDatabaseValues) {
		
String host = DataBaseUtility.getInstance().getServiceHost();
		
		if(null!=host&& StringUtils.isNotBlank(host)){
			
				DatabaseParameterType parameterType =  getDatabaseConnectionDetails();
				validateDatabaseFields(parameterType);
		
				HiveTableSchema databaseTableSchema = DataBaseUtility.getInstance()
					.extractDatabaseDetails(oracleDatabaseValues, parameterType,host);
			
				if (null != databaseTableSchema) {

					for (AbstractWidget abstractWgt : widgets) {
					
						if (abstractWgt.getProperty().getPropertyName().equalsIgnoreCase(Constants.SCHEMA_PROPERTY_NAME)) {
							abstractWgt.refresh(getComponentSchema(databaseTableSchema));
						}
					}
	
					WidgetUtility.createMessageBox(Messages.METASTORE_IMPORT_SUCCESS,Messages.INFORMATION , SWT.ICON_INFORMATION);
					propertyDialogButtonBar.enableApplyButton(true);
				}
		}
		else{
			WidgetUtility.createMessageBox(Messages.HOST_NAME_BLANK_ERROR,Messages.ERROR , SWT.ICON_ERROR);
			}
	
	}
 
Example 56
Project: Reer   File: HtmlReportRenderer.java   Source Code and License 5 votes vote down vote up
Resource addResource(URL source) {
    String urlString = source.toString();
    Resource resource = resources.get(urlString);
    if (resource == null) {
        String name = StringUtils.substringAfterLast(source.getPath(), "/");
        String type = StringUtils.substringAfterLast(source.getPath(), ".");
        if (type.equalsIgnoreCase("png") || type.equalsIgnoreCase("gif")) {
            type = "images";
        }
        String path = type + "/" + name;
        resource = new Resource(source, path);
        resources.put(urlString, resource);
    }
    return resource;
}
 
Example 57
Project: spring_mybatis_shiro   File: CookieUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 添加cookie
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie名称
 * @param value
 *            cookie值
 * @param maxAge
 *            有效期(单位: 秒)
 * @param path
 *            路径
 * @param domain
 *            域
 * @param secure
 *            是否启用加密
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value,
		Integer maxAge, String path, String domain, Boolean secure) {
	Assert.notNull(request);
	Assert.notNull(response);
	Assert.hasText(name);
	try {
		name = URLEncoder.encode(name, "UTF-8");
		value = URLEncoder.encode(value, "UTF-8");
		Cookie cookie = new Cookie(name, value);
		if (maxAge != null) {
			cookie.setMaxAge(maxAge);
		}
		if (StringUtils.isNotEmpty(path)) {
			cookie.setPath(path);
		}
		if (StringUtils.isNotEmpty(domain)) {
			cookie.setDomain(domain);
		}
		if (secure != null) {
			cookie.setSecure(secure);
		}
		response.addCookie(cookie);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
}
 
Example 58
Project: logistimo-web-service   File: EntityMover.java   Source Code and License 5 votes vote down vote up
/**
 * Moves list of given entity {@code kiosks} from its source domain to {@code destDomainId}.
 *
 * @param kiosks       List of kiosk ids to be moved to other domain.
 * @param destDomainId Destination domain id of all kiosks to be moved.
 * @throws ServiceException when there is error in fetching object.
 *
 * @see EntityMoveHelper
 */
public static void moveEntitiesToDomain(List<Long> kiosks, Long destDomainId, String sDid)
    throws ServiceException {
  EntitiesService as = Services.getService(EntitiesServiceImpl.class, null);
  List<IKiosk> kioskList = as.getKiosksByIds(kiosks);
  Set<String> users = EntityMoveHelper.extractUserIds(kioskList);
  Long sourceDomainId = kioskList.get(0).getDomainId();
  if (StringUtils.isNotEmpty(sDid)) {
    sourceDomainId = Long.parseLong(sDid);
  }
  String relatedObjectsStr = ConfigUtil.get(MOVE_ENTITY_PROP);
  Map<String, String[]> relatedClassesMap = PropertyUtil.parseProperty(relatedObjectsStr);
  for (String relatedClassName : relatedClassesMap.keySet()) {
    String[] fieldName = relatedClassesMap.get(relatedClassName);
    try {
      List ids;
      if (relatedClassName.endsWith("UserAccount")) {
        ids = new ArrayList<String>(users);
      } else {
        ids = kiosks;
      }
      xLogger
          .info("Scheduling task for moving Object: {0}[{1}] from domainID {2} to domainId {3}",
              relatedClassName, ids, sourceDomainId, destDomainId);
      execute(relatedClassName, fieldName, ids, sourceDomainId, destDomainId);
      xLogger.info("AUDITLOG\tENTITY\t " +
          "MOVE\t{0}\tfrom domainId:{1}\tto domainId:{2}", ids, sourceDomainId, destDomainId);
    } catch (Exception e) {
      xLogger.severe(
          "{0} when scheduling task for moving Object: {1} from domainID {2} to domainId {3}: {4}",
          e.getClass().getName(), relatedClassName, sourceDomainId, destDomainId, e.getMessage(),
          e);
    }
  }
}
 
Example 59
Project: lams   File: ScratchieServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
   public List<ReflectDTO> getReflectionList(Long contentId) {
ArrayList<ReflectDTO> reflections = new ArrayList<>();

// get all available leaders associated with this content as only leaders have reflections
List<ScratchieSession> sessionList = scratchieSessionDao.getByContentId(contentId);
for (ScratchieSession session : sessionList) {

    ScratchieUser leader = session.getGroupLeader();
    if (leader != null) {
	NotebookEntry notebookEntry = getEntry(session.getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL,
		ScratchieConstants.TOOL_SIGNATURE, leader.getUserId().intValue());
	if ((notebookEntry != null) && StringUtils.isNotBlank(notebookEntry.getEntry())) {
	    User user = new User();
	    user.setLastName(leader.getLastName());
	    user.setFirstName(leader.getFirstName());
	    ReflectDTO reflectDTO = new ReflectDTO(user);
	    reflectDTO.setGroupName(session.getSessionName());
	    String reflection = notebookEntry.getEntry();
	    reflection = StringEscapeUtils.escapeJavaScript(reflection);
	    reflectDTO.setReflection(reflection);
	    reflectDTO.setIsGroupLeader(session.isUserGroupLeader(leader.getUid()));

	    reflections.add(reflectDTO);
	}
    }
}

return reflections;
   }
 
Example 60
Project: gitlab-branch-source-plugin   File: GitLabSCMPublishAction.java   Source Code and License 5 votes vote down vote up
public void updateBuildDescription(Run<?, ?> build, String description, TaskListener listener) {
    if (updateBuildDescription && !StringUtils.isBlank(description)) {
        try {
            build.setDescription(description);
        } catch (IOException e) {
            listener.getLogger().println("Failed to set build description");
        }
    }
}