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

The following examples show how to use org.apache.commons.lang.Validate. 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
/**
 * 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 2
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 Project: oodt   Source File: GetFilePercentTransferredCliAction.java    License: 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 4
Source Project: HeavySpleef   Source File: LocationFlag.java    License: 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 5
Source Project: SimFix   Source File: 1_FastDateFormat.java    License: 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 6
Source Project: HeavySpleef   Source File: ProxyExecution.java    License: 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 7
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 8
Source Project: Thermos   Source File: TileEntityCommand.java    License: 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 9
Source Project: oodt   Source File: DynWorkflowCliAction.java    License: 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 10
Source Project: UhcCore   Source File: VaultManager.java    License: 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 11
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 12
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 13
Source Project: Thermos   Source File: CraftIpBanList.java    License: 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 14
Source Project: XSeries   Source File: SkullUtils.java    License: 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 15
Source Project: Thermos   Source File: CraftTeam.java    License: 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 16
Source Project: oodt   Source File: ClassExistsCmdLineOptionValidator.java    License: 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 17
public static synchronized SchematronValidator getInstance(String schematronLocation) throws TransformerException {
   Validate.notEmpty(schematronLocation, "Location for the Schematron schema needs to be specified.");
   LOG.info(String.format("Retrieving validator for schematron file [%s]", schematronLocation));
   if (!cachedTemplates.containsKey(schematronLocation)) {
      LOG.debug(String.format("Template for schematron file [%s] not in cache, creating it", schematronLocation));
      Source dataSource = new StreamSource(SchematronValidator.class.getResource(schematronLocation).toString());
      Templates templates = transformerFactory.newTemplates(dataSource);
      cachedTemplates.put(schematronLocation, templates);
      LOG.debug(String.format("Template for schematron file [%s] created and cached", schematronLocation));
   }

   Templates template = (Templates)cachedTemplates.get(schematronLocation);
   return new SchematronValidator(template);
}
 
Example 18
public RevocationRequest(byte[] publicKeyIdentifier, GeneratedRevocationContract contract) throws TechnicalConnectorException {
   Validate.notNull(publicKeyIdentifier);
   Validate.notNull(contract);
   Validate.isTrue(contract.isContractViewed());
   this.publicKeyIdentifier = ArrayUtils.clone(publicKeyIdentifier);
   this.contract = contract;
}
 
Example 19
Source Project: zap-extensions   Source File: ExtensionSelenium.java    License: Apache License 2.0 5 votes vote down vote up
private static void validateProxyAddressPort(String proxyAddress, int proxyPort) {
    Validate.notEmpty(proxyAddress, "Parameter proxyAddress must not be null nor empty.");
    if (proxyPort < MIN_PORT || proxyPort > MAX_PORT) {
        throw new IllegalArgumentException(
                "Parameter proxyPort must be under: " + MIN_PORT + " <= port <= " + MAX_PORT);
    }
}
 
Example 20
protected BrooklinMetricInfo(String nameOrRegex, Optional<List<String>> attributes) {
  Validate.notNull(nameOrRegex, "Metric name/regex must be non-null");
  Validate.notNull(attributes, "attributes must be non-null");
  _nameOrRegex = nameOrRegex;
  _attributes = attributes;
  _hashCode = Objects.hash(_nameOrRegex, _attributes.map(HashSet::new).orElse(null));
}
 
Example 21
Source Project: oodt   Source File: FilemgrUniquenessChecker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean performAction(File product, Metadata productMetadata)
      throws CrawlerActionException {
   try {
      Validate.notNull(productMetadata.getMetadata(PRODUCT_NAME),
            PRODUCT_NAME + " was not found in metadata");

      FileManagerClient fmClient = RpcCommunicationFactory.createClient(new URL(this.filemgrUrl));
      return !fmClient.hasProduct(productMetadata.getMetadata(PRODUCT_NAME));
   } catch (Exception e) {
      throw new CrawlerActionException("Product failed uniqueness check : ["
            + product + "] : " + e.getMessage(), e);
   }
}
 
Example 22
Source Project: keycloak   Source File: ResourceServerTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResourceServer newEntity(Client client) {
    Validate.notNull(client);
    Validate.notNull(client.getRepresentation());
    Validate.notNull(client.getRepresentation().getBaseUrl());
    return new ResourceServer(client);
}
 
Example 23
Source Project: Skript   Source File: Commands.java    License: 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 24
@Override
protected void doCommit(DefaultTransactionStatus status) throws TransactionException {
	@SuppressWarnings("unchecked")
	List<DefaultTransactionStatus> list = 
	      (List<DefaultTransactionStatus>) status.getTransaction();

	logger.info("prepare to commit transactions on multiple data sources.");
	Validate.isTrue(list.size() <= this.getTransactionManagers().size());

	TransactionException lastException = null;
	for(int i=list.size()-1; i>=0;i--){
		PlatformTransactionManager transactionManager=this.getTransactionManagers().get(i);
		TransactionStatus localTransactionStatus=list.get(i);
		
		try{
			transactionManager.commit(localTransactionStatus);
		}
		catch (TransactionException e) {
			lastException=e;
			logger.error("Error in commit", e);

		}
	}
	if (lastException != null) {
		throw lastException;
		// Rollback will ensue as long as rollbackOnCommitFailure=true
	}

}
 
Example 25
/**
 * @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 26
Source Project: projectforge-webapp   Source File: BaseDao.java    License: 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 27
Source Project: rya   Source File: RyaGeoDirectExample.java    License: 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!
}
 
Example 28
public KeyStoreInfo(String pathKeystore, String keystoreType, char[] pwdKeystore, String alias, char[] privateKeyPwd) throws TechnicalConnectorException {
   Validate.notEmpty(alias);
   Validate.notNull(privateKeyPwd);
   if (StringUtils.isNotEmpty(pathKeystore)) {
      Validate.notEmpty(keystoreType);
      Validate.notNull(pwdKeystore);
   }

   this.keystorePath = this.getKeystoreLoc(pathKeystore);
   this.keystoreType = keystoreType;
   this.keystorePassword = ArrayUtils.clone(pwdKeystore);
   this.alias = alias;
   this.privateKeyPassword = ArrayUtils.clone(privateKeyPwd);
}
 
Example 29
Source Project: NyaaUtils   Source File: MailboxLocations.java    License: 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 30
Source Project: brooklin   Source File: JsonUtils.java    License: 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;
}