code
stringlengths
73
34.1k
label
stringclasses
1 value
public long[] readLongArray(final int items, final JBBPByteOrder byteOrder) throws IOException { int pos = 0; if (items < 0) { long[] buffer = new long[INITIAL_ARRAY_BUFFER_SIZE]; // till end while (hasAvailableData()) { final long next = readLong(byteOrder); if (buffer.length ...
java
public double[] readDoubleArray(final int items, final JBBPByteOrder byteOrder) throws IOException { int pos = 0; if (items < 0) { double[] buffer = new double[INITIAL_ARRAY_BUFFER_SIZE]; // till end while (hasAvailableData()) { final long next = readLong(byteOrder); if (buffer...
java
public int readUnsignedShort(final JBBPByteOrder byteOrder) throws IOException { final int b0 = this.read(); if (b0 < 0) { throw new EOFException(); } final int b1 = this.read(); if (b1 < 0) { throw new EOFException(); } return byteOrder == JBBPByteOrder.BIG_ENDIAN ? (b0 << 8) | ...
java
public int readInt(final JBBPByteOrder byteOrder) throws IOException { if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { return (readUnsignedShort(byteOrder) << 16) | readUnsignedShort(byteOrder); } else { return readUnsignedShort(byteOrder) | (readUnsignedShort(byteOrder) << 16); } }
java
public float readFloat(final JBBPByteOrder byteOrder) throws IOException { final int value; if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { value = (readUnsignedShort(byteOrder) << 16) | readUnsignedShort(byteOrder); } else { value = readUnsignedShort(byteOrder) | (readUnsignedShort(byteOrder) << 1...
java
public long readLong(final JBBPByteOrder byteOrder) throws IOException { if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { return (((long) readInt(byteOrder) & 0xFFFFFFFFL) << 32) | ((long) readInt(byteOrder) & 0xFFFFFFFFL); } else { return ((long) readInt(byteOrder) & 0xFFFFFFFFL) | (((long) readInt(byt...
java
public double readDouble(final JBBPByteOrder byteOrder) throws IOException { final long value; if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { value = (((long) readInt(byteOrder) & 0xFFFFFFFFL) << 32) | ((long) readInt(byteOrder) & 0xFFFFFFFFL); } else { value = ((long) readInt(byteOrder) & 0xFFFFF...
java
public byte readBitField(final JBBPBitNumber numOfBitsToRead) throws IOException { final int value = this.readBits(numOfBitsToRead); if (value < 0) { throw new EOFException("Can't read bits from stream [" + numOfBitsToRead + ']'); } return (byte) value; }
java
public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); if (result >= 0) { this.byteCounter++; ...
java
public void align(final long alignByteNumber) throws IOException { this.alignByte(); if (alignByteNumber > 0) { long padding = (alignByteNumber - (this.byteCounter % alignByteNumber)) % alignByteNumber; while (padding > 0) { final int skippedByte = this.read(); if (skippedByte < 0)...
java
private int readByteFromStream() throws IOException { int result = this.in.read(); if (result >= 0 && this.msb0) { result = JBBPUtils.reverseBitsInByte((byte) result) & 0xFF; } return result; }
java
private int loadNextByteInBuffer() throws IOException { final int value = this.readByteFromStream(); if (value < 0) { return value; } this.bitBuffer = value; this.bitsInBuffer = 8; return value; }
java
public String readString(final JBBPByteOrder byteOrder) throws IOException { final int prefix = this.readByte(); final int len; if (prefix == 0) { len = 0; } else if (prefix == 0xFF) { len = -1; } else if (prefix < 0x80) { len = prefix; } else if ((prefix & 0xF0) == 0x80) { ...
java
public String[] readStringArray(final int items, final JBBPByteOrder byteOrder) throws IOException { int pos = 0; if (items < 0) { String[] buffer = new String[INITIAL_ARRAY_BUFFER_SIZE]; // till end while (hasAvailableData()) { final String next = readString(byteOrder); if (bu...
java
public JBBPNamedFieldInfo findFieldForPath(final String fieldPath) { JBBPNamedFieldInfo result = null; for (final JBBPNamedFieldInfo f : this.namedFieldData) { if (f.getFieldPath().equals(fieldPath)) { result = f; break; } } return result; }
java
public int findFieldOffsetForPath(final String fieldPath) { for (final JBBPNamedFieldInfo f : this.namedFieldData) { if (f.getFieldPath().equals(fieldPath)) { return f.getFieldOffsetInCompiledBlock(); } } throw new JBBPIllegalArgumentException("Unknown field path [" + fieldPath + ']'); ...
java
@Deprecated public void sendEvent(String eventId, String ymlPrivileges) { SystemEvent event = buildSystemEvent(eventId, ymlPrivileges); serializeEvent(event).ifPresent(this::send); }
java
public void sendEvent(String eventId, Set<Privilege> privileges) { // TODO do not use yml in json events... String ymlPrivileges = PrivilegeMapper.privilegesToYml(privileges); SystemEvent event = buildSystemEvent(eventId, ymlPrivileges); serializeEvent(event).ifPresent(this::send); ...
java
private void send(String content) { if (!StringUtils.isBlank(content)) { log.info("Sending system queue event to kafka-topic = '{}', data = '{}'", topicName, content); template.send(topicName, content); } }
java
public static void createSchema(DataSource dataSource, String name) { try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate(String.format(Constants.DDL_CREATE_SCHEMA, name)); } catch (SQLException e...
java
@JsonIgnore @SuppressWarnings("unchecked") public Map<String, Object> getDataMap() { if (data instanceof Map) { return (Map<String, Object>) data; } return Collections.emptyMap(); }
java
public String getMessage(String code, Map<String, String> substitutes, boolean firstFindInMessageBundle, String defaultMessage) { Locale locale = authContextHolder.getContext().getDetailsValue(LANGUAGE) ...
java
public String getMessage(String code, Map<String, String> substitutes) { return getMessage(code, substitutes, true, null); }
java
public Map<String, Role> getRoles(String tenant) { if (!roles.containsKey(tenant)) { return new HashMap<>(); } return roles.get(tenant); }
java
public static String printExceptionWithStackInfo(Throwable throwable) { StringBuilder out = new StringBuilder(); printExceptionWithStackInfo(throwable, out); return out.toString(); }
java
@SafeVarargs public static <T> String joinUrlPaths(final T[] arr, final T... arr2) { try { T[] url = ArrayUtils.addAll(arr, arr2); String res = StringUtils.join(url); return (res == null) ? "" : res; } catch (IndexOutOfBoundsException | IllegalArgumentException | ...
java
public static String getCallMethod(JoinPoint joinPoint) { if (joinPoint != null && joinPoint.getSignature() != null) { Class<?> declaringType = joinPoint.getSignature().getDeclaringType(); String className = (declaringType != null) ? declaringType.getSimpleName() : PRINT_QUESTION; ...
java
public static String printInputParams(JoinPoint joinPoint, String... includeParamNames) { try { if (joinPoint == null) { return "joinPoint is null"; } Signature signature = joinPoint.getSignature(); if (!(signature instanceof MethodSignature)) { ...
java
public static String printCollectionAware(final Object object, final boolean printBody) { if (!printBody) { return PRINT_HIDDEN; } if (object == null) { return String.valueOf(object); } Class<?> clazz = object.getClass(); if (!Collection.class.i...
java
private static String replaceOperators(String spel) { if (StringUtils.isBlank(spel)) { return spel; } return spel.replaceAll("==", " = ") .replaceAll("&&", " and ") .replaceAll("\\|\\|", " or "); }
java
public static void checkSecurity() { SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(new ManagementPermission(PERMISSION_NAME_CONTROL)); } }
java
protected final <T> String getString(final IKey<T> key) { final Object value = config.get(key.key()); return String.valueOf(value != null ? value : key.getDefaultValue()); }
java
@SuppressWarnings("unchecked") @Override public final <T> T get(final IKey<T> key) { T value = (T) config.get(key.key()); return value != null ? value : key.getDefaultValue(); }
java
protected static <T> IKey<T> newKey(final String key, final T defaultValue) { return new Key<T>(key, defaultValue); }
java
@Override public Resource getResource(String location) { String cfgPath = StringUtils.removeStart(location, XM_MS_CONFIG_URL_PREFIX); return scriptResources.getOrDefault(cfgPath, XmLepScriptResource.nonExist()); }
java
@Override public void updateConfigurations(String commit, Collection<String> paths) { Map<String, Configuration> configurationsMap = getConfigurationMap(commit, paths); paths.forEach(path -> notifyUpdated(configurationsMap .getOrDefault(path, new Configuration(path, null)))); }
java
public static String generateRid() { byte[] encode = Base64.getEncoder().encode(DigestUtils.sha256(UUID.randomUUID().toString())); try { String rid = new String(encode, StandardCharsets.UTF_8.name()); rid = StringUtils.replaceChars(rid, "+/=", ""); return StringUtils....
java
@Override public void onBeforeExecutionEvent(BeforeExecutionEvent event) { LepManager manager = event.getSource(); ScopedContext threadContext = manager.getContext(ContextScopes.THREAD); if (threadContext == null) { throw new IllegalStateException("LEP manager thread context does...
java
@SuppressWarnings("squid:S00112") //suppress throwable warning public Object onMethodInvoke(Class<?> targetType, Object target, Method method, Object[] args) throws Throwable { LepService typeLepService = targetType.getAnnotation(LepService.class); Objects.requireNonNull(typeLepService, "No " + LepS...
java
@Retryable(maxAttemptsExpression = "${application.retry.max-attempts}", backoff = @Backoff(delayExpression = "${application.retry.delay}", multiplierExpression = "${application.retry.multiplier}")) public void consumeEvent(ConsumerRecord<String, String> message) { MdcUtils.putRid(); ...
java
static Object executeScript(UrlLepResourceKey scriptResourceKey, ProceedingLep proceedingLep, // can be null LepMethod method, LepManagerService managerService, Supplier<GroovyScriptRunner> re...
java
private static Binding buildBinding(UrlLepResourceKey scriptResourceKey, LepManagerService managerService, LepMethod method, ProceedingLep proceedingLep, LepMet...
java
@Override protected Map<String, Object> decode(String token) { try { //check if our public key and thus SignatureVerifier have expired long ttl = oAuth2Properties.getSignatureVerification().getTtl(); if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl)...
java
private boolean tryCreateSignatureVerifier() { long t = System.currentTimeMillis(); if (t - lastKeyFetchTimestamp < oAuth2Properties.getSignatureVerification().getPublicKeyRefreshRateLimit()) { return false; } try { SignatureVerifier verifier = signatureVerifierCl...
java
public static void install(Application app, IWicketJquerySelectorsSettings settings) { final IWicketJquerySelectorsSettings existingSettings = settings(app); if (existingSettings == null) { if (settings == null) { settings = new WicketJquerySelectorsSettings(); }...
java
public String privilegesToYml(Collection<Privilege> privileges) { try { Map<String, Set<Privilege>> map = new TreeMap<>(); privileges.forEach(privilege -> { map.putIfAbsent(privilege.getMsName(), new TreeSet<>()); map.get(privilege.getMsName()).add(privile...
java
public String privilegesMapToYml(Map<String, Collection<Privilege>> privileges) { try { return mapper.writeValueAsString(privileges); } catch (Exception e) { log.error("Failed to create privileges YML file from map, error: {}", e.getMessage(), e); } return null; ...
java
public Map<String, Set<Privilege>> ymlToPrivileges(String yml) { try { Map<String, Set<Privilege>> map = mapper.readValue(yml, new TypeReference<TreeMap<String, TreeSet<Privilege>>>() { }); map.forEach((msName, privileges) -> privileges.forEach(privilege -...
java
public static <T> T fromJson(final String json, final JavaType type) { try { return createObjectMapper().readValue(json, type); } catch (Exception e) { throw new ParseException(e); } }
java
public static JsonNode toJson(final Object data) { if (data == null) { return newObject(); } try { return createObjectMapper().valueToTree(data); } catch (Exception e) { throw new ParseException(e); } }
java
public static String stringify(final JsonNode json) { try { return json != null ? createObjectMapper().writeValueAsString(json) : "{}"; } catch (JsonProcessingException jpx) { throw new RuntimeException("A problem occurred while stringifying a JsonNode: " + jpx.getMessage(), jpx)...
java
public static boolean isValid(final String json) { if (Strings.isEmpty(json)) { return false; } try { return parse(json) != null; } catch (ParseException e) { return false; } }
java
public static JsonNode parse(final String jsonString) { if (Strings.isEmpty(jsonString)) { return newObject(); } try { return createObjectMapper().readValue(jsonString, JsonNode.class); } catch (Throwable e) { throw new ParseException(String.format("c...
java
public static void validateScriptsCombination(Set<XmLepResourceSubType> scriptTypes, LepMethod lepMethod, UrlLepResourceKey compositeResourceKey) { byte mask = getCombinationMask(scriptTypes, lepMethod, composite...
java
private static byte getCombinationMask(Set<XmLepResourceSubType> scriptTypes, LepMethod lepMethod, UrlLepResourceKey compositeResourceKey) { byte combinationMask = 0; for (XmLepResourceSubType scriptType : scriptTypes)...
java
public String createEventJson(HttpServletRequest request, HttpServletResponse response, String tenant, String userLogin, String userKey) { try { String requestBody ...
java
@Async public void send(String topic, String content) { try { if (!StringUtils.isBlank(content)) { log.debug("Sending kafka event with data {} to topic {}", content, topic); template.send(topic, content); } } catch (Exception e) { l...
java
public static String join(final Iterable<?> elements, final char separator) { return Joiner.on(separator).skipNulls().join(elements); }
java
protected void registerTenantInterceptorWithIgnorePathPattern( InterceptorRegistry registry, HandlerInterceptor interceptor) { InterceptorRegistration tenantInterceptorRegistration = registry.addInterceptor(interceptor); tenantInterceptorRegistration.addPathPatterns("/**"); ...
java
public static Optional<LoggingAspectConfig> getConfigAnnotation(JoinPoint joinPoint) { Optional<Method> method = getCallingMethod(joinPoint); Optional<LoggingAspectConfig> result = method .map(m -> AnnotationUtils.findAnnotation(m, LoggingAspectConfig.class)); if (!result.isPresen...
java
public String rolesToYml(Collection<Role> roles) { try { Map<String, Role> map = new TreeMap<>(); roles.forEach(role -> map.put(role.getKey(), role)); return mapper.writeValueAsString(map); } catch (Exception e) { log.error("Failed to create roles YML file...
java
public Map<String, Role> ymlToRoles(String yml) { try { Map<String, Role> map = mapper .readValue(yml, new TypeReference<TreeMap<String, Role>>() { }); map.forEach((roleKey, role) -> role.setKey(roleKey)); return map; } catch (Exception...
java
public boolean hasPermission(Authentication authentication, Object privilege) { return checkRole(authentication, privilege, true) || checkPermission(authentication, null, privilege, false, true); }
java
public boolean hasPermission(Authentication authentication, Object resource, Object privilege) { boolean logPermission = isLogPermission(resource); return checkRole(authentication, privilege, logPermission) || checkPermission(...
java
@SuppressWarnings("unchecked") public boolean hasPermission(Authentication authentication, Serializable resource, String resourceType, Object privilege) { boolean logPermission = isLogPermission(resource); ...
java
public String createCondition(Authentication authentication, Object privilegeKey, SpelTranslator translator) { if (!hasPermission(authentication, privilegeKey)) { throw new AccessDeniedException("Access is denied"); } String roleKey = getRoleKey(authentication); Permission ...
java
protected Module addSerializer(SimpleModule module) { module.addSerializer(ConfigModel.class, Holder.CONFIG_MODEL_SERIALIZER); module.addSerializer(Config.class, Holder.CONFIG_SERIALIZER); module.addSerializer(Json.RawValue.class, Holder.RAW_VALUE_SERIALIZER); return module; }
java
protected ObjectMapper configure(ObjectMapper mapper) { mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); return mapper; }
java
public String permissionsToYml(Collection<Permission> permissions) { try { Map<String, Map<String, Set<Permission>>> map = new TreeMap<>(); permissions.forEach(permission -> { map.putIfAbsent(permission.getMsName(), new TreeMap<>()); map.get(permission.get...
java
public Map<String, Permission> ymlToPermissions(String yml, String msName) { Map<String, Permission> result = new TreeMap<>(); try { Map<String, Map<String, Set<Permission>>> map = mapper .readValue(yml, new TypeReference<TreeMap<String, TreeMap<String, TreeSet<Permission>>>>...
java
public <T> List<T> findAll(Class<T> entityClass, String privilegeKey) { return findAll(null, entityClass, privilegeKey).getContent(); }
java
public <T> Page<T> findAll(Pageable pageable, Class<T> entityClass, String privilegeKey) { String selectSql = format(SELECT_ALL_SQL, entityClass.getSimpleName()); String countSql = format(COUNT_ALL_SQL, entityClass.getSimpleName()); String permittedCondition = createPermissionCondition(privileg...
java
public <T> Page<T> findByCondition(String whereCondition, Map<String, Object> conditionParams, Collection<String> embed, Pageable pageable, Class<T> entityClass...
java
public CombinableConfig combine(Config... fallbackConfigs) { CombinableConfig newConfig = this; for (Config fallback : fallbackConfigs) { newConfig = new ConfigWithFallback(newConfig, fallback); } return newConfig; }
java
@PostConstruct public void init() { log.debug("Registering JVM gauges"); metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet()); metricRegistry.register(PROP_METRIC_REG_JVM_...
java
@Override public SignatureVerifier getSignatureVerifier() throws Exception { try { HttpEntity<Void> request = new HttpEntity<>(new HttpHeaders()); String content = restTemplate.exchange(getPublicKeyEndpoint(), HttpMethod.GET, request, String.class).getBody(); ...
java
private String getPublicKeyEndpoint() { String tokenEndpointUrl = oauth2Properties.getSignatureVerification().getPublicKeyEndpointUri(); if (tokenEndpointUrl == null) { throw new InvalidClientException("no token endpoint configured in application properties"); } return tokenE...
java
public String logicalCollectionTableName(String tableName, String ownerEntityTable, String associatedEntityTable, String propertyName) { if (tableName == null) { // use of a stringbuilder to workaround a JDK bug return new StringBuilder(ownerEntityTable).append("_") .append(associatedEnt...
java
protected final void addMessage(String msgKey, Object... args) { getFlash().addMessageNow(getTextInternal(msgKey, args)); }
java
protected final void addError(String msgKey, Object... args) { getFlash().addErrorNow(getTextInternal(msgKey, args)); }
java
protected final void addFlashError(String msgKey, Object... args) { getFlash().addError(getTextInternal(msgKey, args)); }
java
protected final void addFlashMessage(String msgKey, Object... args) { getFlash().addMessage(getTextInternal(msgKey, args)); }
java
private void addGetterAndSetter(JDefinedClass traversingVisitor, JFieldVar field) { String propName = Character.toUpperCase(field.name().charAt(0)) + field.name().substring(1); traversingVisitor.method(JMod.PUBLIC, field.type(), "get" + propName).body()._return(field); JMethod setVisitor = trave...
java
private String buildServletPath() { String uri = servletPath; if (uri == null && null != requestURI) { uri = requestURI; if (!contextPath.equals("/")) uri = uri.substring(contextPath.length()); } return (null == uri) ? "" : uri; }
java
public String buildRequestUrl() { StringBuilder sb = new StringBuilder(); sb.append(buildServletPath()); if (null != pathInfo) { sb.append(pathInfo); } if (null != queryString) { sb.append('?').append(queryString); } return sb.toString(); }
java
public String buildUrl() { StringBuilder sb = new StringBuilder(); boolean includePort = true; if (null != scheme) { sb.append(scheme).append("://"); includePort = (port != (scheme.equals("http") ? 80 : 443)); } if (null != serverName) { sb.append(serverName); if (includePort...
java
public Map.Entry<K, V> getEntry(Object key) { EntryImpl<K, V> entry = _entries[keyHash(key) & _mask]; while (entry != null) { if (key.equals(entry._key)) { return entry; } entry = entry._next; } return null; }
java
private void addEntry(K key, V value) { EntryImpl<K, V> entry = _poolFirst; if (entry != null) { _poolFirst = entry._after; entry._after = null; } else { // Pool empty. entry = new EntryImpl<K, V>(); } // Setup entry paramters. entry._key = key; entry._value = value; i...
java
private void removeEntry(EntryImpl<K, V> entry) { // Removes from bucket. EntryImpl<K, V> previous = entry._previous; EntryImpl<K, V> next = entry._next; if (previous != null) { previous._next = next; entry._previous = null; } else { // First in bucket. _entries[entry._index] = ne...
java
@SuppressWarnings("unchecked") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { int capacity = stream.readInt(); initialize(capacity); int size = stream.readInt(); for (int i = 0; i < size; i++) { addEntry((K) stream.readObject(), (V) stream.readObje...
java
private void writeObject(ObjectOutputStream stream) throws IOException { stream.writeInt(_capacity); stream.writeInt(_size); int count = 0; EntryImpl<K, V> entry = _mapFirst; while (entry != null) { stream.writeObject(entry._key); stream.writeObject(entry._value); count++; en...
java
static Set<JClass> discoverDirectClasses(Outline outline, Set<ClassOutline> classes) throws IllegalAccessException { Set<String> directClassNames = new LinkedHashSet<>(); for(ClassOutline classOutline : classes) { // for each field, if it's a bean, then visit it List<FieldOutlin...
java
private static void parseXmlAnnotations(Outline outline, FieldOutline field, Set<String> directClasses) throws IllegalAccessException { if (field instanceof UntypedListField) { JFieldVar jfv = (JFieldVar) FieldHack.listField.get(field); for(JAnnotationUse jau : jfv.annotations()) { ...
java
private static void handleXmlElement(Outline outline, Set<String> directClasses, JAnnotationValue type) { StringWriter sw = new StringWriter(); JFormatter jf = new JFormatter(new PrintWriter(sw)); type.generate(jf); String s = sw.toString(); s = s.substring(0, s.length()-".class"...
java
static JMethod getter(FieldOutline fieldOutline) { final JDefinedClass theClass = fieldOutline.parent().implClass; final String publicName = fieldOutline.getPropertyInfo().getName(true); final JMethod getgetter = theClass.getMethod("get" + publicName, NONE); if (getgetter != null) { ...
java
static boolean isJAXBElement(JType type) { //noinspection RedundantIfStatement if (type.fullName().startsWith(JAXBElement.class.getName())) { return true; } return false; }
java
static List<JClass> allConcreteClasses(Set<ClassOutline> classes) { return allConcreteClasses(classes, Collections.emptySet()); }
java
static List<JClass> allConcreteClasses(Set<ClassOutline> classes, Set<JClass> directClasses) { List<JClass> results = new ArrayList<>(); classes.stream() .filter(classOutline -> !classOutline.target.isAbstract()) .forEach(classOutline -> { JClass implClass = c...
java
private Set<ClassOutline> sortClasses(Outline outline) { Set<ClassOutline> sorted = new TreeSet<>((aOne, aTwo) -> { String one = aOne.implClass.fullName(); String two = aTwo.implClass.fullName(); return one.compareTo(two); }); sorted.addAll(outline.getClasses(...
java
private <T extends Annotation> T findAnnotation(Class<?> cls, Class<T> annotationClass, String name) { Class<?> curr = cls; T ann = null; while (ann == null && curr != null && !curr.equals(Object.class)) { ann = findAnnotationLocal(curr, annotationClass, name); curr = curr.getSuperclass(); }...
java