Java Code Examples for org.apache.commons.lang.Validate#isTrue()

The following examples show how to use org.apache.commons.lang.Validate#isTrue() . 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: UserController.java    From spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework with MIT License 6 votes vote down vote up
/**
 * Authenticate a user
 *
 * @param userDTO
 * @return
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER})
public @ResponseBody APIResponse authenticate(@RequestBody UserDTO userDTO,
                                              HttpServletRequest request, HttpServletResponse response) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, AuthenticationFailedException {
    Validate.isTrue(StringUtils.isNotBlank(userDTO.getEmail()), "Email is blank");
    Validate.isTrue(StringUtils.isNotBlank(userDTO.getEncryptedPassword()), "Encrypted password is blank");
    String password = decryptPassword(userDTO);

    LOG.info("Looking for user by email: "+userDTO.getEmail());
    User user = userService.findByEmail(userDTO.getEmail());

    HashMap<String, Object> authResp = new HashMap<>();
    if(userService.isValidPass(user, password)) {
        LOG.info("User authenticated: "+user.getEmail());
        userService.loginUser(user, request);
        createAuthResponse(user, authResp);
    } else {
        throw new AuthenticationFailedException("Invalid username/password combination");
    }

    return APIResponse.toOkResponse(authResp);
}
 
Example 2
Source File: MonetaConfiguration.java    From moneta with Apache License 2.0 6 votes vote down vote up
protected void validateTopic(Topic topic) {
	Validate.notEmpty(topic.getTopicName(), "Null or blank Topics.Topic.name not allowed");
	Validate.notEmpty(topic.getPluralName(), "Null or blank Topics.Topic.pluralName not allowed");
	Validate.notEmpty(topic.getDataSourceName(), "Null or blank Topics.Topic.dataSource not allowed.  topic="+topic.getTopicName());
	Validate.notEmpty(topic.getTableName(), "Null or blank Topics.Topic.table not allowed.  topic="+topic.getTopicName());
	Validate.notNull(topic.getReadOnly(), "Null or blank Topics.Topic.readOnly not allowed.  topic="+topic.getTopicName());
	
	if (StringUtils.isEmpty(topic.getSchemaName())) {
		Validate.isTrue(topic.getCatalogName()==null, "Null or blank Topics.Topic.catalog not allowed when schema is provided.  topic="+topic.getTopicName());
	}
	
	if ( !connectionPoolMap.containsKey(topic.getDataSourceName())) {
		throw new MonetaException("Topic references non-existent data source")
			.addContextValue("topic", topic.getTopicName())
			.addContextValue("dataSource", topic.getDataSourceName());
	}
}
 
Example 3
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 4
Source File: LdapManagerImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private LinkDomainToLdapResponse linkDomainToLdap(Long domainId, String type, String name, short accountType) {
    Validate.notNull(type, "type cannot be null. It should either be GROUP or OU");
    Validate.notNull(domainId, "domainId cannot be null.");
    Validate.notEmpty(name, "GROUP or OU name cannot be empty");
    //Account type should be 0 or 2. check the constants in com.cloud.user.Account
    Validate.isTrue(accountType==0 || accountType==2, "accountype should be either 0(normal user) or 2(domain admin)");
    LinkType linkType = LdapManager.LinkType.valueOf(type.toUpperCase());
    LdapTrustMapVO vo = _ldapTrustMapDao.persist(new LdapTrustMapVO(domainId, linkType, name, accountType, 0));
    DomainVO domain = domainDao.findById(vo.getDomainId());
    String domainUuid = "<unknown>";
    if (domain == null) {
        LOGGER.error("no domain in database for id " + vo.getDomainId());
    } else {
        domainUuid = domain.getUuid();
    }
    LinkDomainToLdapResponse response = new LinkDomainToLdapResponse(domainUuid, vo.getType().toString(), vo.getName(), vo.getAccountType());
    return response;
}
 
Example 5
Source File: EmployeeDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * If more than one employee is found, null will be returned.
 * @param fullname Format: &lt;last name&gt;, &lt;first name&gt;
 */
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public EmployeeDO getByName(final String fullname)
{
  final StringTokenizer tokenizer = new StringTokenizer(fullname, ",");
  if (tokenizer.countTokens() != 2) {
    log.error("EmployeeDao.getByName: Token '" + fullname + "' not supported.");
  }
  Validate.isTrue(tokenizer.countTokens() == 2);
  final String lastname = tokenizer.nextToken().trim();
  final String firstname = tokenizer.nextToken().trim();
  @SuppressWarnings("unchecked")
  final List<EmployeeDO> list = getHibernateTemplate().find("from EmployeeDO e where e.user.lastname = ? and e.user.firstname = ?",
      new Object[] { lastname, firstname});
  // final List<EmployeeDO> list = getHibernateTemplate().find("from EmployeeDO e where e.user.lastname = ?", lastname);
  if (list != null && list.size() == 1) {
    return list.get(0);
  }
  return null;
}
 
Example 6
Source File: PersonalContactDao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param obj
 * @return true, if already existing entry was updated, otherwise false (e. g. if no entry exists for update).
 */
private boolean internalUpdate(final PersonalContactDO obj)
{
  PersonalContactDO dbObj = null;
  if (obj.getId() != null) {
    dbObj = getHibernateTemplate().load(PersonalContactDO.class, obj.getId(), LockMode.PESSIMISTIC_WRITE);
  }
  if (dbObj == null) {
    dbObj = getByContactId(obj.getContactId());
  }
  if (dbObj == null) {
    return false;
  }
  checkAccess(dbObj);
  Validate.isTrue(ObjectUtils.equals(dbObj.getContactId(), obj.getContactId()));
  obj.setId(dbObj.getId());
  // Copy all values of modified user to database object.
  final ModificationStatus modified = dbObj.copyValuesFrom(obj, "owner", "address", "id");
  if (modified == ModificationStatus.MAJOR) {
    dbObj.setLastUpdate();
    log.info("Object updated: " + dbObj.toString());
  }
  return true;
}
 
Example 7
Source File: MonetaConfiguration.java    From moneta with Apache License 2.0 6 votes vote down vote up
protected void initTopics(XMLConfiguration config) {
	int nbrTopics = 0;
	Object temp = config.getList("Topics.Topic[@name]");
	if (temp instanceof Collection) {
		nbrTopics = ((Collection)temp).size();
	}
	
	Topic topic;
	String readOnlyStr;
	for (int i = 0; i < nbrTopics; i++) {
		topic = new Topic();
		gatherTopicAttributes(config, topic, i);
		gatherAliasAttributes(config, topic);
		gatherKeyFields(config, topic);
		
		validateTopic(topic);			
		topicMap.put(topic.getTopicName(), topic);
		pluralNameMap.put(topic.getPluralName(), topic);
	}
	
	Validate.isTrue(topicMap.size() > 0, "No Topics configured.");	
}
 
Example 8
Source File: StdCmdLineConstructor.java    From oodt with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
/* package */static Set<CmdLineOption> verifyGroupHasRequiredSubOptions(
      CmdLineOptionInstance group) {
   Validate.isTrue(group.isGroup());

   Set<CmdLineOption> missingSubOptions = new HashSet<CmdLineOption>();
   TOP: for (GroupSubOption subOption : ((GroupCmdLineOption) group.getOption())
         .getSubOptions()) {
      if (subOption.isRequired()) {
         for (CmdLineOptionInstance specifiedSubOption : group
               .getSubOptions()) {
            if (specifiedSubOption.getOption().equals(subOption.getOption())) {
               continue TOP;
            }
         }
         missingSubOptions.add(subOption.getOption());
      }
   }
   return missingSubOptions;
}
 
Example 9
Source File: CommunicationTool.java    From DataLink with Apache License 2.0 5 votes vote down vote up
public static Communication getReportCommunication(Communication now, Communication old, int totalStage) {
    Validate.isTrue(now != null && old != null,
            "为汇报准备的新旧metric不能为null");

    long totalReadRecords = getTotalReadRecords(now);
    long totalReadBytes = getTotalReadBytes(now);
    now.setLongCounter(TOTAL_READ_RECORDS, totalReadRecords);
    now.setLongCounter(TOTAL_READ_BYTES, totalReadBytes);
    now.setLongCounter(TOTAL_ERROR_RECORDS, getTotalErrorRecords(old));
    now.setLongCounter(TOTAL_ERROR_BYTES, getTotalErrorBytes(old));
    now.setLongCounter(WRITE_SUCCEED_RECORDS, getWriteSucceedRecords(old));
    now.setLongCounter(WRITE_SUCCEED_BYTES, getWriteSucceedBytes(old));

    long timeInterval = now.getTimestamp() - old.getTimestamp();
    long sec = timeInterval <= 1000 ? 1 : timeInterval / 1000;
    long bytesSpeed = (totalReadBytes
            - getTotalReadBytes(old)) / sec;
    long recordsSpeed = (totalReadRecords
            - getTotalReadRecords(old)) / sec;

    now.setLongCounter(BYTE_SPEED, bytesSpeed < 0 ? 0 : bytesSpeed);
    now.setLongCounter(RECORD_SPEED, recordsSpeed < 0 ? 0 : recordsSpeed);
    now.setDoubleCounter(PERCENTAGE, now.getLongCounter(STAGE) / (double) totalStage);
    //now.setState(old.getState());
    if (old.getThrowable() != null) {
        now.setThrowable(old.getThrowable());
    }

    return now;
}
 
Example 10
Source File: PFUserDO.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param email The email to set.
 * @return this for chaining.
 */
public PFUserDO setEmail(final String email)
{
  Validate.isTrue(email == null || email.length() <= 255, email);
  this.email = email;
  return this;
}
 
Example 11
Source File: GameManager.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
public void renameGame(final Game game, final String to, FutureCallback<Void> callback) {
	String oldName;
	
	synchronized (games) {
		Validate.isTrue(!hasGame(to), "A game with the name '" + to + "' already exists");
		
		oldName = game.getName();
		game.setName(to);
		
		games.remove(oldName);
		games.put(to, game);
	}
	
	heavySpleef.getDatabaseHandler().renameGame(game, oldName, to, callback);
}
 
Example 12
Source File: Commands.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
public CommandAliasHelpTopic(final String alias, final String aliasFor, final HelpMap helpMap) {
	this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor;
	this.helpMap = helpMap;
	name = alias.startsWith("/") ? alias : "/" + alias;
	Validate.isTrue(!name.equals(this.aliasFor), "Command " + name + " cannot be alias for itself");
	shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor;
}
 
Example 13
Source File: NameTagChanger.java    From NameTagChanger with MIT License 5 votes vote down vote up
/**
 * Resets a player's skin back to normal
 * <p>
 * NOTE: This does not update the player's skin, so a call to
 * updatePlayer() is needed for the changes to take effect.
 *
 * @param player the player to reset
 */
public void resetPlayerSkin(Player player) {
    Validate.isTrue(enabled, "NameTagChanger is disabled");
    if (player == null || !gameProfiles.containsKey(player.getUniqueId())) {
        return;
    }
    GameProfileWrapper profile = gameProfiles.get(player.getUniqueId());
    profile.getProperties().removeAll("textures");
    GameProfileWrapper defaultProfile = packetHandler.getDefaultPlayerProfile(player);
    if (defaultProfile.getProperties().containsKey("textures")) {
        profile.getProperties().putAll("textures", defaultProfile.getProperties().get("textures"));
    }
    checkForRemoval(player);
}
 
Example 14
Source File: AuthenticationCertificateRegistrationServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public Result<Void> revoke(RevokeCertificateContract contract) throws TechnicalConnectorException {
   Validate.isTrue(contract.isContractViewed());
   String nationalNumber = BeIDInfo.getInstance().getIdentity().getNationalNumber();
   if (!cacheRevokables.containsKey(nationalNumber)) {
      cacheRevokables.put(nationalNumber, this.getRevocableCertificates(nationalNumber));
   }

   byte[] revocableCertificatesDataSignedResponse = (byte[])cacheRevokables.get(nationalNumber);
   RevocableCertificatesDataResponse response = (RevocableCertificatesDataResponse)RaUtils.transform(revocableCertificatesDataSignedResponse, RevocableCertificatesDataResponse.class);
   List<RevocableCertificateType> revocables = new ArrayList();
   revocables.addAll(response.getRevocablePersonalCertificates());
   revocables.addAll(response.getRevocableOrganizationCertificates());
   String requestId = null;
   Iterator i$ = revocables.iterator();

   while(i$.hasNext()) {
      RevocableCertificateType revocable = (RevocableCertificateType)i$.next();
      X509Certificate cert = contract.getX509Certificate();
      if (revocable.getAuthSerial().equals(cert.getSerialNumber().toString(10)) && cert.getIssuerX500Principal().equals(new X500Principal(revocable.getIssuerDN()))) {
         requestId = revocable.getRequestId();
         break;
      }
   }

   Validate.notNull(requestId);
   RevokeDataRequest revokeDataRequest = new RevokeDataRequest();
   revokeDataRequest.setRequestId(requestId);
   revokeDataRequest.setContract(contract.getContract());
   revokeDataRequest.setRevocableCertificatesDataSignedResponse(revocableCertificatesDataSignedResponse);
   RevokeRequest revokeReq = new RevokeRequest();
   revokeReq.setRevokeDataRequest(RaUtils.transform(this.cred, revokeDataRequest, RevokeDataRequest.class));
   Result<RevokeResponse> revokeResponse = RaUtils.invokeCertRa(revokeReq, "urn:be:fgov:ehealth:etee:certra:revokecertificate", RevokeResponse.class);
   return revokeResponse.hasStatusError() ? new Result("Unable to revoke certificate", revokeResponse.getCause()) : new Result((Void)null);
}
 
Example 15
Source File: RyaMongoGeoDirectExample.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Try out some geospatial data and queries
 * @param conn
 */
private static void testAddPointAndWithinSearch(final SailRepositoryConnection conn) throws Exception {

    final String update = "PREFIX geo: <http://www.opengis.net/ont/geosparql#>  "//
            + "INSERT DATA { " //
            + "  <urn:feature> a geo:Feature ; " //
            + "    geo:hasGeometry [ " //
            + "      a geo:Point ; " //
            + "      geo:asWKT \"Point(-77.03524 38.889468)\"^^geo:wktLiteral "//
            + "    ] . " //
            + "}";

    final Update u = conn.prepareUpdate(QueryLanguage.SPARQL, update);
    u.execute();

    String queryString;
    TupleQuery tupleQuery;
    CountingResultHandler tupleHandler;

    // ring containing point
    queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#>  "//
            + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/>  "//
            + "SELECT ?feature ?point ?wkt " //
            + "{" //
            + "  ?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)) " //
            + "}";//
    tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);

    tupleHandler = new CountingResultHandler();
    tupleQuery.evaluate(tupleHandler);
    log.info("Result count -- ring containing point: " + tupleHandler.getCount());
    Validate.isTrue(tupleHandler.getCount() >= 1); // may see points from during previous runs

    // ring outside point
    queryString = "PREFIX geo: <http://www.opengis.net/ont/geosparql#>  "//
            + "PREFIX geof: <http://www.opengis.net/def/function/geosparql/>  "//
            + "SELECT ?feature ?point ?wkt " //
            + "{" //
            + "  ?feature a geo:Feature . "//
            + "  ?feature geo:hasGeometry ?point . "//
            + "  ?point a geo:Point . "//
            + "  ?point geo:asWKT ?wkt . "//
            + "  FILTER(geof:sfWithin(?wkt, \"POLYGON((-77 39, -76 39, -76 38, -77 38, -77 39))\"^^geo:wktLiteral)) " //
            + "}";//
    tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);

    tupleHandler = new CountingResultHandler();
    tupleQuery.evaluate(tupleHandler);
    log.info("Result count -- ring outside point: " + tupleHandler.getCount());
    Validate.isTrue(tupleHandler.getCount() == 0);
}
 
Example 16
Source File: CraftArrow.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
public void setKnockbackStrength(int knockbackStrength) {
    Validate.isTrue(knockbackStrength >= 0, "Knockback cannot be negative");
    getHandle().setKnockbackStrength(knockbackStrength);
}
 
Example 17
Source File: CraftMetaBook.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
public String getPage(final int page) {
    Validate.isTrue(isValidPage(page), "Invalid page number");
    return pages.get(page - 1);
}
 
Example 18
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
private void isValidApplicationId(String applicationId) {
   if (!StringUtils.isEmpty(applicationId)) {
      Validate.isTrue(APPLICATIONID_PATTERN.matcher(applicationId).matches());
   }
}
 
Example 19
Source File: MonetaConfiguration.java    From moneta with Apache License 2.0 4 votes vote down vote up
public Topic findByPlural(String pluralTopicName) {
	Validate.notEmpty(pluralTopicName, "Null or blank pluralTopicName not allowed");
	Validate.isTrue(this.initRun, "Moneta not properly initialized.");
	return pluralNameMap.get(pluralTopicName);
}
 
Example 20
Source File: LiquidityChartBuilder.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param forecast
 * @param settings (next days)
 * @return
 */
public JFreeChart createXYPlot(final LiquidityForecast forecast, final LiquidityForecastSettings settings)
{
  Validate.isTrue(settings.getNextDays() > 0 && settings.getNextDays() < 500);

  final LiquidityForecastCashFlow cashFlow = new LiquidityForecastCashFlow(forecast, settings.getNextDays());

  final TimeSeries accumulatedSeries = new TimeSeries(I18n.getString("plugins.liquidityplanning.forecast.dueDate"));
  final TimeSeries accumulatedSeriesExpected = new TimeSeries(
      PFUserContext.getLocalizedString("plugins.liquidityplanning.forecast.expected"));
  final TimeSeries worstCaseSeries = new TimeSeries(I18n.getString("plugins.liquidityplanning.forecast.worstCase"));
  double accumulatedExpected = settings.getStartAmount().doubleValue();
  double accumulated = accumulatedExpected;
  double worstCase = accumulated;

  final DayHolder dh = new DayHolder();
  final Date lower = dh.getDate();
  for (int i = 0; i < settings.getNextDays(); i++) {
    if (log.isDebugEnabled() == true) {
      log.debug("day: " + i + ", credits=" + cashFlow.getCredits()[i] + ", debits=" + cashFlow.getDebits()[i]);
    }
    final Day day = new Day(dh.getDayOfMonth(), dh.getMonth() + 1, dh.getYear());
    if (i > 0) {
      accumulated += cashFlow.getDebits()[i - 1].doubleValue() + cashFlow.getCredits()[i - 1].doubleValue();
      accumulatedExpected += cashFlow.getDebitsExpected()[i - 1].doubleValue() + cashFlow.getCreditsExpected()[i - 1].doubleValue();
      worstCase += cashFlow.getCredits()[i - 1].doubleValue();
    }
    accumulatedSeries.add(day, accumulated);
    accumulatedSeriesExpected.add(day, accumulatedExpected);
    worstCaseSeries.add(day, worstCase);
    dh.add(Calendar.DATE, 1);
  }
  dh.add(Calendar.DATE, -1);
  final XYChartBuilder cb = new XYChartBuilder(null, null, null, null, true);

  int counter = 0;

  final TimeSeriesCollection xyDataSeries = new TimeSeriesCollection();
  xyDataSeries.addSeries(accumulatedSeries);
  xyDataSeries.addSeries(worstCaseSeries);
  final XYLineAndShapeRenderer lineRenderer = new XYLineAndShapeRenderer(true, false);
  lineRenderer.setSeriesPaint(0, Color.BLACK);
  lineRenderer.setSeriesVisibleInLegend(0, true);
  lineRenderer.setSeriesPaint(1, cb.getGrayMarker());
  lineRenderer.setSeriesStroke(1, cb.getDashedStroke());
  lineRenderer.setSeriesVisibleInLegend(1, true);
  cb.setRenderer(counter, lineRenderer).setDataset(counter++, xyDataSeries);

  final TimeSeriesCollection accumulatedSet = new TimeSeriesCollection();
  accumulatedSet.addSeries(accumulatedSeriesExpected);
  final XYDifferenceRenderer diffRenderer = new XYDifferenceRenderer(cb.getGreenFill(), cb.getRedFill(), true);
  diffRenderer.setSeriesPaint(0, cb.getRedMarker());
  cb.setRenderer(counter, diffRenderer).setDataset(counter++, accumulatedSet)
  .setStrongStyle(diffRenderer, false, accumulatedSeriesExpected);
  diffRenderer.setSeriesVisibleInLegend(0, true);

  cb.setDateXAxis(true).setDateXAxisRange(lower, dh.getDate()).setYAxis(true, null);
  return cb.getChart();
}