/** * Sends the data to the bStats server. * * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(JsonObject data) throws Exception { Validate.notNull(data, "Data cannot be null"); HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); connection.getInputStream().close(); // We don't care about the response - Just send our data :) }
@Transactional(propagation = Propagation.REQUIRES_NEW) public Raid removeAllSignUpsAt(String raidId, LocalDateTime startAt) { Validate.notNull(raidId, "Raid ID cannot be null"); Validate.notNull(startAt, "Start time cannot be null"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("About to remove signups for raid " + raidId + " at " + printTimeIfSameDay(startAt)); } RaidEntity entity = findEntityByRaidId(raidId); if (entity != null) { for (RaidEntitySignUp signUp : entity.getSignUpsAsSet()) { if (signUp.getArrivalTime().equals(startAt.toLocalTime())) { RaidEntitySignUp removed = entity.removeSignUp(signUp); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Removed signup: " + removed); } } } entity = raidEntityRepository.save(entity); } return getRaidInstance(entity); }
@Nullable private ExtensionInfo unmarshalExtensionInfo(@NotNull final File file) { Validate.notNull(file); try { if (null == EXTENSION_INFO_JAXB_CONTEXT) { LOG.error(String.format( "Can not unmarshal '%s' because JAXBContext has not been created.", file.getAbsolutePath() )); return null; } final Unmarshaller jaxbUnmarshaller = EXTENSION_INFO_JAXB_CONTEXT.createUnmarshaller(); return (ExtensionInfo) jaxbUnmarshaller.unmarshal(file); } catch (JAXBException e) { LOG.error("Can not unmarshal " + file.getAbsolutePath(), e); } return null; }
static void readId(final TrackingReplayableIdAndSizeByteSource source, IdConsumer resultAcceptor) { if (!isEnoughBytes(source, 1)) { return; } final int firstByte = readByte(source); if (firstByte == -1) { resultAcceptor.accept(firstByte, 1); } Validate.isTrue(firstByte >= 0, "EBML Id has negative firstByte" + firstByte); final int numAdditionalBytes = getNumLeadingZeros(firstByte); if (!isEnoughBytes(source, numAdditionalBytes)) { return; } Validate.isTrue(numAdditionalBytes <= (EBML_ID_MAX_BYTES - 1), "Trying to decode an EBML ID and it wants " + numAdditionalBytes + " more bytes, but IDs max out at 4 bytes. firstByte was " + firstByte); final int rest = (int) readEbmlValueNumber(source, numAdditionalBytes); resultAcceptor.accept(firstByte << (numAdditionalBytes * Byte.SIZE) | rest, numAdditionalBytes + 1); }
protected void initializeProcessor(ProcessorInstanceHolder instanceHolder, BaseProcessorAdapter adapter) { Processor processor = instanceHolder.getProcessor(); processor.onConfigure(); // Must be verified after onConfigure, because onConfigure may change for example the name of the processor. Optional<Map.Entry<ProcessorType, RegistrationHandler>> alreadyRegistered = findAlreadyRegisteredByDifferentType(adapter); if (alreadyRegistered.isPresent()) { Validate.isTrue(false, "% named '%' has already been registered as % type", adapter.getType().getDisplayName(), adapter.getName(), alreadyRegistered.get().getKey().getDisplayName()); } processor.getAdapter().validate(); if (processor.getAdapter().getDefinition().isSingleton()) { processor.onInit(); } }
@Override public float get(int x, int y) { Validate.inclusiveBetween(0, width-1, x); Validate.inclusiveBetween(0, height-1, y); if(region == null) return 0; int inRegionX = x-regionPosition.x; int inRegionY = y-regionPosition.y; if(inRegionX >= 0 && inRegionX < region.getWidth()) if(inRegionY >= 0 && inRegionY < region.getHeight()) return region.get(inRegionX, inRegionY); return 0; }
/** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. * 如向上转型到Object仍无法找到, 返回null. * 匹配函数名+参数类型。 * <p/> * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 continue;// new add } } return null; }
/** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. * 如向上转型到Object仍无法找到, 返回null. * 匹配函数名+参数类型。 * <p> * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 continue;// new add } } return null; }
/** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. * 如向上转型到Object仍无法找到, 返回null. * 只匹配函数名。 * <p> * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethodByName(final Object obj, final String methodName) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { Method[] methods = searchType.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { makeAccessible(method); return method; } } } return null; }
public void moveAllSignUpsForTimeToNewTime(String raidId, LocalDateTime currentStartAt, LocalDateTime newDateTime, User user) { Validate.notNull(raidId, "Raid ID cannot be null"); Validate.notNull(currentStartAt, "Current start time cannot be null"); Validate.notNull(newDateTime, "New start time cannot be null"); Validate.notNull(user, "User cannot be null"); RaidEntity entity = raidEntityRepository.findOne(raidId); if (entity != null) { for (RaidEntitySignUp signUp : entity.getSignUpsAsSet()) { if (signUp.getArrivalTime().equals(currentStartAt.toLocalTime())) { signUp.setEta(Utils.printTime(newDateTime.toLocalTime())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Changed ETA for signup: " + signUp); } } } raidEntityRepository.save(entity); } else { throw new UserMessedUpException(user, localeService.getMessageFor(LocaleService.NO_RAID_AT_GYM, localeService.getLocaleForUser(user))); } // todo: throw error if problem? }
protected void configurePlatformRoots( @NotNull final HybrisModuleDescriptor moduleDescriptor, @NotNull final ContentEntry contentEntry ) { Validate.notNull(moduleDescriptor); Validate.notNull(contentEntry); if (!HybrisConstants.PLATFORM_EXTENSION_NAME.equalsIgnoreCase(moduleDescriptor.getName())) { return; } final File rootDirectory = moduleDescriptor.getRootDirectory(); final File platformBootstrapDirectory = new File(rootDirectory, PLATFORM_BOOTSTRAP_DIRECTORY); if (!moduleDescriptor.getRootProjectDescriptor().isImportOotbModulesInReadOnlyMode()) { final File platformBootstrapResourcesDirectory = new File(platformBootstrapDirectory, RESOURCES_DIRECTORY); contentEntry.addSourceFolder( VfsUtil.pathToUrl(platformBootstrapResourcesDirectory.getAbsolutePath()), JavaResourceRootType.RESOURCE ); } excludeDirectory(contentEntry, new File(platformBootstrapDirectory, PLATFORM_MODEL_CLASSES_DIRECTORY)); excludeDirectory(contentEntry, new File(rootDirectory, PLATFORM_TOMCAT_DIRECTORY)); contentEntry.addExcludePattern("apache-ant-*"); }
public MessageHeader transform(AdtMessage sourceMessage) throws ParseException, MapperException, TransformException { Validate.notNull(sourceMessage); Validate.notNull(sourceMessage.getMshSegment()); Validate.notNull(sourceMessage.getEvnSegment()); MshSegment mshSegment = sourceMessage.getMshSegment(); EvnSegment evnSegment = sourceMessage.getEvnSegment(); MessageHeader target = new MessageHeader(); setId(sourceMessage, target); setTimestamp(mshSegment, target); setEvent(mshSegment, target); setSource(mshSegment, target); setDestination(mshSegment, target); setResponsible(target); setMessageControlId(mshSegment, target); setSequenceNumber(mshSegment, target); setEnterer(evnSegment, target); setData(target); return target; }
public <V> ListenableFuture<V> callFromMainThread(Callable<V> callable) { Validate.notNull(callable); if (!this.isCallingFromMinecraftThread() && !this.isServerStopped()) { ListenableFutureTask<V> listenablefuturetask = ListenableFutureTask.<V>create(callable); synchronized (this.futureTaskQueue) { this.futureTaskQueue.add(listenablefuturetask); return listenablefuturetask; } } else { try { return Futures.<V>immediateFuture(callable.call()); } catch (Exception exception) { return Futures.immediateFailedCheckedFuture(exception); } } }
@NotNull @Override public String getPlaceholder(@NotNull final PsiElement psiElement) { Validate.notNull(psiElement); if (ImpexPsiUtils.isImpexAttribute(psiElement)) { final ImpexAttribute attribute = (ImpexAttribute) psiElement; return this.getPlaceholder(attribute); } if (ImpexPsiUtils.isImpexParameters(psiElement)) { return IMPEX_PARAMETERS_PLACEHOLDER; } return psiElement.getText(); }
@Nonnull @Override public Process unmarshallBusinessProcessXml(@NotNull final File file) throws UnmarshalException { Validate.notNull(file); try { if (null == this.jaxbContext) { LOG.error(String.format( "Can not unmarshall '%s' because JAXBContext has not been created.", file.getAbsolutePath() )); return null; } final Unmarshaller jaxbUnmarshaller = this.jaxbContext.get().createUnmarshaller(); return (Process) jaxbUnmarshaller.unmarshal(file); } catch (Exception e) { throw new UnmarshalException("Can not unmarshall " + file.getAbsolutePath(), e); } }
private void loadZkInfos() { Properties props = new Properties(); try { props.load(ZKChildMonitor.class.getResourceAsStream(CLUSTER_CONF_FILE)); } catch (IOException e) { LOGGER.error("Read cluster.properties exception", e); } String zkServersStr = System.getProperty(ZK_SERVERS); if (StringUtils.isNotEmpty(zkServersStr)) { LOGGER.warn("Apply the zk servers from system setting: [{}]", zkServersStr); } else { zkServersStr = props.getProperty(ZK_SERVERS); LOGGER.warn("Apply the zk servers from cluster.properties: [{}]", zkServersStr); } Validate.notEmpty(zkServersStr); zkServers = zkServersStr; }
public static List<Split> kfold(Dataset dataset, int k, boolean shuffle, long seed) { int length = dataset.length(); Validate.isTrue(k < length); int[] indexes = IntStream.range(0, length).toArray(); if (shuffle) { shuffle(indexes, seed); } int[][] folds = prepareFolds(indexes, k); List<Split> result = new ArrayList<>(); for (int i = 0; i < k; i++) { int[] testIdx = folds[i]; int[] trainIdx = combineTrainFolds(folds, indexes.length, i); result.add(Split.fromIndexes(dataset, trainIdx, testIdx)); } return result; }
protected String resolveProcessorName(KnowledgeBase knowledgeBase, Object processorClass, Class javaClass) { Validate.notNull(processorClass, "Processor class cannot be null"); String name = knowledgeBase.getInterpreter().getScriptKnowledgeBaseProcessorClassName(processorClass); if (name != null) { // Script-based processor. return name; } // Java-based processor. if (processorClass instanceof Class) { Class destJavaClass = (Class) processorClass; if (!javaClass.isAssignableFrom(destJavaClass)) { throw new SpongeException( "Unsupported processor specification: " + destJavaClass.getName() + " can't be used as " + javaClass.getName()); } return destJavaClass.getName(); } else { throw new SpongeException("Unsupported processor class: " + processorClass); } }
@Contract(pure = true) private boolean isNameEqualsAndAndValueIsTrue( @NotNull final ImpexAttribute impexAttribute, @NotNull final String name ) { Validate.notNull(impexAttribute); Validate.notNull(name); if (!this.quoteAwareStringEquals(name, impexAttribute.getAnyAttributeName().getText())) { return false; } if (null == impexAttribute.getAnyAttributeValue()) { return false; } final String value = impexAttribute.getAnyAttributeValue().getText(); if (null == value) { return false; } final String trimmedValue = value.trim(); return this.quoteAwareStringEquals("true", trimmedValue); }
/** * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. * * 如向上转型到Object仍无法找到, 返回null. */ public static Field getAccessibleField(final Object obj, final String fieldName) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(fieldName, "fieldName can't be blank"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { Field field = superClass.getDeclaredField(fieldName); makeAccessible(field); return field; } catch (NoSuchFieldException e) {//NOSONAR // Field不在当前类定义,继续向上转型 continue;// new add } } return null; }
/** * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. * 如向上转型到Object仍无法找到, 返回null. * 匹配函数名+参数类型。 * * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method不在当前类定义,继续向上转型 continue;// new add } } return null; }
public <V> ListenableFuture<V> addScheduledTask(Callable<V> callableToSchedule) { Validate.notNull(callableToSchedule); if (this.isCallingFromMinecraftThread()) { try { return Futures.<V>immediateFuture(callableToSchedule.call()); } catch (Exception exception) { return Futures.immediateFailedCheckedFuture(exception); } } else { ListenableFutureTask<V> listenablefuturetask = ListenableFutureTask.<V>create(callableToSchedule); synchronized (this.scheduledTasks) { this.scheduledTasks.add(listenablefuturetask); return listenablefuturetask; } } }
public KafkaMonitor(String zkServers, String kafkaServers, int latThreshold) { Validate.notBlank(zkServers); Validate.notBlank(kafkaServers); this.latThreshold = latThreshold; zkClient = new ZkClient(zkServers, 10000, 10000, ZKStringSerializer$.MODULE$); try { zkConsumerCommand = new ZkConsumerCommand(zkClient, zkServers, kafkaServers); kafkaConsumerCommand = new KafkaConsumerCommand(kafkaServers); } catch (Exception e) { e.printStackTrace(); } // initCollectionTimer(); }
private void configureFacetDependencies( @NotNull final HybrisModuleDescriptor moduleDescriptor, @NotNull final Map<String, ModifiableFacetModel> modifiableFacetModelMap ) { Validate.notNull(moduleDescriptor); Validate.notNull(modifiableFacetModelMap); final SpringFileSet springFileSet = getSpringFileSet(modifiableFacetModelMap, moduleDescriptor.getName()); if (springFileSet == null) { return; } for (HybrisModuleDescriptor dependsOnModule : moduleDescriptor.getDependenciesTree()) { final SpringFileSet parentFileSet = getSpringFileSet(modifiableFacetModelMap, dependsOnModule.getName()); if (parentFileSet == null) { continue; } springFileSet.addDependency(parentFileSet); } }
public static List<Cx> getAllEpisodeIdentifiers(AdtMessage source) { Validate.notNull(source.getPidSegment()); Validate.notNull(source.getPv1Segment()); List<Cx> episodeIdentifiers = new ArrayList<>(); if (source.getPidSegment().getPatientAccountNumber() != null) episodeIdentifiers.add(source.getPidSegment().getPatientAccountNumber()); if (source.getPv1Segment().getVisitNumber() != null) episodeIdentifiers.add(source.getPv1Segment().getVisitNumber()); if (source.getPv1Segment().getAlternateVisitID() != null) episodeIdentifiers.add(source.getPv1Segment().getAlternateVisitID()); return episodeIdentifiers; }
public static Field getAccessibleField(Class<?> cls, String fieldName) { Validate.notNull(cls, "class could not be null", new Object[0]); Validate.notBlank(fieldName, "property could not be null", new Object[0]); Class superClass = cls; while (superClass != Object.class) { try { Field field = superClass.getDeclaredField(fieldName); makeAccessible(field); return field; } catch (NoSuchFieldException var4) { superClass = superClass.getSuperclass(); } } return null; }
public static void updateTaskGroupCommunication(final int taskGroupId, final Communication communication) { Validate.isTrue(taskGroupCommunicationMap.containsKey( taskGroupId), String.format("taskGroupCommunicationMap中没有注册taskGroupId[%d]的Communication," + "无法更新该taskGroup的信息", taskGroupId)); taskGroupCommunicationMap.put(taskGroupId, communication); }
public SimpleMenuEntry(String navigationTarget, String name) { super(); Validate.notBlank(navigationTarget); Validate.notBlank(name); this.navigationTarget = navigationTarget; this.name = name; }
@Override public void run(@NotNull final ProgressIndicator indicator) { Validate.notNull(indicator); this.projectImportParameters.setRootDirectoryAndScanForModules( this.rootProjectDirectory, new DirectoriesScannerProgressIndicatorUpdaterProcessor(indicator), new DirectoriesScannerErrorsProcessor() ); }
@SuppressWarnings("StandardVariableNames") @Nullable @Override public String apply(@Nullable final ImpexModifierValue f) { Validate.notNull(f); return f.getModifierValue(); }
public static boolean isTypeDoubleStrongVsPokemonWithTwoTypes(String pokemonTypeOne, String pokemonTypeTwo, String typeToCheck) { Validate.notEmpty(pokemonTypeOne); Validate.notEmpty(pokemonTypeTwo); Validate.notEmpty(typeToCheck); if (typeIsStrongVsPokemon(pokemonTypeOne, typeToCheck) && typeIsStrongVsPokemon(pokemonTypeTwo, typeToCheck)) { return true; } else { return false; } }
/** * @param selectPercent * 采样率,在0-100 之间,可以有小数位 */ protected Sampler(double selectPercent) { Validate.isTrue((selectPercent >= 0) && (selectPercent <= 100), "Invalid selectPercent value: " + selectPercent); this.threshold = selectPercent / 100; }
@Contract protected void clearHighlightedArea(@NotNull final Editor editor) { Validate.notNull(editor); if (!cache.asMap().isEmpty()) { final List<PsiElement> column = cache.getIfPresent(editor); cache.invalidate(editor); if (null != column) { ApplicationManager.getApplication() .invokeLater( () -> modifyHighlightedArea(editor, column, true)); } } }
@Nullable @Override public String getPlaceholderText(@NotNull final ASTNode node) { Validate.notNull(node); return ImpexFoldingPlaceholderBuilderFactory.getPlaceholderBuilder().getPlaceholder(node.getPsi()); }
@Override protected boolean stop(Object id) { Validate.notNull(id); Validate.isTrue(id instanceof Integer, "Id must be a Integer!"); boolean state = state(id); if (!state) { return false; } Integer castedId = (Integer) id; plugin.getServer().getScheduler().cancelTask(castedId); return true; }
private Sound.Type deserializeType(JsonObject object, Sound.Type defaultValue) { Sound.Type sound$type = defaultValue; if (object.has("type")) { sound$type = Sound.Type.getByName(JsonUtils.getString(object, "type")); Validate.notNull(sound$type, "Invalid type", new Object[0]); } return sound$type; }
public DefaultJavaLibraryDescriptor( @NotNull final File libraryFile, final boolean isExported, final boolean isDirectoryWithClasses ) { Validate.notNull(libraryFile); this.libraryFile = libraryFile; this.sourcesFile = null; this.isExported = isExported; this.isDirectoryWithClasses = isDirectoryWithClasses; this.scope = DependencyScope.COMPILE; }
public Object get(String path, Object def) { Validate.notNull(path, "Path cannot be null"); if (path.length() == 0) { return this; } ConfigurationBase root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot access section without a root"); } final char separator = root.options().pathSeparator(); // i1 is the leading (higher) index // i2 is the trailing (lower) index int i1 = -1, i2; ConfigurationSection section = this; while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { section = section.getConfigurationSection(path.substring(i2, i1)); if (section == null) { return def; } } String key = path.substring(i2); if (section == this) { Object result = map.get(key); return (result == null) ? def : result; } return section.get(key, def); }
/** * 生成随机的Byte[]作为salt. * * @param numBytes byte数组的大小 */ public static byte[] generateSalt(int numBytes) { Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes); byte[] bytes = new byte[numBytes]; random.nextBytes(bytes); return bytes; }