code
stringlengths
73
34.1k
label
stringclasses
1 value
protected Device resolveWithPlatform(DeviceType deviceType, DevicePlatform devicePlatform) { return LiteDevice.from(deviceType, devicePlatform); }
java
protected void init() { getMobileUserAgentPrefixes().addAll( Arrays.asList(KNOWN_MOBILE_USER_AGENT_PREFIXES)); getMobileUserAgentKeywords().addAll( Arrays.asList(KNOWN_MOBILE_USER_AGENT_KEYWORDS)); getTabletUserAgentKeywords().addAll( Arrays.asList(KNOWN_TABLET_USER_AGENT_KEYWORDS)); }
java
public static SitePreference getCurrentSitePreference(RequestAttributes attributes) { return (SitePreference) attributes.getAttribute(CURRENT_SITE_PREFERENCE_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); }
java
protected String optionalPort(HttpServletRequest request) { if ("http".equals(request.getScheme()) && request.getServerPort() != 80 || "https".equals(request.getScheme()) && request.getServerPort() != 443) { return ":" + request.getServerPort(); } else { return null; } }
java
@Override protected Map<String, Set<String>> filterQueryParamsByKey(QueryParamsParserContext context, String queryKey) { Map<String, Set<String>> filteredQueryParams = new HashMap<>(); for (String paramName : context.getParameterNames()) { if (paramName.startsWith(queryKey)) { filteredQueryParams.put(param...
java
public static String getProperty(Object bean, String field) { Object property = PropertyUtils.getProperty(bean, field); if (property == null) { return "null"; } return property.toString(); }
java
public FilterSpec addExpression(FilterSpec expr) { if (expressions == null) { expressions = new ArrayList<>(); } expressions.add((FilterSpec) expr); return this; }
java
private static void addMergeInclusions(JpaQueryExecutor<?> executor, QuerySpec querySpec) { ArrayDeque<String> attributePath = new ArrayDeque<>(); Class<?> resourceClass = querySpec.getResourceClass(); addMergeInclusions(attributePath, executor, resourceClass); }
java
public QueryParams buildQueryParams(QueryParamsParserContext context) { try { return queryParamsParser.parse(context); } catch (KatharsisException e) { throw e; } catch (RuntimeException e) { throw new ParametersDeserializationException(e.getMessage(), e); ...
java
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { Object response = responseContext.getEntity(); if (response == null) { return; } // only modify responses which contain a single or a list of Katharsis resources if (isRes...
java
private boolean isResourceResponse(Object response) { boolean singleResource = response.getClass().getAnnotation(JsonApiResource.class) != null; boolean resourceList = ResourceListBase.class.isAssignableFrom(response.getClass()); return singleResource || resourceList; }
java
public SimpleModule build(ResourceRegistry resourceRegistry, boolean isClient) { SimpleModule simpleModule = new SimpleModule(JSON_API_MODULE_NAME, new Version(1, 0, 0, null, null, null)); simpleModule.addSerializer(new ErrorDataSerializer()); simpleModule.addDeserializer(ErrorD...
java
@SuppressWarnings("unchecked") private Set<Resource> lookupRelationshipField(Collection<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, RepositoryMethodParameterProvider parameterProvider, Map<ResourceIdentifier, Resource> resourceMap, Map<ResourceIdentifier, Object> entityMap...
java
public Object[] buildParameters(Object[] firstParameters, Method method, QueryAdapter queryAdapter, Class<? extends Annotation> annotationType) { int parametersLength = method.getParameterTypes().length; if (firstParameters.length > 0 && parametersLength < 1) { ...
java
@Override public <M extends MetaInformation> M as(Class<M> metaClass) { try { return mapper.readerFor(metaClass).readValue(data); } catch (IOException e) { throw new IllegalStateException(e); } }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Serializable parseIdString(String id) { Class idType = getIdField().getType(); return parser.parse(id, idType); }
java
public Response dispatchRequest(JsonPath jsonPath, String method, Map<String, Set<String>> parameters, RepositoryMethodParameterProvider parameterProvider, Document requestBody) { try { BaseController controller = controllerRegistry.getController(jsonPath, method); ResourceInformation resourceInformatio...
java
public static String buildPath(JsonPath jsonPath) { List<String> urlParts = new LinkedList<>(); JsonPath currentJsonPath = jsonPath; String pathPart; do { if (currentJsonPath instanceof RelationshipsPath) { pathPart = RELATIONSHIP_MARK + SEPARATOR + currentJs...
java
public RegistryEntry addEntry(Class<?> resource, RegistryEntry registryEntry) { resources.put(resource, registryEntry); registryEntry.initialize(moduleRegistry); logger.debug("Added resource {} to ResourceRegistry", resource.getName()); return registryEntry; }
java
@Bean public BraveModule braveModule() { String serviceName = "exampleApp"; Endpoint localEndpoint = Endpoint.builder().serviceName(serviceName).build(); InheritableServerClientAndLocalSpanState spanState = new InheritableServerClientAndLocalSpanState(localEndpoint); Brave.Builder builder = new Brave.Builder(s...
java
@Bean public JpaModule jpaModule() { JpaModule module = JpaModule.newServerModule(em, transactionRunner); // directly expose entity module.addRepository(JpaRepositoryConfig.builder(ScheduleEntity.class).build()); // additionally expose entity as a mapped dto module.addRepository(JpaRepositoryConfig.builder...
java
public String getMethodName(Method method) { String name; if (ClassUtils.isBooleanGetter(method)) { name = extractMethodName(method, 2); } else { name = extractMethodName(method, 3); } return name; }
java
public static Method findMethodWith(Class<?> searchClass, Class<? extends Annotation> annotationClass) { Method foundMethod = null; methodFinder: while (searchClass != null && searchClass != Object.class) { for (Method method : searchClass.getDeclaredMethods()) { if (method.isAnnotationPresent(annotationClas...
java
public static <T> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ResourceException(String.format("couldn't create a new instance of %s", clazz)); } }
java
public static JpaModule newServerModule(EntityManagerFactory emFactory, EntityManager em, TransactionRunner transactionRunner) { return new JpaModule(emFactory, em, transactionRunner); }
java
public <T> void addRepository(JpaRepositoryConfig<T> config) { checkNotInitialized(); Class<?> resourceClass = config.getResourceClass(); if (repositoryConfigurationMap.containsKey(resourceClass)) { throw new IllegalArgumentException(resourceClass.getName() + " is already registered"); } repositoryConfigur...
java
private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) { MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup; Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class; MetaDataObject meta = metaLookup.getMeta(resourceClass, me...
java
@Override public void addRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) { List<Project> newProjectList = new LinkedList<>(); Iterable<Project> projectsToAdd = projectRepository.findAll(projectIds, null); for (Project project: projectsToAdd) { newProjectList...
java
@Override public void removeRelations(Task task, Iterable<ObjectId> projectIds, String fieldName) { try { if (PropertyUtils.getProperty(task, fieldName) != null) { Iterable<Project> projects = (Iterable<Project>) PropertyUtils.getProperty(task, fieldName); Iterato...
java
public static ByAttribute attribute(final String name, final String value) { if (name == null) throw new IllegalArgumentException( "Cannot find elements when the attribute name is null"); return new ByAttribute(name, value); }
java
public static ByComposite composite(By.ByTagName b0, By.ByClassName b1) { return new ByComposite(b0, b1); }
java
public FluentSelect deselectByIndex(final int index) { executeAndWrapReThrowIfNeeded(new DeselectByIndex(index), Context.singular(context, "deselectByIndex", null, index), true); return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundException);...
java
public static MethodIdentifier of(final String containingClass, final String methodName, final String signature, final boolean staticMethod) { final String returnType = JavaUtils.getReturnType(signature); final List<String> parameters = JavaUtils.getParameters(signature); return new MethodIdenti...
java
public static MethodIdentifier ofNonStatic(final String containingClass, final String methodName, final String returnType, final String... parameterTypes) { return of(containingClass, methodName, returnType, false, parameterTypes); }
java
public static MethodIdentifier ofStatic(final String containingClass, final String methodName, final String returnType, final String... parameterTypes) { return of(containingClass, methodName, returnType, true, parameterTypes); }
java
public static boolean isAssignableTo(final String leftType, final String rightType) { if (leftType.equals(rightType)) return true; final boolean firstTypeArray = leftType.charAt(0) == '['; if (firstTypeArray ^ rightType.charAt(0) == '[') { return false; } ...
java
public static List<String> getTypeParameters(final String type) { if (type.charAt(0) != 'L') return emptyList(); int lastStart = type.indexOf('<') + 1; final List<String> parameters = new ArrayList<>(); if (lastStart > 0) { int depth = 0; for (int i ...
java
public static List<String> getParameters(final String methodDesc) { // final String[] types = resolveMethodSignature(methodDesc); // return IntStream.range(0, types.length).mapToObj(i -> types[i]).collect(Collectors.toList()); if (methodDesc == null) return emptyList(); final ...
java
public static void debug(final Throwable throwable) { final StringWriter errors = new StringWriter(); throwable.printStackTrace(new PrintWriter(errors)); debugLogger.accept(errors.toString()); }
java
public void analyze() { final Resources resources = new ProjectAnalyzer(analysis.classPaths) .analyze(analysis.projectClassPaths, analysis.projectSourcePaths, analysis.ignoredResources); if (resources.isEmpty()) { LogProvider.info("Empty JAX-RS analysis result, omitting outp...
java
public static TypeRepresentation ofEnum(final TypeIdentifier identifier, final String... enumValues) { return new EnumTypeRepresentation(identifier, new HashSet<>(Arrays.asList(enumValues))); }
java
public static <V, W> Pair<V, W> of(final V left, final W right) { return new Pair<>(left, right); }
java
public void addProjectMethod(final ProjectMethod method) { readWriteLock.writeLock().lock(); try { availableMethods.add(method); } finally { readWriteLock.writeLock().unlock(); } }
java
public Method get(final MethodIdentifier identifier) { // search for available methods readWriteLock.readLock().lock(); try { final Optional<? extends IdentifiableMethod> method = availableMethods.stream().filter(m -> m.matches(identifier)).findAny(); if (method.isPresent...
java
static Set<Integer> findLoadIndexes(final List<Instruction> instructions, final Predicate<LoadInstruction> isLoadIgnored) { return instructions.stream().filter(i -> i.getType() == Instruction.InstructionType.LOAD).map(i -> (LoadInstruction) i) .filter(i -> !isLoadIgnored.test(i)).map(LoadInstruc...
java
static Set<Integer> findReturnsAndThrows(final List<Instruction> instructions) { return find(instruction -> instruction.getType() == Instruction.InstructionType.RETURN || instruction.getType() == Instruction.InstructionType.THROW, instructions); }
java
private static Set<Integer> find(final Predicate<Instruction> predicate, final List<Instruction> instructions) { final Set<Integer> positions = new HashSet<>(); for (int i = 0; i < instructions.size(); i++) { final Instruction instruction = instructions.get(i); if (predicate.tes...
java
public Element simulate(final List<Instruction> instructions) { lock.lock(); try { returnElement = null; return simulateInternal(instructions); } finally { lock.unlock(); } }
java
private void simulate(final Instruction instruction) { switch (instruction.getType()) { case PUSH: final PushInstruction pushInstruction = (PushInstruction) instruction; runtimeStack.push(new Element(pushInstruction.getValueType(), pushInstruction.getValue())); ...
java
private void simulateMethodHandle(final InvokeDynamicInstruction instruction) { final List<Element> arguments = IntStream.range(0, instruction.getDynamicIdentifier().getParameters().size()) .mapToObj(t -> runtimeStack.pop()).collect(Collectors.toList()); Collections.reverse(arguments); ...
java
private void simulateInvoke(final InvokeInstruction instruction) { final List<Element> arguments = new LinkedList<>(); MethodIdentifier identifier = instruction.getIdentifier(); IntStream.range(0, identifier.getParameters().size()).forEach(i -> arguments.add(runtimeStack.pop())); Collec...
java
private void simulateStore(final StoreInstruction instruction) { final int index = instruction.getNumber(); final Element elementToStore = runtimeStack.pop(); if (elementToStore instanceof MethodHandle) mergeMethodHandleStore(index, (MethodHandle) elementToStore); else ...
java
private void mergeElementStore(final int index, final String type, final Element element) { // new element must be created for immutability final String elementType = type.equals(Types.OBJECT) ? determineLeastSpecificType(element.getTypes().toArray(new String[element.getTypes().size()])) : type; ...
java
private void mergeMethodHandleStore(final int index, final MethodHandle methodHandle) { localVariables.merge(index, new MethodHandle(methodHandle), Element::merge); }
java
private void mergePossibleResponse() { // TODO only HttpResponse element? if (!runtimeStack.isEmpty() && runtimeStack.peek().getTypes().contains(Types.RESPONSE)) { mergeReturnElement(runtimeStack.peek()); } }
java
private void simulateSizeChange(final SizeChangingInstruction instruction) { IntStream.range(0, instruction.getNumberOfPops()).forEach(i -> runtimeStack.pop()); IntStream.range(0, instruction.getNumberOfPushes()).forEach(i -> runtimeStack.push(new Element())); }
java
public Resources interpret(final Set<ClassResult> classResults) { resources = new Resources(); resources.setBasePath(PathNormalizer.getApplicationPath(classResults)); javaTypeAnalyzer = new JavaTypeAnalyzer(resources.getTypeRepresentations()); dynamicTypeAnalyzer = new DynamicTypeAnalyz...
java
private void interpretClassResult(final ClassResult classResult) { classResult.getMethods().forEach(m -> interpretMethodResult(m, classResult)); }
java
private void interpretMethodResult(final MethodResult methodResult, final ClassResult classResult) { if (methodResult.getSubResource() != null) { interpretClassResult(methodResult.getSubResource()); return; } // determine resource of the method final String path ...
java
private ResourceMethod interpretResourceMethod(final MethodResult methodResult, final ClassResult classResult) { final MethodComment methodDoc = methodResult.getMethodDoc(); final String description = methodDoc != null ? methodDoc.getComment() : null; final ResourceMethod resourceMethod = new R...
java
private void addMediaTypes(final MethodResult methodResult, final ClassResult classResult, final ResourceMethod resourceMethod) { // accept media types -> inherit resourceMethod.getRequestMediaTypes().addAll(methodResult.getRequestMediaTypes()); if (resourceMethod.getRequestMediaTypes().isEmpty(...
java
void buildPackagePrefix(final String className) { // TODO test final int lastPackageSeparator = className.lastIndexOf('/'); final String packageName = className.substring(0, lastPackageSeparator == -1 ? className.length() : lastPackageSeparator); final String[] splitPackage = packageName...
java
Set<ProjectMethod> findProjectMethods(final List<Instruction> instructions) { final Set<ProjectMethod> projectMethods = new HashSet<>(); addProjectMethods(instructions, projectMethods); return projectMethods; }
java
private boolean isProjectMethod(final InvokeInstruction instruction) { final MethodIdentifier identifier = instruction.getIdentifier(); // check if method is in own package return identifier.getContainingClass().startsWith(projectPackagePrefix); }
java
private static boolean isStackCleared(final Instruction instruction) { return instruction.getType() == Instruction.InstructionType.RETURN || instruction.getType() == Instruction.InstructionType.THROW; }
java
private int findBacktrackPosition(final int position) { int currentPosition = position; // check against stack size after the instruction was executed while (stackSizes.get(currentPosition).getRight() > 0) { currentPosition++; } return currentPosition; }
java
private boolean equalsSimpleTypeNames(MethodIdentifier identifier, MethodResult methodResult) { MethodIdentifier originalIdentifier = methodResult.getOriginalMethodSignature(); return originalIdentifier.getMethodName().equals(identifier.getMethodName()) && matchesTypeBestEffort(original...
java
static String normalizeCollection(final String type) { if (isAssignableTo(type, Types.COLLECTION)) { if (!getTypeParameters(type).isEmpty()) { return getTypeParameters(type).get(0); } return Types.OBJECT; } return type; }
java
public List<Instruction> reduceInstructions(final List<Instruction> instructions) { lock.lock(); try { this.instructions = instructions; stackSizeSimulator.buildStackSizes(instructions); return reduceInstructionsInternal(instructions); } finally { ...
java
private List<Instruction> reduceInstructionsInternal(final List<Instruction> instructions) { final List<Instruction> visitedInstructions = new LinkedList<>(); final Set<Integer> visitedInstructionPositions = new HashSet<>(); final Set<Integer> handledLoadIndexes = new HashSet<>(); final ...
java
private static boolean isLoadIgnored(final LoadInstruction instruction) { return Stream.of(VARIABLE_NAMES_TO_IGNORE).anyMatch(instruction.getName()::equals); }
java
public Resources analyze(Set<Path> projectClassPaths, Set<Path> projectSourcePaths, Set<String> ignoredResources) { lock.lock(); try { projectClassPaths.forEach(this::addProjectPath); // analyze relevant classes final JobRegistry jobRegistry = JobRegistry.getInstance...
java
private void addToClassPool(final Path location) { if (!location.toFile().exists()) throw new IllegalArgumentException("The location '" + location + "' does not exist!"); try { ContextClassReader.addClassPath(location.toUri().toURL()); } catch (Exception e) { ...
java
private void addProjectPath(final Path path) { addToClassPool(path); if (path.toFile().isFile() && path.toString().endsWith(".jar")) { addJarClasses(path); } else if (path.toFile().isDirectory()) { addDirectoryClasses(path, Paths.get("")); } else { th...
java
private void addJarClasses(final Path location) { try (final JarFile jarFile = new JarFile(location.toFile())) { final Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); fina...
java
private void addDirectoryClasses(final Path location, final Path subPath) { for (final File file : location.toFile().listFiles()) { if (file.isDirectory()) addDirectoryClasses(location.resolve(file.getName()), subPath.resolve(file.getName())); else if (file.isFile() && fi...
java
private static String toQualifiedClassName(final String fileName) { final String replacedSeparators = fileName.replace(File.separatorChar, '.'); return replacedSeparators.substring(0, replacedSeparators.length() - ".class".length()); }
java
static String getApplicationPath(final Set<ClassResult> classResults) { return classResults.stream().map(ClassResult::getApplicationPath).filter(Objects::nonNull) .map(PathNormalizer::normalize).findAny().orElse(""); }
java
private static List<String> determinePaths(final MethodResult methodResult) { final List<String> paths = new LinkedList<>(); MethodResult currentMethod = methodResult; while (true) { addNonBlank(currentMethod.getPath(), paths); final ClassResult parentClass = currentMeth...
java
private static void addNonBlank(final String string, final List<String> strings) { if (!StringUtils.isBlank(string) && !"/".equals(string)) strings.add(string); }
java
private static String normalize(final String path) { final StringBuilder builder = new StringBuilder(path); int index = 0; int colonIndex = -1; char current = 0; char last; while ((index > -1) && (index < builder.length())) { last = current; curr...
java
public Element simulate(final List<Element> arguments, final List<Instruction> instructions, final MethodIdentifier identifier) { // prevent infinite loops on analysing recursion if (EXECUTED_PATH_METHODS.contains(identifier)) return new Element(); lock.lock(); EXECUTED_PATH...
java
private void injectArguments(final List<Element> arguments, final MethodIdentifier identifier) { final boolean staticMethod = identifier.isStaticMethod(); final int startIndex = staticMethod ? 0 : 1; final int endIndex = staticMethod ? arguments.size() - 1 : arguments.size(); IntStream....
java
private static SwaggerType toSwaggerType(final String type) { if (INTEGER_TYPES.contains(type)) return SwaggerType.INTEGER; if (DOUBLE_TYPES.contains(type)) return SwaggerType.NUMBER; if (BOOLEAN.equals(type) || PRIMITIVE_BOOLEAN.equals(type)) return Swagger...
java
public Element merge(final Element element) { types.addAll(element.types); possibleValues.addAll(element.possibleValues); return this; }
java
public void addMethod(final String resource, final ResourceMethod method) { resources.putIfAbsent(resource, new HashSet<>()); resources.get(resource).add(method); }
java
public Set<ResourceMethod> getMethods(final String resource) { return Collections.unmodifiableSet(resources.get(resource)); }
java
public void consolidateMultiplePaths() { Map<String, Set<ResourceMethod>> oldResources = resources; resources = new HashMap<>(); oldResources.keySet().forEach(s -> consolidateMultipleMethodsForSamePath(s, oldResources.get(s))); }
java
public Changelog getChangelog(final boolean useIntegrationIfConfigured) throws GitChangelogRepositoryException { try (GitRepo gitRepo = new GitRepo(new File(this.settings.getFromRepo()))) { return getChangelog(gitRepo, useIntegrationIfConfigured); } catch (final IOException e) { throw new GitC...
java
public void toFile(final File file) throws GitChangelogRepositoryException, IOException { createParentDirs(file); write(render().getBytes("UTF-8"), file); }
java
public void toMediaWiki( final String username, final String password, final String url, final String title) throws GitChangelogRepositoryException, GitChangelogIntegrationException { new MediaWikiClient(url, title, render()) // .withUser(username, password) // .createMediaWikiPage(); ...
java
public Slot insertSlotAt(final int position, @NonNull final Slot slot) { if (position < 0 || size < position) { throw new IndexOutOfBoundsException("New slot position should be inside the slots list. Or on the tail (position = size)"); } final Slot toInsert = new Slot(slot); ...
java
public String uri(String name) { try { return String.format("otpauth://totp/%s?secret=%s", URLEncoder.encode(name, "UTF-8"), secret); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
java
public boolean verify(String otp) { long code = Long.parseLong(otp); long currentInterval = clock.getCurrentInterval(); int pastResponse = Math.max(DELAY_WINDOW, 0); for (int i = pastResponse; i >= 0; --i) { int candidate = generate(this.secret, currentInterval - i); ...
java
private void reattach(HeapElement el) { if (el.shift()) { queue.add(el); } else if (el.inclusion) { /* * If we have no live inclusions, then the rest are exclusions which * we can safely discard. */ if (--nInclusionsRemaining == 0) { queue.clear(); } } }
java
boolean shift() { if (!it.hasNext()) { return false; } head = it.next(); comparable = DateValueComparison.comparable(head); return true; }
java
int[] toIntArray() { int[] out = new int[size()]; int a = 0, b = out.length; for (int i = -1; (i = ints.nextSetBit(i + 1)) >= 0;) { int n = decode(i); if (n < 0) { out[a++] = n; } else { out[--b] = n; } } //if it contains -3, -1, 0, 1, 2, 4 //then out will be -1, -3, 4, 2, 1, 0 rever...
java
private static void reverse(int[] array, int start, int end) { for (int i = start, j = end; i < --j; ++i) { int t = array[i]; array[i] = array[j]; array[j] = t; } }
java
public void addTimezonedDate(String tzid, ICalProperty property, ICalDate date) { timezonedDates.put(tzid, new TimezonedDate(date, property)); }
java
public void setValue(Date value, boolean hasTime) { setValue((value == null) ? null : new ICalDate(value, hasTime)); }
java