code
stringlengths
73
34.1k
label
stringclasses
1 value
private Method getPrivateMethod(VelMethod velMethod) throws Exception { Field methodField = velMethod.getClass().getDeclaredField("method"); boolean isAccessible = methodField.isAccessible(); try { methodField.setAccessible(true); return (Method) methodField.get(velMe...
java
private Object[] convertArguments(Object obj, String methodName, Object[] args) { for (Method method : obj.getClass().getMethods()) { if (method.getName().equalsIgnoreCase(methodName) && (method.getGenericParameterTypes().length == args.length || method.isVarArgs())) { ...
java
private void initializeExtension(InstalledExtension installedExtension, String namespaceToLoad, Map<String, Set<InstalledExtension>> initializedExtensions) throws ExtensionException { if (installedExtension.getNamespaces() != null) { if (namespaceToLoad == null) { for (St...
java
private void initializeExtensionInNamespace(InstalledExtension installedExtension, String namespace, Map<String, Set<InstalledExtension>> initializedExtensions) throws ExtensionException { // Check if the extension can be available from this namespace if (!installedExtension.isValid(namespac...
java
private void logWarning(String deprecationType, Object object, String methodName, Info info) { this.log.warn(String.format("Deprecated usage of %s [%s] in %s@%d,%d", deprecationType, object.getClass() .getCanonicalName() + "." + methodName, info.getTemplateName(), info.getLine(), info.getColumn(...
java
protected void extractBeanDescriptor() { Object defaultInstance = null; try { defaultInstance = getBeanClass().newInstance(); } catch (Exception e) { LOGGER.debug("Failed to create a new default instance for class " + this.beanClass + ". The BeanD...
java
protected <T extends Annotation> T extractPropertyAnnotation(Method writeMethod, Method readMethod, Class<T> annotationClass) { T parameterDescription = writeMethod.getAnnotation(annotationClass); if (parameterDescription == null && readMethod != null) { parameterDescription...
java
public int size(boolean recurse) { if (!recurse) { return this.children != null ? this.children.size() : 0; } int size = 0; for (LogEvent logEvent : this) { ++size; if (logEvent instanceof LogTreeNode) { size += ((LogTreeNode) lo...
java
public static CertificateProvider getCertificateProvider(ComponentManager manager, Store store, CertificateProvider certificateProvider) throws GeneralSecurityException { CertificateProvider provider = newCertificateProvider(manager, store); if (certificateProvider == null) { re...
java
public static void addCertificatesToVerifiedData(Store store, BcCMSSignedDataVerified verifiedData, CertificateFactory certFactory) { for (X509CertificateHolder cert : getCertificates(store)) { verifiedData.addCertificate(BcUtils.convertCertificate(certFactory, cert)); } }
java
public static CertificateProvider getCertificateProvider(ComponentManager manager, Collection<CertifiedPublicKey> certificates) throws GeneralSecurityException { if (certificates == null || certificates.isEmpty()) { return null; } Collection<X509CertificateHolder> certs ...
java
private static CertificateProvider newCertificateProvider(ComponentManager manager, Store store) throws GeneralSecurityException { try { CertificateProvider provider = manager.getInstance(CertificateProvider.class, "BCStoreX509"); ((BcStoreX509CertificateProvider) provider).s...
java
public static CertifiedPublicKey getCertificate(CertificateProvider provider, SignerInformation signer, CertificateFactory factory) { SignerId id = signer.getSID(); if (provider instanceof BcStoreX509CertificateProvider) { X509CertificateHolder cert = ((BcStoreX509CertificatePro...
java
public static Version getStrictVersion(Collection<? extends VersionRangeCollection> ranges) { for (VersionRangeCollection collection : ranges) { if (collection.getRanges().size() == 1) { VersionRange range = collection.getRanges().iterator().next(); if (range inst...
java
public DefaultJobProgressStep addLevel(int steps, Object newLevelSource, boolean levelStep) { assertModifiable(); this.maximumChildren = steps; this.levelSource = newLevelSource; if (steps > 0) { this.childSize = 1.0D / steps; } if (this.maximumChildren...
java
public DefaultJobProgressStep nextStep(Message stepMessage, Object newStepSource) { assertModifiable(); // Close current step and move to the end finishStep(); // Add new step return addStep(stepMessage, newStepSource); }
java
public void finishStep() { // Close step if (this.children != null && !this.children.isEmpty()) { this.children.get(this.children.size() - 1).finish(); } }
java
private void removeNodes(String xpathExpression, Document domdoc) { List<Node> nodes = domdoc.selectNodes(xpathExpression); for (Node node : nodes) { node.detach(); } }
java
@Override public <T> T get(String fieldName) { switch (fieldName.toLowerCase()) { case FIELD_REPOSITORY: return (T) getRepository(); case FIELD_ID: return (T) getId().getId(); case FIELD_VERSION: return (T) getId().getVe...
java
public static String extractXML(Node node, int start, int length) { ExtractHandler handler = null; try { handler = new ExtractHandler(start, length); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(new DOMSource(node), ne...
java
public static String unescape(Object content) { if (content == null) { return null; } String str = String.valueOf(content); str = APOS_PATTERN.matcher(str).replaceAll("'"); str = QUOT_PATTERN.matcher(str).replaceAll("\""); str = LT_PATTERN.matcher(str).re...
java
public static Document parse(LSInput source) { try { LSParser p = LS_IMPL.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); // Disable validation, since this takes a lot of time and causes unneeded network traffic p.getDomConfig().setParameter("validate", false)...
java
public static String serialize(Node node, boolean withXmlDeclaration) { if (node == null) { return ""; } try { LSOutput output = LS_IMPL.createLSOutput(); StringWriter result = new StringWriter(); output.setCharacterStream(result); ...
java
public static String transform(Source xml, Source xslt) { if (xml != null && xslt != null) { try { StringWriter output = new StringWriter(); Result result = new StreamResult(output); javax.xml.transform.TransformerFactory.newInstance().newTransform...
java
public static String formatXMLContent(String content) throws TransformerFactoryConfigurationError, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputPropert...
java
private void declareProperty(ExecutionContextProperty property) { if (this.properties.containsKey(property.getKey())) { throw new PropertyAlreadyExistsException(property.getKey()); } this.properties.put(property.getKey(), property); }
java
public Object setExtensionProperty(String key, Object value) { return getExtensionProperties().put(key, value); }
java
org.bouncycastle.crypto.params.DSAParameters getDsaParameters(SecureRandom random, DSAKeyParametersGenerationParameters params) { DSAParametersGenerator paramGen = getGenerator(params.getHashHint()); if (params.use186r3()) { DSAParameterGenerationParameters p = new DSAParameterG...
java
private DSAParametersGenerator getGenerator(String hint) { if (hint == null || "SHA-1".equals(hint)) { return new DSAParametersGenerator(); } DigestFactory factory; try { factory = this.manager.getInstance(DigestFactory.class, hint); } catch (Compone...
java
static int getUsageIndex(DSAKeyValidationParameters.Usage usage) { if (usage == DSAKeyValidationParameters.Usage.DIGITAL_SIGNATURE) { return DSAParameterGenerationParameters.DIGITAL_SIGNATURE_USAGE; } else if (usage == DSAKeyValidationParameters.Usage.KEY_ESTABLISHMENT) { ret...
java
private static DSAKeyValidationParameters.Usage getUsage(int usage) { if (usage == DSAParameterGenerationParameters.DIGITAL_SIGNATURE_USAGE) { return DSAKeyValidationParameters.Usage.DIGITAL_SIGNATURE; } else if (usage == DSAParameterGenerationParameters.KEY_ESTABLISHMENT_USAGE) { ...
java
@Override public void addURL(URL url) { this.finder.addURI(URI.create(url.toExternalForm())); }
java
@Override public void addURLs(List<URL> urls) { for (URL url : urls) { addURL(url); } }
java
@Override protected Class<?> findClass(final String name) throws ClassNotFoundException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws ClassNotFoundException ...
java
private boolean isSealed(String name, Manifest man) { String path = name.replace('.', '/').concat("/"); Attributes attr = man.getAttributes(path); String sealed = null; if (attr != null) { sealed = attr.getValue(Name.SEALED); } if (sealed == null) { ...
java
@Override public URL findResource(final String name) { return AccessController.doPrivileged(new PrivilegedAction<URL>() { @Override public URL run() { return URIClassLoader.this.finder.findResource(name); } }, this.acc); ...
java
@Override public Enumeration<URL> findResources(final String name) throws IOException { return AccessController.doPrivileged(new PrivilegedAction<Enumeration<URL>>() { @Override public Enumeration<URL> run() { return URIClassLoader.this.finder....
java
protected ResourceHandle getResourceHandle(final String name) { return AccessController.doPrivileged(new PrivilegedAction<ResourceHandle>() { @Override public ResourceHandle run() { return URIClassLoader.this.finder.getResource(name); }...
java
protected Enumeration<ResourceHandle> getResourceHandles(final String name) { return AccessController.doPrivileged(new PrivilegedAction<Enumeration<ResourceHandle>>() { @Override public Enumeration<ResourceHandle> run() { return URIClassLoader.this...
java
protected void initializePatterns() { this.contentPagePatterns = initializationPagePatterns(this.contentPages); this.technicalPagePatterns = initializationPagePatterns(this.technicalPages); // Transform title expectations into Patterns Map<Pattern, Pattern> patterns = new HashMap<>(...
java
protected void executeLicenseGoal(String goal) throws MojoExecutionException { // Find the license plugin (it's project's responsibility to make sure the License plugin is properly setup in // its <pluginManagement>, for most XWiki projects it just mean inherits from xwiki-commons-pom) Plugi...
java
protected Color parseRGB(String value) { StringTokenizer items = new StringTokenizer(value, ","); try { int red = 0; if (items.hasMoreTokens()) { red = Integer.parseInt(items.nextToken().trim()); } int green = 0; if (items...
java
public ResourceHandle getResource(URL source, String name) { return getResource(source, name, new HashSet<>(), null); }
java
public ResourceHandle getResource(URL[] sources, String name) { Set<URL> visited = new HashSet<>(); for (URL source : sources) { ResourceHandle h = getResource(source, name, visited, null); if (h != null) { return h; } } return null...
java
public URL findResource(URL source, String name) { return findResource(source, name, new HashSet<>(), null); }
java
public URL findResource(URL[] sources, String name) { Set<URL> visited = new HashSet<>(); for (URL source : sources) { URL url = findResource(source, name, visited, null); if (url != null) { return url; } } return null; }
java
@Unstable public static String toAlphaNumeric(String text) { if (isEmpty(text)) { return text; } return stripAccents(text).replaceAll("[^a-zA-Z0-9]", ""); }
java
public static List<X509GeneralName> getX509GeneralNames(GeneralNames genNames) { if (genNames == null) { return null; } GeneralName[] names = genNames.getNames(); List<X509GeneralName> x509names = new ArrayList<X509GeneralName>(names.length); for (GeneralName na...
java
public static EnumSet<KeyUsage> getSetOfKeyUsage(org.bouncycastle.asn1.x509.KeyUsage keyUsage) { if (keyUsage == null) { return null; } Collection<KeyUsage> usages = new ArrayList<KeyUsage>(); for (KeyUsage usage : KeyUsage.values()) { if ((((DERBitString) k...
java
public static ExtendedKeyUsages getExtendedKeyUsages(ExtendedKeyUsage usages) { if (usages == null) { return null; } List<String> usageStr = new ArrayList<String>(); for (KeyPurposeId keyPurposeId : usages.getUsages()) { usageStr.add(keyPurposeId.getId()); ...
java
public static GeneralNames getGeneralNames(X509GeneralName[] genNames) { GeneralName[] names = new GeneralName[genNames.length]; int i = 0; for (X509GeneralName name : genNames) { if (name instanceof BcGeneralName) { names[i++] = ((BcGeneralName) name).getGeneral...
java
public static org.bouncycastle.asn1.x509.KeyUsage getKeyUsage(EnumSet<KeyUsage> usages) { int bitmask = 0; for (KeyUsage usage : usages) { bitmask |= usage.value(); } return new org.bouncycastle.asn1.x509.KeyUsage(bitmask); }
java
public static ExtendedKeyUsage getExtendedKeyUsage(Set<String> usages) { KeyPurposeId[] keyUsages = new KeyPurposeId[usages.size()]; int i = 0; for (String usage : usages) { keyUsages[i++] = KeyPurposeId.getInstance(new ASN1ObjectIdentifier(usage)); } return new...
java
public void initialize(ClassLoader classLoader) { ComponentAnnotationLoader loader = new ComponentAnnotationLoader(); loader.initialize(this, classLoader); // Extension point to allow component to manipulate ComponentManager initialized state. try { List<ComponentManager...
java
private Attributes getAttributes(StartElement event) { AttributesImpl attrs = new AttributesImpl(); if (!event.isStartElement()) { throw new InternalError("getAttributes() attempting to process: " + event); } // Add namspace declarations if required if (this.fil...
java
@Override protected TreeMarshaller createMarshallingContext(HierarchicalStreamWriter writer, ConverterLookup converterLookup, Mapper mapper) { return new SafeTreeMarshaller(writer, converterLookup, mapper, RELATIVE); }
java
public Map<String, List<String>> parseQuery(String query) { Map<String, List<String>> queryParams = new LinkedHashMap<>(); if (query != null) { for (NameValuePair params : URLEncodedUtils.parse(query, StandardCharsets.UTF_8)) { String name = params.getName(); ...
java
public static boolean sendEndEvent(Object filter, FilterDescriptor descriptor, String id, FilterEventParameters parameters) throws FilterException { FilterElementDescriptor elementDescriptor = descriptor.getElement(id); if (elementDescriptor != null && elementDescriptor.getEndMethod() != nu...
java
public static boolean sendOnEvent(Object filter, FilterDescriptor descriptor, String id, FilterEventParameters parameters) throws FilterException { FilterElementDescriptor elementDescriptor = descriptor.getElement(id); if (elementDescriptor != null && elementDescriptor.getOnMethod() != null...
java
private void onEventListenerComponentAdded(ComponentDescriptorAddedEvent event, ComponentManager componentManager, ComponentDescriptor<EventListener> descriptor) { try { EventListener eventListener = componentManager.getInstance(EventListener.class, event.getRoleHint()); if ...
java
private void onEventListenerComponentRemoved(ComponentDescriptorRemovedEvent event, ComponentManager componentManager, ComponentDescriptor<?> descriptor) { EventListener removedEventListener = null; for (EventListener eventListener : getListenersByName().values()) { if (eventList...
java
protected org.bouncycastle.crypto.CipherParameters getBcCipherParameter(AsymmetricCipherParameters parameters) { if (parameters instanceof BcAsymmetricKeyParameters) { return ((BcAsymmetricKeyParameters) parameters).getParameters(); } // TODO: convert parameters to compatible on...
java
public int getDirective(char[] array, int currentIndex, StringBuffer velocityBlock, VelocityParserContext context) throws InvalidVelocityException { int i = currentIndex + 1; // Get macro name StringBuffer directiveNameBuffer = new StringBuffer(); i = getDirectiveName(array,...
java
public int getVelocityIdentifier(char[] array, int currentIndex, StringBuffer velocityBlock, VelocityParserContext context) throws InvalidVelocityException { // The first character of an identifier must be a [a-zA-Z] if (!Character.isLetter(array[currentIndex])) { throw new Inval...
java
public int getTableElement(char[] array, int currentIndex, StringBuffer velocityBlock, VelocityParserContext context) { return getParameters(array, currentIndex, velocityBlock, ']', context); }
java
protected boolean tryInstallExtension(ExtensionId extensionId, String namespace) { DefaultExtensionPlanTree currentTree = this.extensionTree.clone(); try { installExtension(extensionId, namespace, currentTree); setExtensionTree(currentTree); return true; ...
java
public static String encode(String str) { String encoded; try { encoded = URLEncoder.encode(str, "UTF-8").replace(".", "%2E").replace("*", "%2A"); } catch (UnsupportedEncodingException e) { // Should never happen encoded = str; } return e...
java
public static boolean isWebjar(Extension extension) { // Ideally webjar extensions should have "webjar" type if (extension.getType().equals(WEBJAR)) { return true; } /////////////////////////////// // But it's not the case for: // ** webjar.org releases ...
java
private ExtensionHandler getExtensionHandler(LocalExtension localExtension) throws ComponentLookupException { return this.componentManager.getInstance(ExtensionHandler.class, localExtension.getType().toLowerCase()); }
java
public static boolean matches(Pattern patternMatcher, Collection<Filter> filters, Extension extension) { if (matches(patternMatcher, extension.getId().getId(), extension.getDescription(), extension.getSummary(), extension.getName(), ExtensionIdConverter.toStringList(extension.getExtensionFeature...
java
public static boolean matches(Collection<Filter> filters, Extension extension) { if (filters != null) { for (Filter filter : filters) { if (!matches(filter, extension)) { return false; } } } return true; }
java
public static boolean matches(Pattern patternMatcher, Object... elements) { if (patternMatcher == null) { return true; } for (Object element : elements) { if (matches(patternMatcher, element)) { return true; } } return fal...
java
public static void sort(List<? extends Extension> extensions, Collection<SortClause> sortClauses) { Collections.sort(extensions, new SortClauseComparator(sortClauses)); }
java
public static <E extends Extension> IterableResult<E> appendSearchResults(IterableResult<E> previousSearchResult, IterableResult<E> result) { AggregatedIterableResult<E> newResult; if (previousSearchResult instanceof AggregatedIterableResult) { newResult = ((AggregatedIterableRe...
java
public static IterableResult<Extension> search(ExtensionQuery query, Iterable<ExtensionRepository> repositories) throws SearchException { IterableResult<Extension> searchResult = null; int currentOffset = query.getOffset() > 0 ? query.getOffset() : 0; int currentNb = query.getLimit(...
java
public static IterableResult<Extension> search(ExtensionRepository repository, ExtensionQuery query, IterableResult<Extension> previousSearchResult) throws SearchException { IterableResult<Extension> result; if (repository instanceof Searchable) { if (repository instanceof Advan...
java
private <E, F> void displayInlineDiff(UnifiedDiffElement<E, F> previous, UnifiedDiffElement<E, F> next, UnifiedDiffConfiguration<E, F> config) { try { List<F> previousSubElements = config.getSplitter().split(previous.getValue()); List<F> nextSubElements = config.getSplitter()...
java
protected List<Element> filterChildren(Element parent, String tagName) { List<Element> result = new ArrayList<Element>(); Node current = parent.getFirstChild(); while (current != null) { if (current.getNodeName().equals(tagName)) { result.add((Element) current); ...
java
protected List<Element> filterDescendants(Element parent, String[] tagNames) { List<Element> result = new ArrayList<Element>(); for (String tagName : tagNames) { NodeList nodes = parent.getElementsByTagName(tagName); for (int i = 0; i < nodes.getLength(); i++) { ...
java
protected boolean hasAttribute(List<Element> elements, String attributeName, boolean checkValue) { boolean hasAttribute = true; if (!checkValue) { for (Element e : elements) { hasAttribute = e.hasAttribute(attributeName) ? hasAttribute : false; } } els...
java
protected void moveChildren(Element parent, Element destination) { NodeList children = parent.getChildNodes(); while (children.getLength() > 0) { destination.appendChild(parent.removeChild(parent.getFirstChild())); } }
java
static org.bouncycastle.crypto.params.DHParameters getDhParameters(SecureRandom random, DHKeyParametersGenerationParameters params) { DHParametersGenerator paramGen = new DHParametersGenerator(); paramGen.init(params.getStrength() * 8, params.getCertainty(), random); return paramGe...
java
private DefaultLocalExtension loadDescriptor(File descriptor) throws InvalidExtensionException { FileInputStream fis; try { fis = new FileInputStream(descriptor); } catch (FileNotFoundException e) { throw new InvalidExtensionException("Failed to open descriptor for re...
java
private String getFilePath(ExtensionId id, String fileExtension) { String encodedId = PathUtils.encode(id.getId()); String encodedVersion = PathUtils.encode(id.getVersion().toString()); String encodedType = PathUtils.encode(fileExtension); return encodedId + File.separator + encoded...
java
public void removeExtension(DefaultLocalExtension extension) throws IOException { File descriptorFile = extension.getDescriptorFile(); if (descriptorFile == null) { throw new IOException("Exception does not exists"); } descriptorFile.delete(); DefaultLocalExten...
java
private void parse() { this.elements = new ArrayList<>(); try { for (Tokenizer tokenizer = new Tokenizer(this.rawVersion); tokenizer.next();) { Element element = new Element(tokenizer); this.elements.add(element); if (element.getVersionTyp...
java
private static void trimPadding(List<Element> elements) { for (ListIterator<Element> it = elements.listIterator(elements.size()); it.hasPrevious();) { Element element = it.previous(); if (element.compareTo(null) == 0) { it.remove(); } else { ...
java
private static int comparePadding(List<Element> elements, int index, Boolean number) { int rel = 0; for (Iterator<Element> it = elements.listIterator(index); it.hasNext();) { Element element = it.next(); if (number != null && number.booleanValue() != element.isNumber()) { ...
java
public static Collection<String> importProperty(MutableExtension extension, String propertySuffix, Collection<String> def) { Object obj = importProperty(extension, propertySuffix); if (obj == null) { return def; } else if (obj instanceof Collection) { return ...
java
protected void sendEntryAddedEvent(CacheEntryEvent<T> event) { for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners .getListeners(org.xwiki.cache.event.CacheEntryListener.class)) { listener.cacheEntryAdded(event); } }
java
protected void sendEntryRemovedEvent(CacheEntryEvent<T> event) { for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners .getListeners(org.xwiki.cache.event.CacheEntryListener.class)) { listener.cacheEntryRemoved(event); } disposeCacheVal...
java
protected void sendEntryModifiedEvent(CacheEntryEvent<T> event) { for (org.xwiki.cache.event.CacheEntryListener<T> listener : this.cacheEntryListeners .getListeners(org.xwiki.cache.event.CacheEntryListener.class)) { listener.cacheEntryModified(event); } }
java
protected void disposeCacheValue(T value) { if (value instanceof DisposableCacheValue) { try { ((DisposableCacheValue) value).dispose(); } catch (Throwable e) { // We catch Throwable because this method is usually automatically called by an event send ...
java
public X509ExtensionBuilder addExtension(ASN1ObjectIdentifier oid, boolean critical, ASN1Encodable value) { try { this.extensions.addExtension(oid, critical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); } catch (IOException e) { // Very unlikely throw ne...
java
public Version getVersion(String rawVersion) { Version version = this.versions.get(rawVersion); if (version == null) { version = new DefaultVersion(rawVersion); this.versions.put(rawVersion, version); } return version; }
java
public VersionConstraint getVersionConstraint(String rawConstraint) { VersionConstraint constraint = this.versionConstrains.get(rawConstraint); if (constraint == null) { constraint = new DefaultVersionConstraint(rawConstraint); this.versionConstrains.put(rawConstraint, cons...
java
protected void extendsTBSCertificate(BcX509TBSCertificateBuilder builder, CertifiedPublicKey issuer, PrincipalIndentifier subjectName, PublicKeyParameters subject, X509CertificateParameters parameters) throws IOException { // Do nothing by default. }
java
public TBSCertificate buildTBSCertificate(PrincipalIndentifier subjectName, PublicKeyParameters subject, X509CertificateParameters parameters) throws IOException { PrincipalIndentifier issuerName; CertifiedPublicKey issuer = null; if (this.signer instanceof CertifyingSigner) { ...
java
private void runInitializers(ExecutionContext context) throws ExecutionContextException { for (ExecutionContextInitializer initializer : this.initializerProvider.get()) { initializer.initialize(context); } }
java
private Class<?> getFieldRole(Field field, Requirement requirement) { Class<?> role; // Handle case of list or map if (isDependencyOfListType(field.getType())) { role = getGenericRole(field); } else { role = field.getType(); } return role; ...
java