@CheckReturnValue public RestAction<MessageJson> getMessageById(long channelId, long messageId) { Route.CompiledRoute route = Route.Messages.GET_MESSAGE.compile(Long.toString(channelId), Long.toString(messageId)); return new RestAction<MessageJson>(fakeJDA, route) { @Override protected void handleResponse(Response response, Request<MessageJson> request) { if (response.isOk()) request.onSuccess(new MessageJson(response.getObject())); else request.onFailure(response); } }; }
/** * Creates a new {@link Scheme} instance. * * @param n the number of parts to produce (must be {@code >1}) * @param k the threshold of joinable parts (must be {@code <= n}) * @return an {@code N}/{@code K} {@link Scheme} */ @CheckReturnValue public static Scheme of(@Nonnegative int n, @Nonnegative int k) { checkArgument(k > 1, "K must be > 1"); checkArgument(n >= k, "N must be >= K"); checkArgument(n <= 255, "N must be <= 255"); return new AutoValue_Scheme(n, k); }
/** * Splits the given secret into {@code n} parts, of which any {@code k} or more can be combined to * recover the original secret. * * @param secret the secret to split * @return a map of {@code n} part IDs and their values */ @CheckReturnValue public Map<Integer, byte[]> split(byte[] secret) { // generate part values final byte[][] values = new byte[n()][secret.length]; for (int i = 0; i < secret.length; i++) { // for each byte, generate a random polynomial, p final byte[] p = GF256.generate(random, k() - 1, secret[i]); for (int x = 1; x <= n(); x++) { // each part's byte is p(partId) values[x - 1][i] = GF256.eval(p, (byte) x); } } // return as a set of objects final Map<Integer, byte[]> parts = new HashMap<>(n()); for (int i = 0; i < values.length; i++) { parts.put(i + 1, values[i]); } return Collections.unmodifiableMap(parts); }
@CheckReturnValue public static boolean canRunDJAction(AvaIre avaire, Message message, DJGuildLevel level) { GuildTransformer transformer = GuildController.fetchGuild(avaire, message); if (transformer == null) { return level.getLevel() <= DJGuildLevel.getNormal().getLevel(); } DJGuildLevel guildLevel = transformer.getDJLevel(); if (guildLevel == null) { guildLevel = DJGuildLevel.getNormal(); } switch (guildLevel) { case ALL: return true; case NONE: return hasDJRole(message); default: return hasDJRole(message) || level.getLevel() < guildLevel.getLevel(); } }
@CheckReturnValue public static VoiceConnectStatus connectToVoiceChannel(Message message, boolean moveChannelIfConnected) { AudioManager audioManager = message.getGuild().getAudioManager(); if (!audioManager.isAttemptingToConnect()) { VoiceChannel channel = message.getMember().getVoiceState().getChannel(); if (channel == null) { return VoiceConnectStatus.NOT_CONNECTED; } if (audioManager.isConnected()) { if (channel.getIdLong() == audioManager.getConnectedChannel().getIdLong()) { return VoiceConnectStatus.CONNECTED; } if (moveChannelIfConnected) { return connectToVoiceChannel(message, channel, audioManager); } return VoiceConnectStatus.CONNECTED; } return connectToVoiceChannel(message, channel, audioManager); } return VoiceConnectStatus.CONNECTED; }
/** * Use this for COUNT() and similar jpql queries which are guaranteed to return a result */ @Nonnull @CheckReturnValue public <T> T selectJpqlQuerySingleResult(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters, @Nonnull final Class<T> resultClass) throws DatabaseException { final EntityManager em = this.databaseConnection.getEntityManager(); try { final Query q = em.createQuery(queryString); if (parameters != null) { parameters.forEach(q::setParameter); } em.getTransaction().begin(); final T result = resultClass.cast(q.getSingleResult()); em.getTransaction().commit(); return setSauce(result); } catch (final PersistenceException | ClassCastException e) { final String message = String.format("Failed to select single result JPQL query %s with %s parameters for class %s on DB %s", queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName()); throw new DatabaseException(message, e); } finally { em.close(); } }
@CheckReturnValue @VisibleForTesting @SuppressWarnings("WeakerAccess") static boolean isAvailable(@Nonnull AnActionEvent event) { final Project project = event.getProject(); if (project == null) { return false; } final IdeView view = event.getData(LangDataKeys.IDE_VIEW); if (view == null) { return false; } final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); final ProjectFileIndex fileIndex = rootManager.getFileIndex(); final Optional<PsiDirectory> sourceDirectory = Stream.of(view.getDirectories()) .filter(directory -> { final VirtualFile virtualFile = directory.getVirtualFile(); return fileIndex.isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES); }) .findFirst(); return sourceDirectory.isPresent(); }
@CheckReturnValue private static VoiceConnectStatus connectToVoiceChannel(Message message, VoiceChannel channel, AudioManager audioManager) { List<Permission> permissions = message.getGuild().getMember(message.getJDA().getSelfUser()).getPermissions(channel); if (!permissions.contains(Permission.VOICE_CONNECT)) { return VoiceConnectStatus.MISSING_PERMISSIONS; } if (channel.getUserLimit() > 0 && !permissions.contains(Permission.VOICE_MOVE_OTHERS) && channel.getUserLimit() <= channel.getMembers().size()) { return VoiceConnectStatus.USER_LIMIT; } try { audioManager.openAudioConnection(channel); } catch (Exception ex) { return VoiceConnectStatus.USER_LIMIT; } return VoiceConnectStatus.CONNECTED; }
/** * @return An entity if it exists in the database or null if it doesn't exist. If the entity is a SaucedEntity the * sauce will be set. */ @Nullable @CheckReturnValue public <E extends IEntity<I, E>, I extends Serializable> E getEntity(@Nonnull final EntityKey<I, E> entityKey) throws DatabaseException { final EntityManager em = this.databaseConnection.getEntityManager(); try { em.getTransaction().begin(); @Nullable final E result = em.find(entityKey.clazz, entityKey.id); em.getTransaction().commit(); return setSauce(result); } catch (final PersistenceException e) { final String message = String.format("Failed to find entity of class %s for id %s on DB %s", entityKey.clazz.getName(), entityKey.id.toString(), this.databaseConnection.getName()); throw new DatabaseException(message, e); } finally { em.close(); } }
/** * @return true if the test query was successful and false if not */ @CheckReturnValue public boolean runTestQuery() { final EntityManager em = this.emf.createEntityManager(); try { em.getTransaction().begin(); em.createNativeQuery(TEST_QUERY).getResultList(); em.getTransaction().commit(); return true; } catch (final PersistenceException e) { log.error("Test query failed", e); return false; } finally { em.close(); } }
/** * The difference of persisting to merging is that persisting will throw an exception if the entity exists already. * * @return The managed version of the provided entity (with set autogenerated values for example). */ @Nonnull @CheckReturnValue //returns whatever was passed in, with a sauce if it was a sauced entity public <E> E persist(@Nonnull final E entity) throws DatabaseException { final EntityManager em = this.databaseConnection.getEntityManager(); try { em.getTransaction().begin(); em.persist(entity); em.getTransaction().commit(); return setSauce(entity); } catch (final PersistenceException e) { final String message = String.format("Failed to persist entity %s on DB %s", entity.toString(), this.databaseConnection.getName()); throw new DatabaseException(message, e); } finally { em.close(); } }
@Nonnull @CheckReturnValue public DatabaseConnection build() throws DatabaseException { return new DatabaseConnection( this.dbName, this.jdbcUrl, this.dataSourceProps, this.hikariConfig, this.hibernateProps, this.entityPackages, this.poolName, this.sshDetails, this.hikariStats, this.hibernateStats, this.checkConnection, this.proxyDataSourceBuilder, this.flyway ); }
/** * Decrypts the given encrypted message. * * @param nonce the 12-byte random nonce used to encrypt the message * @param ciphertext the returned value from {@link #seal(byte[], byte[], byte[])} * @param data the authenticated data used to encrypt the message (may be empty) * @return the plaintext message */ @CheckReturnValue public Optional<byte[]> open(byte[] nonce, byte[] ciphertext, byte[] data) { if (nonce.length != NONCE_SIZE) { throw new IllegalArgumentException("Nonce must be 12 bytes long"); } final byte[] c = new byte[ciphertext.length - AES_BLOCK_SIZE]; final byte[] tag = new byte[AES_BLOCK_SIZE]; System.arraycopy(ciphertext, 0, c, 0, c.length); System.arraycopy(ciphertext, c.length, tag, 0, tag.length); final byte[] authKey = subKey(0, 1, nonce); final Cipher encAES = newAES(subKey(2, aes128 ? 3 : 5, nonce)); aesCTR(encAES, tag, c, c); final byte[] actual = hash(encAES, authKey, nonce, c, data); if (MessageDigest.isEqual(tag, actual)) { return Optional.of(c); } return Optional.empty(); }
@Override @CheckReturnValue public void afterInvocation(final IInvokedMethod method, final ITestResult testResult) { if (method.isTestMethod()) { final String fileName = String.format("http://localhost:4444/video/%s.mp4", testResult.getAttribute("sessionId")); attachUri("Video", fileName); } }
@CheckReturnValue public MessageAction editMessage(long channelId, long messageId, Message newContent) { Checks.notNull(newContent, "message"); Route.CompiledRoute route = Route.Messages.EDIT_MESSAGE.compile(Long.toString(channelId), Long.toString(messageId)); return new MessageAction(fakeJDA, route, new TextChannelImpl(channelId, new GuildImpl(fakeJDA, 0))).apply(newContent); }
@CheckReturnValue public MessageAction sendMessage(long channelId, Message msg) { Checks.notNull(msg, "Message"); Route.CompiledRoute route = Route.Messages.SEND_MESSAGE.compile(Long.toString(channelId)); return new MessageAction(fakeJDA, route, new TextChannelImpl(channelId, new GuildImpl(fakeJDA, 0))).apply(msg); }
@CheckReturnValue public static VoiceConnectStatus play(Message message, GuildMusicManager musicManager, AudioTrack track) { VoiceConnectStatus voiceConnectStatus = connectToVoiceChannel(message); if (voiceConnectStatus.isSuccess()) { musicManager.getScheduler().queue(track, message.getAuthor()); } return voiceConnectStatus; }
@CheckReturnValue private static ResultingStore updateStore( NullnessStore<Nullness> oldStore, ReadableUpdates... updates) { NullnessStore.Builder<Nullness> builder = oldStore.toBuilder(); for (ReadableUpdates update : updates) { for (Map.Entry<AccessPath, Nullness> entry : update.values.entrySet()) { AccessPath key = entry.getKey(); builder.setInformation(key, entry.getValue()); } } NullnessStore<Nullness> newStore = builder.build(); return new ResultingStore(newStore, !newStore.equals(oldStore)); }
@Nonnull @CheckReturnValue public SshDetails setKeyFile(@Nonnull final File file) { if (!file.exists()) { log.warn("Provided key file {} does not exist.", file.getPath()); } this.keyFile = file; return this; }
/** * Results will be sauced if they are SaucedEntites * * @param queryString the raw JPQL query string * @param parameters parameters to be set on the query * @param resultClass expected class of the results of the query * @param offset set to -1 or lower for no offset * @param limit set to -1 or lower for no limit */ //limited and offset results @Nonnull @CheckReturnValue public <T> List<T> selectJpqlQuery(@Nonnull final String queryString, @Nullable final Map<String, Object> parameters, @Nonnull final Class<T> resultClass, final int offset, final int limit) throws DatabaseException { final EntityManager em = this.databaseConnection.getEntityManager(); try { final TypedQuery<T> q = em.createQuery(queryString, resultClass); if (parameters != null) { parameters.forEach(q::setParameter); } if (offset > -1) { q.setFirstResult(offset); } if (limit > -1) { q.setMaxResults(limit); } em.getTransaction().begin(); final List<T> resultList = q.getResultList(); em.getTransaction().commit(); return resultList.stream() .peek(this::setSauce) .collect(Collectors.toList()); } catch (final PersistenceException e) { final String message = String.format("Failed to select JPQL query %s with %s parameters, offset %s, limit %s, on DB %s", queryString, parameters != null ? parameters.size() : "null", offset, limit, this.databaseConnection.getName()); throw new DatabaseException(message, e); } finally { em.close(); } }
/** * Set your own HikariDataSource. By default, the builder populates the HikariDataSource properties with * {@link Builder#getDefaultHikariConfig()} ()} ()}, which can be overriden using this method. */ @Nonnull @CheckReturnValue public Builder setHikariConfig(@Nonnull final HikariConfig hikariConfig) { this.hikariConfig = hikariConfig; return this; }
/** * Add all packages of your application that contain entities that you want to use with this connection. * Example: "com.example.yourorg.yourproject.db.entities" */ @Nonnull @CheckReturnValue public Builder addEntityPackage(@Nonnull final String entityPackage) { this.entityPackages.add(entityPackage); return this; }
/** * Name of the Hikari pool. Should be unique across your application. If you don't set one or set a null one * a default pool name based on the database name will be picked. */ @Nonnull @CheckReturnValue public Builder setPoolName(@Nullable final String poolName) { this.poolName = poolName; return this; }
/** * @return A function to find or create the entity described by the key. * The applied EntityManager needs to have an open transaction, and commit it some time afterwards. */ @Nonnull @CheckReturnValue private <E extends SaucedEntity<I, E>, I extends Serializable> Function<EntityManager, E> findOrCreateFunc(@Nonnull final EntityKey<I, E> entityKey) { return (entityManager) -> { E entity = entityManager.find(entityKey.clazz, entityKey.id); if (entity == null) { entity = this.newInstance(entityKey); } return entity; }; }
/** * @return The result list will be ordered by the order of the provided id list, but may contain null for unknown * entities */ @Nonnull @CheckReturnValue //returns a list of sauced entities that may contain null elements public <E extends SaucedEntity<I, E>, I extends Serializable> List<E> getEntities(@Nonnull final List<I> ids, @Nonnull final Class<E> clazz) throws DatabaseException { return getEntities(ids.stream() .map(id -> EntityKey.of(id, clazz)) .collect(Collectors.toList())); }
/** * @return A list of all elements of the requested entity class */ // NOTE: this method is probably not a great idea to use for giant tables @Nonnull @CheckReturnValue //returns a list of sauced entities public <E extends SaucedEntity<I, E>, I extends Serializable> List<E> loadAll(@Nonnull final Class<E> clazz) throws DatabaseException { final EntityManager em = this.databaseConnection.getEntityManager(); try { final String query = "SELECT c FROM " + clazz.getSimpleName() + " c"; em.getTransaction().begin(); final List<E> queryResult = em .createQuery(query, clazz) .getResultList(); em.getTransaction().commit(); return queryResult .stream() .map(s -> s.setSauce(this)) .collect(Collectors.toList()); } catch (final PersistenceException e) { final String message = String.format("Failed to load all %s entities on DB %s", clazz.getName(), this.databaseConnection.getName()); throw new DatabaseException(message, e); } finally { em.close(); } }
@Nonnull @CheckReturnValue @Override public PsiType apply(@Nonnull TypeName typeName) { return Stream.of(PrimitiveType.values()) .filter(primitiveType -> primitiveType.isSameAs(typeName)) .map(PrimitiveType::psiType) .findFirst() .orElseGet(() -> PsiType.getJavaLangObject(psiManager, GlobalSearchScope.EMPTY_SCOPE)); }
@Nonnull @CheckReturnValue static TypeName box(@Nonnull TypeName typeName) { try { return typeName.box(); } catch (Exception e) { return typeName; } }
@Nonnull @CheckReturnValue static TypeName unbox(@Nonnull TypeName typeName) { try { return typeName.unbox(); } catch (Exception e) { return typeName; } }
@NotNull @CheckReturnValue public String format(@Nonnull String text) { final String name = Extensions.append(NAME, fileType); final PsiFile file = fileFactory.createFileFromText(name, fileType, text); final CodeStyleManager styleManager = CodeStyleManager.getInstance(file.getProject()); styleManager.reformat(file); return file.getText(); }
@Nonnull @CheckReturnValue NewClassCommandAction create( @Nonnull @Assisted("Name") String name, @Nonnull @Assisted("Json") String json, @Nonnull PsiDirectory directory, @Nonnull JavaConverter converter );
/** * Set this to tunnel the database connection through the configured SSH tunnel. Provide a null object to reset. */ @Nonnull @CheckReturnValue public Builder setSshDetails(@Nullable final SshTunnel.SshDetails sshDetails) { this.sshDetails = sshDetails; return this; }
/** * Wrap a transaction into begin and commit */ @Nonnull @CheckReturnValue public static <E> Function<EntityManager, E> wrapTransaction(@Nonnull final Function<EntityManager, E> transaction) { return (entityManager) -> { entityManager.getTransaction().begin(); final E result = transaction.apply(entityManager); entityManager.getTransaction().commit(); return result; }; }
/** * @return The returned entity is not necessarily a persisted one but may be a default constructed one. */ @Nonnull @CheckReturnValue public <E extends SaucedEntity<I, E>, I extends Serializable> E getOrCreate(@Nonnull final EntityKey<I, E> entityKey) throws DatabaseException { final E entity = getEntity(entityKey); //return a fresh object if we didn't find the one we were looking for // no need to set the sauce as either getEntity or newInstance do that already return entity != null ? entity : newInstance(entityKey); }
@Nonnull @CheckReturnValue public JsonBoolean asBoolean() { if (isBoolean()) { return (JsonBoolean) this; } throw new IllegalStateException("This value is not a boolean"); }
@Nonnull @CheckReturnValue public JsonNumber asNumber() { if (isNumber()) { return (JsonNumber) this; } throw new IllegalStateException("This value is not a number"); }
@Nonnull @CheckReturnValue public JsonString asString() { if (isString()) { return (JsonString) this; } throw new IllegalStateException("This value is not a string"); }
@Nonnull @CheckReturnValue public JsonObject asObject() { if (isObject()) { return (JsonObject) this; } throw new IllegalStateException("This value is not an object"); }
@Nonnull @CheckReturnValue public String convert(@Nonnull String packageName, @Nonnull String className, @Nonnull String json) throws IOException { final JsonValue value = configuration.jsonParser().parse(json); final TypeSpec.Builder builder = fromValue(className, value).toBuilder(); // Adding root class specific annotations for (final AnnotationPolicy policy : configuration.annotationPolicies()) { policy.apply(builder); } return configuration.javaBuilder().build(packageName, builder.build()); }
/** * Encrypts the given plaintext. * * @param nonce a 12-byte random nonce * @param plaintext a plaintext message (may be empty) * @param data authenticated data (may be empty) * @return the encrypted message */ @CheckReturnValue public byte[] seal(byte[] nonce, byte[] plaintext, byte[] data) { if (nonce.length != NONCE_SIZE) { throw new IllegalArgumentException("Nonce must be 12 bytes long"); } final byte[] authKey = subKey(0, 1, nonce); final Cipher encAES = newAES(subKey(2, aes128 ? 3 : 5, nonce)); final byte[] tag = hash(encAES, authKey, nonce, plaintext, data); final byte[] output = new byte[plaintext.length + tag.length]; aesCTR(encAES, tag, plaintext, output); System.arraycopy(tag, 0, output, plaintext.length, tag.length); return output; }