Java Code Examples for org.apache.wicket.util.string.Strings

The following examples show how to use org.apache.wicket.util.string.Strings. These examples are extracted from open source projects. 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 Project: openmeetings   Source File: RedirectMessageDialog.java    License: Apache License 2.0 6 votes vote down vote up
private void startTimer(IPartialPageRequestHandler handler) {
	getLabel().add(new OmTimerBehavior(DELAY, labelId) {
		private static final long serialVersionUID = 1L;

		@Override
		protected void onFinish(AjaxRequestTarget target) {
			if (Strings.isEmpty(url)) {
				throw new RestartResponseException(Application.get().getHomePage());
			} else {
				throw new RedirectToUrlException(url);
			}
		}
	}).setOutputMarkupId(true);
	if (handler != null) {
		handler.add(getLabel());
	}
}
 
Example 2
Source Project: onedev   Source File: FormComponent.java    License: MIT License 6 votes vote down vote up
/**
 * Gets current value for a form component, which can be either input data entered by the user,
 * or the component's model object if no input was provided.
 * 
 * @return The value
 */
public final String getValue()
{
	if (NO_RAW_INPUT.equals(rawInput))
	{
		return getModelValue();
	}
	else
	{
		if (getEscapeModelStrings() && rawInput != null)
		{
			return Strings.escapeMarkup(rawInput).toString();
		}
		return rawInput;
	}
}
 
Example 3
Source Project: Orienteer   Source File: OClassIntrospector.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OQueryDataProvider<ODocument> getDataProviderForGenericSearch(OClass oClass, IModel<String> queryModel) {
	String searchSql = CustomAttribute.SEARCH_QUERY.getValue(oClass);
	String sql=null;
	if(!Strings.isEmpty(searchSql)) {
		String upper = searchSql.toUpperCase().trim();
		if(upper.startsWith("SELECT")) sql = searchSql;
		else if(upper.startsWith("WHERE")) sql = "select from "+oClass.getName()+" "+searchSql;
		else {
			LOG.error("Unrecognized search sql: "+searchSql);
		}
	}

	if(sql==null) sql = "select from "+oClass.getName()+" where any() containstext :query";

	return new OQueryDataProvider<ODocument>(sql).setParameter("query", queryModel);
}
 
Example 4
Source Project: Orienteer   Source File: JobEntityHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Statement
public List<JobEntity> selectJobsByConfiguration(OPersistenceSession session, ListQueryParameterObject query) {
	Map<String, Object> params = (Map<String, Object>) query.getParameter(); 
    String config = (String) params.get("handlerConfiguration");
    String followUpConfig = (String) params.get("handlerConfigurationWithFollowUpJobCreatedProperty");
    String type = (String) params.get("handlerType");
    List<String> args = new ArrayList<>();
    Query q = new Query().from(getSchemaClass());
    q.where(Clause.clause("jobHandlerType", Operator.EQ, Parameter.PARAMETER));
    args.add(type);
    Clause eqConfig = Clause.clause("JobHandlerConfigurationRaw", Operator.EQ, Parameter.PARAMETER);
    if(Strings.isEmpty(followUpConfig)) {
    	q.where(eqConfig);
    	args.add(config);
    } else {
    	q.where(Clause.or(eqConfig, eqConfig));
    	args.add(config); 
    	args.add(followUpConfig);
    }
    return queryList(session, q.toString(), args.toArray());
}
 
Example 5
Source Project: openmeetings   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
private JSONObject addUserJson(JSONObject o) {
	JSONObject u = new JSONObject();
	if (user != null) {
		JSONObject a = new JSONObject();
		u.put("id", user.getId())
			.put("firstName", user.getFirstname())
			.put("lastName", user.getLastname())
			.put("displayName", user.getDisplayName())
			.put("address", a)
			.put("pictureUri", pictureUri);
		if (user.getAddress() != null) {
			if (Strings.isEmpty(user.getFirstname()) && Strings.isEmpty(user.getLastname())) {
				a.put("email", user.getAddress().getEmail());
			}
			a.put("country", user.getAddress().getCountry());
		}
	}
	return o.put("user", u)
			.put("level", hasRight(Right.MODERATOR) ? 5 : (hasRight(Right.WHITEBOARD) ? 3 : 1));
}
 
Example 6
Source Project: openmeetings   Source File: UserDTO.java    License: Apache License 2.0 6 votes vote down vote up
public User get(UserDao userDao, GroupDao groupDao) {
	User u = id == null ? new User() : userDao.get(id);
	u.setLogin(login);
	u.setFirstname(firstname);
	u.setLastname(lastname);
	u.setRights(rights);
	u.setLanguageId(languageId);
	u.setAddress(address);
	u.setTimeZoneId(timeZoneId);
	if (Type.EXTERNAL == type || (!Strings.isEmpty(externalId) && !Strings.isEmpty(externalType))) {
		type = Type.EXTERNAL;
		if (u.getGroupUsers().stream().filter(gu -> gu.getGroup().isExternal() && gu.getGroup().getName().equals(externalType)).count() == 0) {
			u.addGroup(groupDao.getExternal(externalType));
		}
		u.setExternalId(externalId);
	}
	u.setType(type);
	u.setPictureUri(pictureUri);
	return u;
}
 
Example 7
Source Project: Orienteer   Source File: AddTabCommand.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void initializeContent(final ModalWindow modal) {
	modal.setTitle(new ResourceModel("command.add.tab"));
	modal.setContent(new AddTabDialog<T>(modal.getContentId()) {
		private static final long serialVersionUID = 1L;

		@Override
		protected void onCreateTab(String name, Optional<AjaxRequestTarget> targetOptional) {
			targetOptional.ifPresent(modal::close);
			if(Strings.isEmpty(name)) {
				name = getLocalizer().getString("command.add.tab.modal.defaultname", null);
			}
			
			AbstractWidgetPage<T> page = (AbstractWidgetPage<T>)findPage();
			page.getCurrentDashboard().setModeObject(DisplayMode.VIEW); //Close action on current tab
			page.addTab(name);
			page.selectTab(name, targetOptional);
			send(page, Broadcast.DEPTH, new SwitchDashboardTabEvent(targetOptional));
			page.getCurrentDashboard().setModeObject(DisplayMode.EDIT); //Open action on new tab
			targetOptional.ifPresent(target -> target.add(page.getCurrentDashboardComponent()));
		}
	});
	modal.setAutoSize(true);
	modal.setMinimalWidth(300);
}
 
Example 8
Source Project: openmeetings   Source File: GroupChoiceProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void query(String term, int page, Response<Group> response) {
	if (WebSession.getRights().contains(User.Right.ADMIN)) {
		List<Group> groups = groupDao.get(0, Integer.MAX_VALUE);
		for (Group g : groups) {
			if (Strings.isEmpty(term) || g.getName().toLowerCase(Locale.ROOT).contains(term.toLowerCase(Locale.ROOT))) {
				response.add(g);
			}
		}
	} else {
		User u = userDao.get(getUserId());
		for (GroupUser ou : u.getGroupUsers()) {
			if (Strings.isEmpty(term) || ou.getGroup().getName().toLowerCase(Locale.ROOT).contains(term.toLowerCase(Locale.ROOT))) {
				response.add(ou.getGroup());
			}
		}
	}
}
 
Example 9
Source Project: wicket-orientdb   Source File: AbstractNamingModel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns name
 * @param component component to look associated localization 
 * @return name
 */
public String getObject(Component component) {
	if(objectModel!=null)
	{
		T object = objectModel.getObject();
		if(object==null) return null;
		resourceKey = getResourceKey(object);
	}
	String defaultValue = getDefault();
	if(defaultValue==null) defaultValue = Strings.lastPathComponent(resourceKey, '.');
	if(defaultValue!=null) defaultValue = buitify(defaultValue);
	return Application.get()
			.getResourceSettings()
			.getLocalizer()
			.getString(resourceKey, null, defaultValue);
}
 
Example 10
Source Project: openmeetings   Source File: ChatForm.java    License: Apache License 2.0 6 votes vote down vote up
boolean process(BooleanSupplier processAll, Predicate<Room> processRoom, Predicate<User> processUser) {
	try {
		final String scope = getScope();
		if (Strings.isEmpty(scope) || ID_ALL.equals(scope)) {
			return processAll.getAsBoolean();
		} else if (scope.startsWith(ID_ROOM_PREFIX)) {
			Room r = roomDao.get(Long.parseLong(scope.substring(ID_ROOM_PREFIX.length())));
			if (r != null) {
				return processRoom.test(r);
			}
		} else if (scope.startsWith(ID_USER_PREFIX)) {
			User u = userDao.get(Long.parseLong(scope.substring(ID_USER_PREFIX.length())));
			if (u != null) {
				return processUser.test(u);
			}
		}
	} catch (Exception e) {
		//no-op
	}
	return false;
}
 
Example 11
Source Project: webanno   Source File: UrlImporter.java    License: Apache License 2.0 6 votes vote down vote up
private Optional<Import> resolvePackageDependency(String url)
{
    if (Strings.isEmpty(scopeClass)) {
        throw new IllegalStateException(
                "Cannot resolve dependency '" + url + "' without a scope class!");
    }

    LOG.debug("Going to resolve an import from the package: {}", url);
    String resourceName = url.startsWith(PACKAGE_SCHEME)
            ? url.substring(PACKAGE_SCHEME.length())
            : url;
    if (resourceName.indexOf(0) == '/') {
        resourceName = resourceName.substring(1);
    }

    Class<?> scope = WicketObjects.resolveClass(scopeClass);
    URL importUrl = scope.getResource(resourceName);

    return Optional.ofNullable(importUrl).map(this::buildImport);

}
 
Example 12
Source Project: Orienteer   Source File: BasePage.java    License: Apache License 2.0 6 votes vote down vote up
public BasePage(PageParameters parameters)
{
	super(parameters);
	if(parameters!=null && !parameters.isEmpty())
	{
		IModel<T> model = resolveByPageParameters(parameters);
		if(model!=null) setModel(model);
		String perspective = parameters.get("_perspective").toOptionalString();
		if(!Strings.isEmpty(perspective))
		{
			perspectivesModule.getPerspectiveByAliasAsDocument(getDatabase(), perspective)
					.ifPresent(perspectiveDoc -> OrienteerWebSession.get().setPerspecive(perspectiveDoc));
		}
	}
	initialize();
}
 
Example 13
Source Project: openmeetings   Source File: ThreadHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static void startRunnable(Runnable r, String name) {
	final Application app = Application.get();
	final WebSession session = WebSession.get();
	final RequestCycle rc = RequestCycle.get();
	Thread t = new Thread(() -> {
		ThreadContext.setApplication(app);
		ThreadContext.setSession(session);
		ThreadContext.setRequestCycle(rc);
		r.run();
		ThreadContext.detach();
	});
	if (!Strings.isEmpty(name)) {
		t.setName(name);
	}
	t.start();
}
 
Example 14
Source Project: Orienteer   Source File: OrienteerLocalizationModule.java    License: Apache License 2.0 6 votes vote down vote up
public String loadStringResource(final String key, Locale locale, final String style, final String variation)
{
	if(Strings.isEmpty(key)) {
		System.out.println("Empty!");
	}

	final String language = locale!=null?locale.getLanguage():null;
	return new DBClosure<String>() {

		@Override
		protected String execute(ODatabaseDocument db) {
			String ret = sudoLoadStringResource(db, true, key, language, style, variation);
			return ret!=null || DEFAULT_LANGUAGE.equals(language) ? ret : sudoLoadStringResource(db, false, key, DEFAULT_LANGUAGE, style, variation);
		}
	}.execute();
}
 
Example 15
Source Project: openmeetings   Source File: ReminderJob.java    License: Apache License 2.0 6 votes vote down vote up
public void loadRss() {
	log.trace("ReminderJob.loadRss");
	if (!isInitComplete()) {
		return;
	}
	if (!cfgDao.getBool(CONFIG_DASHBOARD_SHOW_RSS, false)) {
		log.debug("Rss disabled by Admin");
		return;
	}
	JSONArray feed = new JSONArray();
	for (String url : new String[] {cfgDao.getString(CONFIG_DASHBOARD_RSS_FEED1, ""), cfgDao.getString(CONFIG_DASHBOARD_RSS_FEED2, "")}) {
		if (!Strings.isEmpty(url)) {
			AtomReader.load(url, feed);
		}
	}
	if (feed.length() > 0) {
		setRss(feed);
	}
}
 
Example 16
public static String getClientIp(final ServletRequest request)
{
  String remoteAddr = null;
  if (request instanceof HttpServletRequest) {
    remoteAddr = ((HttpServletRequest) request).getHeader("X-Forwarded-For");
  }
  if (remoteAddr != null) {
    if (remoteAddr.contains(",")) {
      // sometimes the header is of form client ip,proxy 1 ip,proxy 2 ip,...,proxy n ip,
      // we just want the client
      remoteAddr = Strings.split(remoteAddr, ',')[0].trim();
    }
    try {
      // If ip4/6 address string handed over, simply does pattern validation.
      InetAddress.getByName(remoteAddr);
    } catch (final UnknownHostException e) {
      remoteAddr = request.getRemoteAddr();
    }
  } else {
    remoteAddr = request.getRemoteAddr();
  }
  return remoteAddr;
}
 
Example 17
Source Project: Orienteer   Source File: BinaryViewPanel.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public BinaryViewPanel(String id, final IModel<ODocument> docModel, final IModel<OProperty> propModel, IModel<V> valueModel) {
	super(id, valueModel);
	
	nameModel = new LoadableDetachableModel<String>() {

		@Override
		protected String load() {
			String filename = docModel.getObject().field(propModel.getObject().getName()+BinaryEditPanel.FILENAME_SUFFIX, String.class);
			if(Strings.isEmpty(filename)){
				filename = oClassIntrospector.getDocumentName(docModel.getObject());
				filename += "."+propModel.getObject().getName()+".bin";
			}
			return filename;
		}
		
		@Override
		public void detach() {
			super.detach();
			docModel.detach();
			propModel.detach();
		}
	};
	
	initialize();
}
 
Example 18
Source Project: Orienteer   Source File: OLoggerModule.java    License: Apache License 2.0 6 votes vote down vote up
private void installOLogger(OrienteerWebApplication app, Module module) {
	IOLoggerConfiguration config = new DefaultOLoggerConfiguration();
	config.setApplicationName(app.getResourceSettings().getLocalizer().getString("application.name", null));

	//If collector URL was not overwriten from system properties: lets get it from module
	if (Strings.isEmpty(config.getCollectorUrl())) {
		config.setCollectorUrl(module.getCollectorUrl());
	}

	if (module.getCorrelationIdGenerator() != null) {
		config.setCorrelationIdGenerator(module.getCorrelationIdGenerator().createCorrelationIdGenerator());
	}

	OLoggerBuilder builder = new OLoggerBuilder();
	builder.setLoggerEventDispatcher(module.getLoggerEventDispatcher().createDispatcherClassInstance());
	module.getLoggerEnhancersInstances().forEach(builder::addEnhancer);
	builder.addDefaultEnhancers();

	OLogger.set(builder.create(config));
}
 
Example 19
Source Project: openmeetings   Source File: StrongPasswordValidator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasStopWords(String password) {
	if (checkWord(password, u.getLogin())) {
		return true;
	}
	if (u.getAddress() != null) {
		String email = u.getAddress().getEmail();
		if (!Strings.isEmpty(email)) {
			for (String part : email.split("[[email protected]]")) {
				if (checkWord(password, part)) {
					return true;
				}
			}
		}
	}
	return false;
}
 
Example 20
Source Project: openmeetings   Source File: StrongPasswordValidator.java    License: Apache License 2.0 6 votes vote down vote up
private void error(IValidatable<String> pass, String key, Map<String, Object> params) {
	if (web) {
		ValidationError err = new ValidationError().addKey(key);
		if (params != null) {
			err.setVariables(params);
		}
		pass.error(err);
	} else {
		String msg = LabelDao.getString(key, 1L);
		if (params != null && !params.isEmpty() && !Strings.isEmpty(msg)) {
			for (Map.Entry<String, Object> e : params.entrySet()) {
				msg = msg.replace(String.format("${%s}", e.getKey()), "" + e.getValue());
			}
		}
		log.warn(msg);
		pass.error(new ValidationError(msg));
	}
}
 
Example 21
Source Project: Orienteer   Source File: LookupResourceHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public URL lookup(String identifier) {
	String path = System.getProperty(identifier);
	if(!Strings.isEmpty(path))
	{
		File file = new File(path);
		return convertFileToURL(file);
	}
	else return null;
}
 
Example 22
Source Project: onedev   Source File: FormComponent.java    License: MIT License 5 votes vote down vote up
private String substitute(String string, final Map<String, Object> vars)
	throws IllegalStateException
{
	return new VariableInterpolator(string, Application.get()
		.getResourceSettings()
		.getThrowExceptionOnMissingResource())
	{
		private static final long serialVersionUID = 1L;

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		protected String getValue(String variableName)
		{
			Object value = vars.get(variableName);
			
			if (value == null ||value instanceof String)
			{
				return String.valueOf(value);
			}
			
			IConverter converter = getConverter(value.getClass());
			
			if (converter == null)
			{
				return Strings.toString(value);
			}
			else
			{
				return converter.convertToString(value, getLocale());
			}
		}
	}.toString();
}
 
Example 23
Source Project: onedev   Source File: BasicResourceReferenceMapper.java    License: MIT License 5 votes vote down vote up
/**
 * Checks whether the passed Url can be handled by this mapper
 *
 * @param url
 *      the Url to check
 * @return {@code true} - if the Url can be handled, {@code false} - otherwise
 */
protected boolean canBeHandled(final Url url)
{
	List<String> segments = url.getSegments();
	return (segments.size() >= 4 &&
			urlStartsWith(url, getContext().getNamespace(), getContext().getResourceIdentifier()) &&
			Strings.isEmpty(segments.get(3)) == false
	);

}
 
Example 24
Source Project: Orienteer   Source File: OETLConfig.java    License: Apache License 2.0 5 votes vote down vote up
private void printCause(Throwable e,OETLTaskSession session){
	if (!Strings.isEmpty(e.getMessage())){
		session.appendOut(e.getMessage());
	}
	if (e.getCause()!=null){
		printCause(e.getCause(), session);
	}
}
 
Example 25
@Override
public void onComponentTag(final Component component, final ComponentTag tag)
{
	String className = getCssClass();
	if (!Strings.isEmpty(className))
	{
		tag.append("class", className, " ");
	}
}
 
Example 26
Source Project: openmeetings   Source File: MeetingMemberDTO.java    License: Apache License 2.0 5 votes vote down vote up
public MeetingMember get(UserDao userDao, GroupDao groupDao, User owner) {
	MeetingMember mm = new MeetingMember();
	mm.setId(id);
	if (user.getId() != null) {
		mm.setUser(userDao.get(user.getId()));
	} else {
		User u = null;
		if (User.Type.EXTERNAL == user.getType()) {
			// try to get ext. user
			u = userDao.getExternalUser(user.getExternalId(), user.getExternalType());
		}
		if (u == null && user.getAddress() != null) {
			u = userDao.getContact(user.getAddress().getEmail()
					, user.getFirstname()
					, user.getLastname()
					, user.getLanguageId()
					, user.getTimeZoneId()
					, owner);
		}
		if (u == null) {
			user.setType(User.Type.CONTACT);
			u = user.get(userDao, groupDao);
			u.getRights().clear();
		}
		if (Strings.isEmpty(u.getTimeZoneId())) {
			u.setTimeZoneId(owner.getTimeZoneId());
		}
		mm.setUser(u);
	}
	return mm;
}
 
Example 27
Source Project: Orienteer   Source File: StartupPropertiesLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve startup properties 
 * @return not null {@link Properties}
 */
public static Properties retrieveProperties() {
	Properties loadedProperties = new Properties();
	loadedProperties.putAll(PROPERTIES_DEFAULT);
	String qualifier = System.getProperty(ORIENTEER_PROPERTIES_QUALIFIER_PROPERTY_NAME);
	if(!Strings.isEmpty(qualifier))
	{
		LOG.info("Orienteer startup properties qualifier: "+qualifier);
		Properties qualifierProperties = retrieveProperties(qualifier);
		if(qualifierProperties!=null)
		{
			loadedProperties.putAll(qualifierProperties);
			loadedProperties = retrieveSystemProperties(loadedProperties);
			return loadedProperties;
		}
		else
		{
			LOG.info("Properties for qualifier '"+qualifier+"' was not found.");
		}
	}
	LOG.info("Using default orienteer startup properties qualifier");
	Properties defaultQualifierProperties = retrieveProperties(DEFAULT_ORENTEER_PROPERTIES_QUALIFIER);
	if(defaultQualifierProperties!=null)
	{
		loadedProperties.putAll(defaultQualifierProperties);
		loadedProperties = retrieveSystemProperties(loadedProperties);
		return loadedProperties;
	}
	else
	{
		LOG.info("Properties for qualifier '"+qualifier+"' was not found. Using embedded.");
		loadedProperties = retrieveSystemProperties(loadedProperties);
		return loadedProperties;
	}
	
}
 
Example 28
Source Project: openmeetings   Source File: BackupImport.java    License: Apache License 2.0 5 votes vote down vote up
private void checkHash(BaseFileItem file, BaseFileItemDao dao, BiConsumer<String, String> consumer) {
	String oldHash = file.getHash();
	if (Strings.isEmpty(oldHash) || !UUID_PATTERN.matcher(oldHash).matches() || dao.get(oldHash) != null) {
		file.setHash(randomUUID().toString());
		hashMap.put(oldHash, file.getHash());
		if (consumer != null) {
			consumer.accept(oldHash, file.getHash());
		}
	} else {
		hashMap.put(file.getHash(), file.getHash());
	}
}
 
Example 29
Source Project: Orienteer   Source File: CommonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert content to JavaScript string.
 * Added '"' at start and end of content
 * Replaces all '\n' by '\\n"'
 * @param content {@link CharSequence} content
 * @return {@link CharSequence} JavaScript string or "null" if content is null
 */
public static final CharSequence escapeAndWrapAsJavaScriptString(CharSequence content) {
	if(content==null) return "null";
	else {
		content = JavaScriptUtils.escapeQuotes(content);
		content = "\"" + content + "\""; 
		content = Strings.replaceAll(content, "\r", "");
		content = Strings.replaceAll(content, "\n", "\" + \n\"");
		return content;
	}
}
 
Example 30
Source Project: Orienteer   Source File: AbstractEntityHandler.java    License: Apache License 2.0 5 votes vote down vote up
public AbstractEntityHandler(String schemaClass, String pkField) {
	this.schemaClass = schemaClass;
	this.pkField = pkField;
	for(Method method:getClass().getMethods()) {
		Statement statement = method.getAnnotation(Statement.class);
		if(statement!=null) {
			String st = statement.value();
			if(Strings.isEmpty(st)) st = method.getName();
			statementMethodsMapping.put(st, method);
		}
	}
}