org.apache.commons.lang.Validate Java Examples

The following examples show how to use org.apache.commons.lang.Validate. 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: CraftIpBanList.java    From Thermos with GNU General Public License v3.0 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 #2
Source File: EmbeddedDataSourceFactory.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
public static JdbcDataSource getJdbcDataSource(String initScriptLocation) {
    Validate.notEmpty(initScriptLocation, "initScriptLocation is empty");

    String mavenRelativePath = "src/main/resources/" + initScriptLocation;
    String mavenRootRelativePath = "camel-cookbook-transactions/" + mavenRelativePath;

    // check that we can load the init script
    FileLocator locator = new FileLocator().with(initScriptLocation).with(mavenRelativePath).with(mavenRootRelativePath);
    File file = locator.find();
    Validate.notNull(file, locator.getErrorMessage());
    FileSystemResource script = new FileSystemResource(file);

    JdbcDataSource dataSource = new JdbcDataSource();
    dataSource.setURL("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
    dataSource.setUser("sa");
    dataSource.setPassword("");

    DataSourceInitializer.initializeDataSource(dataSource, script);

    return dataSource;
}
 
Example #3
Source File: ProxyExecution.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
public void attachProxy(Proxy proxy) {
	Validate.isTrue(!isProxyAttached(proxy), "Proxy already attached");
	Class<? extends Proxy> clazz = proxy.getClass();
	
	Priority priority = Priority.NORMAL;
	if (clazz.isAnnotationPresent(ProxyPriority.class)) {
		ProxyPriority priorityAnnotation = clazz.getAnnotation(ProxyPriority.class);
		priority = priorityAnnotation.value();
	}
	
	String[] filter = null;
	if (clazz.isAnnotationPresent(Filter.class)) {
		Filter filterAnnotation = clazz.getAnnotation(Filter.class);
		filter = filterAnnotation.value();
	}
	
	ProxyHolder holder = new ProxyHolder();
	holder.proxy = proxy;
	holder.priority = priority;
	holder.filter = filter;
	
	proxies.add(holder);
	//Finally sort the list to get an appropriate order
	Collections.sort(proxies);
}
 
Example #4
Source File: GetFilePercentTransferredCliAction.java    From oodt with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ActionMessagePrinter printer)
      throws CmdLineActionException {
   try (FileManagerClient client = getClient()) {
      Validate.notNull(origRef, "Must specify origRef");

      Reference ref = new Reference();
      ref.setOrigReference(getUri(origRef).toString());

      printer.println("Reference: [origRef=" + origRef + ",transferPct=" + client.getRefPctTransferred(ref) + "]");
   } catch (Exception e) {
      throw new CmdLineActionException(
            "Failed to get percent transfered for" + " file '" + origRef
                  + "' : " + e.getMessage(), e);
   }
}
 
Example #5
Source File: LocationFlag.java    From HeavySpleef with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void marshal(Element element) {
	Element worldElement = element.addElement("world");
	Element xElement = element.addElement("x");
	Element yElement = element.addElement("y");
	Element zElement = element.addElement("z");
	
	Location value = getValue();
	Validate.notNull(value, "getValue() cannot be null when marshalling flag value");
	
	worldElement.addText(value.getWorld().getName());
	xElement.addText(String.valueOf(value.getX()));
	yElement.addText(String.valueOf(value.getY()));
	zElement.addText(String.valueOf(value.getZ()));
	
	if (value.getYaw() != 0f) {
		element.addElement("yaw").addText(String.valueOf(value.getYaw()));
	}
	if (value.getPitch() != 0f) {
		element.addElement("pitch").addText(String.valueOf(value.getPitch()));
	}
}
 
Example #6
Source File: 1_FastDateFormat.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public final void appendTo(StringBuffer buffer, int value) {
    if (value < 100) {
        for (int i = mSize; --i >= 2; ) {
            buffer.append('0');
        }
        buffer.append((char)(value / 10 + '0'));
        buffer.append((char)(value % 10 + '0'));
    } else {
        int digits;
        if (value < 1000) {
            digits = 3;
        } else {
            Validate.isTrue(value > -1, "Negative values should not be possible", value);
            digits = Integer.toString(value).length();
        }
        for (int i = mSize; --i >= digits; ) {
            buffer.append('0');
        }
        buffer.append(Integer.toString(value));
    }
}
 
Example #7
Source File: AccessChecker.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks the availability and the demanded value of the right for the context user. The right will be checked itself on required
 * constraints, e. g. if assigned groups required.
 * @param user Check the access for the given user instead of the logged-in user.
 * @param rightId
 * @param values At least one of the values should match.
 * @param throwException
 * @return
 */
public boolean hasRight(final PFUserDO user, final UserRightId rightId, final boolean throwException, final UserRightValue... values)
{
  Validate.notNull(user);
  Validate.notNull(values);
  final UserRightDO rightDO = user.getRight(rightId);
  final UserRight right = userRights.getRight(rightId);
  for (final UserRightValue value : values) {
    if ((rightDO == null || rightDO.getValue() == null) && right.matches(userGroupCache, user, value) == true) {
      return true;
    }
    if (rightDO != null && rightDO.getValue() == value) {
      if (right != null && right.isAvailable(userGroupCache, user, value) == true) {
        return true;
      }
    }
  }
  if (throwException == true) {
    throw new AccessException("access.exception.userHasNotRight", rightId, StringHelper.listToString(", ", (Object[]) values));
  }
  return false;
}
 
Example #8
Source File: MySqlChunkedQueryManager.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static String generateChunkedQuery(String nestedQuery, List<String> keys, long chunkSize, int partitionCount,
    List<Integer> partitions, boolean isFirstRun) {
  Validate.isTrue(!keys.isEmpty(), "Need keys to generate chunked query. No keys supplied");

  String hashPredicate = generateFullPartitionHashPredicate(generatePerPartitionHashPredicate(keys, partitionCount), partitions);

  StringBuilder query = new StringBuilder();
  query.append(SELECT_FROM);
  query.append(nestedQuery);
  // 'nestedTab' alias needed as mysql requires every derived table to have its own alias
  query.append(" ) nestedTab1 ");
  query.append(hashPredicate);
  if (!isFirstRun) {
    query.append(" AND ( " + generateKeyChunkingPredicate(keys)).append(" )");
  }

  query.append(" ORDER BY ").append(keys.get(0));
  for (int i = 1; i < keys.size(); i++) {
    query.append(" , ").append(keys.get(i));
  }

  query.insert(0, SELECT_FROM).append(" ) as nestedTab2 LIMIT " + chunkSize);
  return query.toString();
}
 
Example #9
Source File: TileEntityCommand.java    From Thermos with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args)
{
    Validate.notNull(sender, "Sender cannot be null");
    Validate.notNull(args, "Arguments cannot be null");
    Validate.notNull(alias, "Alias cannot be null");

    if (args.length == 1)
    {
        return StringUtil.copyPartialMatches(args[0], COMMANDS, new ArrayList<String>(COMMANDS.size()));
    }
    if (((args.length == 2) && "get".equalsIgnoreCase(args[0])) || "set".equalsIgnoreCase(args[0]))
    {
        return StringUtil.copyPartialMatches(args[1], MinecraftServer.getServer().tileEntityConfig.getSettings().keySet(), new ArrayList<String>(MinecraftServer.getServer().tileEntityConfig.getSettings().size()));
    }

    return ImmutableList.of();
}
 
Example #10
Source File: DynWorkflowCliAction.java    From oodt with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ActionMessagePrinter printer)
        throws CmdLineActionException {
    Validate.notNull(taskIds, "Must specify taskIds");

    try (WorkflowManagerClient client = getClient()) {
        LOGGER.fine(String.format("Starting workflow %d tasks", taskIds.size()));
        String instId = client.executeDynamicWorkflow(taskIds, metadata);
        LOGGER.fine(String.format("Started workflow with instanceId: %s", instId));
        printer.println("Started dynamic workflow with id '" + instId + "'");
    } catch (Exception e) {
        throw new CmdLineActionException(
                "Failed to submit dynamic workflow for taskIds " + taskIds
                        + " with metadata " + metadata.getMap() + " : "
                        + e.getMessage(), e);
    }
}
 
Example #11
Source File: VaultManager.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public static void addMoney(final Player player, final double amount){
	Validate.notNull(player);

	if(!GameManager.getGameManager().getConfiguration().getVaultLoaded()){
		return;
	}

	if(economy == null){
		Bukkit.getLogger().warning("[UhcCore] Vault is not loaded! Couldn't pay "+amount+" to "+player.getName()+"!");
		return;
	}

	final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(player.getUniqueId());

	Bukkit.getScheduler().runTaskAsynchronously(UhcCore.getPlugin(), () -> economy.depositPlayer(offlinePlayer, amount));
}
 
Example #12
Source File: SecureString.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void append(char[] chars) throws GeneralSecurityException {
   Validate.notNull(chars);
   if (chars.length != 0) {
      char[] value = this.getValue();
      char[] result = new char[value.length + chars.length];

      int i;
      for(i = 0; i < value.length; ++i) {
         result[i] = value[i];
         value[i] = 0;
      }

      for(i = 0; i < chars.length; ++i) {
         result[value.length + i] = chars[i];
      }

      this.encrypt(charToByte(result));

      for(i = 0; i < result.length; ++i) {
         result[i] = 0;
      }

   }
}
 
Example #13
Source File: SingleSignOnServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signinWithSAML2Artifact(String targetLocation) throws TechnicalConnectorException {
   try {
      String template = ConnectorIOUtils.getResourceAsString("/sso/SSORequestSTSSAML2Artifact.xml");
      template = StringUtils.replaceEach(template, new String[]{"${reqId}", "${endpoint.idp.saml2.artifact}"}, new String[]{this.idGenerator.generateId(), this.getSAML2Artifact()});
      NodeList references = this.invokeSecureTokenService(ConnectorXmlUtils.flatten(template)).getElementsByTagNameNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Reference");
      Validate.notNull(references);
      Validate.isTrue(references.getLength() == 1);
      Element reference = (Element)references.item(0);
      String uri = reference.getAttribute("URI");
      if (StringUtils.isNotBlank(targetLocation)) {
         uri = uri + "&RelayState=" + targetLocation;
      }

      LOG.debug("Launching browser with url [" + uri + "]");
      this.launchBrowser(new URI(uri));
   } catch (IOException var6) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.CORE_TECHNICAL, var6, new Object[]{var6.getMessage()});
   } catch (URISyntaxException var7) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.CORE_TECHNICAL, var7, new Object[]{var7.getMessage()});
   }
}
 
Example #14
Source File: SkillTree.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param node
 * @return true, if the given skill has the same id as the Skill tree's root node, otherwise false;
 */
public boolean isRootNode(final SkillDO skill)
{
  Validate.notNull(skill);
  checkRefresh();
  if (root == null && skill.getParentId() == null) {
    // First skill, so it should be the root node.
    return true;
  }
  if (skill.getId() == null) {
    // Node has no id, so it can't be the root node.
    return false;
  }
  return root.getId().equals(skill.getId());
}
 
Example #15
Source File: GameManager.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
public void setGameState(GameState gameState){
    Validate.notNull(gameState);

    if (this.gameState == gameState){
        return; // Don't change the game state when the same.
    }

    GameState oldGameState = this.gameState;
    this.gameState = gameState;

    // Call UhcGameStateChangedEvent
    Bukkit.getPluginManager().callEvent(new UhcGameStateChangedEvent(oldGameState, gameState));

    // Update MOTD
    switch(gameState){
        case ENDED:
            setMotd(Lang.DISPLAY_MOTD_ENDED);
            break;
        case LOADING:
            setMotd(Lang.DISPLAY_MOTD_LOADING);
            break;
        case DEATHMATCH:
            setMotd(Lang.DISPLAY_MOTD_PLAYING);
            break;
        case PLAYING:
            setMotd(Lang.DISPLAY_MOTD_PLAYING);
            break;
        case STARTING:
            setMotd(Lang.DISPLAY_MOTD_STARTING);
            break;
        case WAITING:
            setMotd(Lang.DISPLAY_MOTD_WAITING);
            break;
        default:
            setMotd(Lang.DISPLAY_MOTD_ENDED);
            break;
    }
}
 
Example #16
Source File: MailboxLocations.java    From NyaaUtils with MIT License 5 votes vote down vote up
public void updateLocationMapping(UUID uuid, Location location) {
    Validate.notNull(uuid);
    if (location == null) { // unset
        if (locationMap.containsKey(uuid)) {
            locationMap.remove(uuid);
            save();
        }
    } else {
        if (!location.equals(locationMap.get(uuid))) {
            locationMap.put(uuid, location);
            save();
        }
    }
}
 
Example #17
Source File: CraftTeam.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public void setSuffix(String suffix) throws IllegalStateException, IllegalArgumentException {
    Validate.notNull(suffix, "Suffix cannot be null");
    Validate.isTrue(suffix.length() <= 32, "Suffix '" + suffix + "' is longer than the limit of 32 characters");
    CraftScoreboard scoreboard = checkState();

    team.setNameSuffix(suffix);
}
 
Example #18
Source File: JsonUtils.java    From brooklin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Deserialize a JSON string into an object based on a type reference.
 * This method allows the caller to specify precisely the desired output
 * type for the target object.
 * @param json JSON string
 * @param typeRef type reference of the target object
 * @param <T> type of the target object
 * @return deserialized Java object
 */
public static <T> T fromJson(String json, TypeReference<T> typeRef) {
  Validate.notNull(json, "null JSON string");
  Validate.notNull(typeRef, "null type reference");
  T object = null;
  try {
    object = MAPPER.readValue(json, typeRef);
  } catch (IOException e) {
    String errorMessage = "Failed to parse json: " + json;
    ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
  }
  return object;
}
 
Example #19
Source File: SchemaValidatorHandler.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public SchemaValidatorHandler(int verifyType, String... schemaFile) {
   validVerifyType(verifyType);
   Validate.notEmpty(schemaFile);
   Validate.noNullElements(schemaFile);
   this.verify = verifyType;
   this.schemaFiles = schemaFile;
}
 
Example #20
Source File: Organization.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public Organization(String id, IdentifierType type, String name) {
   Validate.notEmpty(id);
   Validate.notNull(type);
   Validate.notEmpty(name);
   this.id = id;
   this.name = name;
   this.type = type;
}
 
Example #21
Source File: CraftPlayer.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public void setScoreboard(Scoreboard scoreboard) {
    Validate.notNull(scoreboard, "Scoreboard cannot be null");
    net.minecraft.network.NetHandlerPlayServer playerConnection = getHandle().playerNetServerHandler;
    if (playerConnection == null) {
        throw new IllegalStateException("Cannot set scoreboard yet");
    }
    if (playerConnection.isDisconnected()) {
        // throw new IllegalStateException("Cannot set scoreboard for invalid CraftPlayer"); // Spigot - remove this as Mojang's semi asynchronous Netty implementation can lead to races
    }

    this.server.getScoreboardManager().setPlayerBoard(this, scoreboard);
}
 
Example #22
Source File: RyaDirectExample.java    From rya with Apache License 2.0 5 votes vote down vote up
private static void testDeleteTemporalData(
		final SailRepositoryConnection conn) throws Exception {
	// Delete all stored dates
	final String sparqlDelete = "PREFIX time: <http://www.w3.org/2006/time#>\n"
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "DELETE {\n" //
			+ "  ?event time:inXSDDateTime ?time . \n"
			+ "}\n"
			+ "WHERE { \n" + "  ?event time:inXSDDateTime ?time . \n"//
			+ "}";//

	final Update deleteUpdate = conn.prepareUpdate(QueryLanguage.SPARQL,
			sparqlDelete);
	deleteUpdate.execute();

	// Find all stored dates.
	final String queryString = "PREFIX time: <http://www.w3.org/2006/time#> \n"//
			+ "PREFIX tempo: <tag:rya-rdf.org,2015:temporal#> \n"//
			+ "SELECT ?event ?time \n" //
			+ "WHERE { \n"
			+ "  ?event time:inXSDDateTime ?time . \n"//
			+ "  FILTER(tempo:after(?time, '2001-01-01T01:01:03-08:00') ) \n"// after
																				// 3
																				// seconds
			+ "}";//

	final CountingResultHandler tupleHandler = new CountingResultHandler();
	final TupleQuery tupleQuery = conn.prepareTupleQuery(
			QueryLanguage.SPARQL, queryString);
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 0);
}
 
Example #23
Source File: NumberedSplit.java    From reef with Apache License 2.0 5 votes vote down vote up
public NumberedSplit(final E entry, final int index, final DistributedDataSetPartition partition) {
  Validate.notNull(entry, "Entry cannot be null");
  Validate.notNull(partition, "Partition cannot be null");
  this.entry = entry;
  this.index = index;
  this.partition = partition;
}
 
Example #24
Source File: ClassExistsCmdLineOptionValidator.java    From oodt with Apache License 2.0 5 votes vote down vote up
@Override
public Result validate(CmdLineOptionInstance optionInst) {
   Validate.notNull(optionInst);

   for (String value : optionInst.getValues()) {
      try {
         Class.forName(value);
      } catch (Exception e) {
         return new Result(Grade.FAIL, "Value '" + value
               + "' for option " + optionInst.getOption().getLongOption()
               + " is not a valid class");
      }
   }
   return new Result(Grade.PASS, "Success");
}
 
Example #25
Source File: ContactData.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void isValidEmail(String emailAddress) {
   if (emailAddress != null) {
      if (emailAddress.length() > 320) {
         throw new IllegalArgumentException("emailAddress [" + emailAddress + "] to long.");
      } else {
         Validate.isTrue(EMAIL_PATTERN.matcher(emailAddress).matches());
      }
   }
}
 
Example #26
Source File: TemplateEntry.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public TemplateCalendarProperties addNewCalendarProperties(final TeamCalCalendarFilter filter, final Integer calId)
{
  Validate.notNull(calId);
  final TemplateCalendarProperties props = new TemplateCalendarProperties();
  props.setCalId(calId);
  props.setColorCode(filter.getUsedColor(calId));
  this.calendarProperties.add(props);
  this.visibleCalendarIds = null;
  return props;
}
 
Example #27
Source File: BaseDao.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param obj
 * @throws AccessException
 * @return true, if modifications were done, false if no modification detected.
 * @see #internalUpdate(ExtendedBaseDO, boolean)
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public ModificationStatus update(final O obj) throws AccessException
{
  Validate.notNull(obj);
  if (obj.getId() == null) {
    final String msg = "Could not update object unless id is not given:" + obj.toString();
    log.error(msg);
    throw new RuntimeException(msg);
  }
  return internalUpdate(obj, true);
}
 
Example #28
Source File: SkullUtils.java    From XSeries with MIT License 5 votes vote down vote up
/**
 * https://api.mojang.com/users/profiles/minecraft/Username gives the ID
 * https://api.mojang.com/user/profiles/ID without dashes/names gives the names used for the unique ID.
 * https://sessionserver.mojang.com/session/minecraft/profile/ID example data:
 * <p>
 * <pre>
 * {
 *      "id": "Without dashes -",
 *      "name": "",
 *      "properties": [
 *      {
 *          "name": "textures",
 *          "value": ""
 *      }
 *      ]
 * }
 * </pre>
 */
@Nonnull
public static String getSkinValue(@Nonnull String name, boolean isId) {
    Validate.notEmpty(name, "Player name/UUID cannot be null or empty");

    try {
        String uuid;
        JsonParser parser = new JsonParser();

        if (!isId) {
            URL convertName = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
            InputStreamReader readId = new InputStreamReader(convertName.openStream());
            JsonObject jObject = parser.parse(readId).getAsJsonObject();
            if (mojangError(jObject)) return null;
            uuid = jObject.get("id").getAsString();
        } else uuid = StringUtils.remove(name, '-');

        URL properties = new URL(session + uuid); // + "?unsigned=false"
        InputStreamReader readProperties = new InputStreamReader(properties.openStream());
        JsonObject jObjectP = parser.parse(readProperties).getAsJsonObject();

        if (mojangError(jObjectP)) return null;
        JsonObject textureProperty = jObjectP.get("properties").getAsJsonArray().get(0).getAsJsonObject();
        //String signature = textureProperty.get("signature").getAsString();
        return textureProperty.get("value").getAsString();
    } catch (IOException | IllegalStateException e) {
        System.err.println("Could not get skin data from session servers! " + e.getMessage());
        e.printStackTrace();
        return null;
    }
}
 
Example #29
Source File: UserDao.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Ohne Zugangsbegrenzung. Wird bei Anmeldung benötigt.
 * @param username
 * @param encryptedPassword
 * @return
 */
@SuppressWarnings("unchecked")
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public PFUserDO authenticateUser(final String username, final String password)
{
  Validate.notNull(username);
  Validate.notNull(password);

  PFUserDO user = getUser(username, password, true);
  if (user != null) {
    final int loginFailures = user.getLoginFailures();
    final Timestamp lastLogin = user.getLastLogin();
    user.setLastLogin(new Timestamp(new Date().getTime()));
    user.setLoginFailures(0);
    user.setMinorChange(true); // Avoid re-indexing of all dependent objects.
    internalUpdate(user, false);
    if (user.hasSystemAccess() == false) {
      log.warn("Deleted/deactivated user tried to login: " + user);
      return null;
    }
    final PFUserDO contextUser = new PFUserDO();
    contextUser.copyValuesFrom(user);
    contextUser.setLoginFailures(loginFailures); // Restore loginFailures for current user session.
    contextUser.setLastLogin(lastLogin); // Restore lastLogin for current user session.
    contextUser.setPassword(null);
    return contextUser;
  }
  final List<PFUserDO> list = getHibernateTemplate().find("from PFUserDO u where u.username = ?", username);
  if (list != null && list.isEmpty() == false && list.get(0) != null) {
    user = list.get(0);
    user.setLoginFailures(user.getLoginFailures() + 1);
    internalUpdate(user);
  }
  return null;
}
 
Example #30
Source File: RyaGeoDirectExample.java    From rya with Apache License 2.0 5 votes vote down vote up
private static void testGeoFreetextWithPCJSearch(
		final SailRepositoryConnection conn)
		throws MalformedQueryException, RepositoryException,
		TupleQueryResultHandlerException, QueryEvaluationException {
	// ring outside point
	final String queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#>  "//
			+ "PREFIX fts: <http://rdf.useekm.com/fts#>  "//
			+ "PREFIX geof: <http://www.opengis.net/def/function/geosparql/>  "//
			+ "SELECT ?feature ?point ?wkt ?e ?c ?l ?o ?person ?match " //
			+ "{" //
			+ "  ?person a <http://example.org/ontology/Person> . "//
			+ "  ?person <http://www.w3.org/2000/01/rdf-schema#label> ?match . "//
			+ "  FILTER(fts:text(?match, \"!alice & hose\")) " //
			+ "  ?e a ?c . "//
			+ "  ?e <http://www.w3.org/2000/01/rdf-schema#label> ?l . "//
			+ "  ?e <uri:talksTo> ?o . "//
			+ "  ?feature a geo:Feature . "//
			+ "  ?feature geo:hasGeometry ?point . "//
			+ "  ?point a geo:Point . "//
			+ "  ?point geo:asWKT ?wkt . "//
			+ "  FILTER(geof:sfWithin(?wkt, \"POLYGON((-78 39, -77 39, -77 38, -78 38, -78 39))\"^^geo:wktLiteral)) " //
			+ "}";//
	final TupleQuery tupleQuery = conn.prepareTupleQuery(
			QueryLanguage.SPARQL, queryString);
	final CountingResultHandler tupleHandler = new CountingResultHandler();
	tupleQuery.evaluate(tupleHandler);
	log.info("Result count : " + tupleHandler.getCount());
	Validate.isTrue(tupleHandler.getCount() == 0);// TODO ==1  some data is missing for this query!
}