code
stringlengths
73
34.1k
label
stringclasses
1 value
private void openTag(String qName, Attributes atts) { this.result.append('<').append(qName); for (int i = 0; i < atts.getLength(); i++) { this.result.append(' ').append(atts.getQName(i)).append("=\"").append(atts.getValue(i)).append('\"'); } this.result.append('>'); }
java
private void checkValue(Object value) { if (this.nonNull && value == null) { throw new IllegalArgumentException(String.format("The property [%s] may not be null!", getKey())); } if (getType() != null && value != null && !getType().isAssignableFrom(value.getClass())) { ...
java
protected static int[] newKeySizeArray(int minSize, int maxSize, int step) { int[] result = new int[((maxSize - minSize) / step) + 1]; for (int i = minSize, j = 0; i <= maxSize; i += step, j++) { result[j] = i; } return result; }
java
public BcX509v3TBSCertificateBuilder setExtensions(CertifiedPublicKey issuer, PublicKeyParameters subject, X509Extensions extensions1, X509Extensions extensions2) throws IOException { DefaultX509ExtensionBuilder extBuilder = new DefaultX509ExtensionBuilder(); extBuilder.addAuthorityKeyIdent...
java
public <E> List<E> unmodifiable(List<E> input) { if (input == null) { return null; } return Collections.unmodifiableList(input); }
java
public <K, V> Map<K, V> unmodifiable(Map<K, V> input) { if (input == null) { return null; } return Collections.unmodifiableMap(input); }
java
public <E> Set<E> unmodifiable(Set<E> input) { if (input == null) { return null; } return Collections.unmodifiableSet(input); }
java
public <E> Collection<E> unmodifiable(Collection<E> input) { if (input == null) { return null; } return Collections.unmodifiableCollection(input); }
java
public <E> boolean reverse(List<E> input) { if (input == null) { return false; } try { Collections.reverse(input); return true; } catch (UnsupportedOperationException ex) { return false; } }
java
public <E extends Comparable<E>> boolean sort(List<E> input) { if (input == null) { return false; } try { Collections.sort(input); return true; } catch (UnsupportedOperationException ex) { return false; } }
java
private <E> boolean isFullyModified(List commonAncestor, Patch<E> patchCurrent) { return patchCurrent.size() == 1 && commonAncestor.size() == patchCurrent.get(0).getPrevious().size(); }
java
@Override public Iterator getIterator(Object obj, Info i) throws Exception { if (obj != null) { SecureIntrospectorControl sic = (SecureIntrospectorControl) this.introspector; if (sic.checkObjectExecutePermission(obj.getClass(), null)) { return super.getIterator(ob...
java
protected void unpackXARToOutputDirectory(Artifact artifact, String[] includes, String[] excludes) throws MojoExecutionException { if (!this.outputBuildDirectory.exists()) { this.outputBuildDirectory.mkdirs(); } File file = artifact.getFile(); unpack(file, this.o...
java
protected Set<Artifact> resolveArtifactDependencies(Artifact artifact) throws ArtifactResolutionException, ArtifactNotFoundException, ProjectBuildingException { Artifact pomArtifact = this.factory.createArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "", ...
java
protected XWikiDocument getDocFromXML(File file) throws MojoExecutionException { XWikiDocument doc; try { doc = new XWikiDocument(); doc.fromXML(file); } catch (Exception e) { throw new MojoExecutionException(String.format("Failed to parse [%s].", file.ge...
java
private void repair() throws IOException { File folder = this.configuration.getStorage(); if (folder.exists()) { if (!folder.isDirectory()) { throw new IOException("Not a directory: " + folder); } repairFolder(folder); } }
java
public void runJob() { try { this.currentJob = this.jobQueue.take(); // Create a clean Execution Context ExecutionContext context = new ExecutionContext(); try { this.executionContextManager.initialize(context); } catch (Execution...
java
private void initRepositoryFeatures() { if (this.repositoryVersion == null) { // Default features this.repositoryVersion = new DefaultVersion(Resources.VERSION10); this.filterable = false; this.sortable = false; // Get remote features ...
java
public void fromXML(Document domdoc) throws DocumentException { this.encoding = domdoc.getXMLEncoding(); Element rootElement = domdoc.getRootElement(); this.reference = readDocumentReference(domdoc); this.locale = rootElement.attributeValue("locale"); if (this.locale == nu...
java
public static String readElement(Element rootElement, String elementName) throws DocumentException { String result = null; Element element = rootElement.element(elementName); if (element != null) { // Make sure the element does not have any child element if (!element....
java
public static X509CertificateHolder getX509CertificateHolder(CertifiedPublicKey cert) { if (cert instanceof BcX509CertifiedPublicKey) { return ((BcX509CertifiedPublicKey) cert).getX509CertificateHolder(); } else { try { return new X509CertificateHolder(cert.ge...
java
public static AsymmetricKeyParameter getAsymmetricKeyParameter(PublicKeyParameters publicKey) { if (publicKey instanceof BcAsymmetricKeyParameters) { return ((BcAsymmetricKeyParameters) publicKey).getParameters(); } else { try { return PublicKeyFactory.createK...
java
public static SubjectPublicKeyInfo getSubjectPublicKeyInfo(PublicKeyParameters publicKey) { try { if (publicKey instanceof BcPublicKeyParameters) { return ((BcPublicKeyParameters) publicKey).getSubjectPublicKeyInfo(); } else { return SubjectPublicKeyIn...
java
public static X509CertificateHolder getX509CertificateHolder(TBSCertificate tbsCert, byte[] signature) { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(tbsCert.getSignature()); v.add(new DERBitString(signature)); return new X509CertificateHolder(Ce...
java
public static boolean isAlgorithlIdentifierEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) { if (!id1.getAlgorithm().equals(id2.getAlgorithm())) { return false; } if (id1.getParameters() == null) { return !(id2.getParameters() != null && !id2....
java
public static Signer updateDEREncodedObject(Signer signer, ASN1Encodable tbsObj) throws IOException { OutputStream sOut = signer.getOutputStream(); DEROutputStream dOut = new DEROutputStream(sOut); dOut.writeObject(tbsObj); sOut.close(); return signer; }
java
public static X500Name getX500Name(PrincipalIndentifier principal) { if (principal instanceof BcPrincipalIdentifier) { return ((BcPrincipalIdentifier) principal).getX500Name(); } else { return new X500Name(principal.getName()); } }
java
public static AlgorithmIdentifier getSignerAlgoritmIdentifier(Signer signer) { if (signer instanceof ContentSigner) { return ((ContentSigner) signer).getAlgorithmIdentifier(); } else { return AlgorithmIdentifier.getInstance(signer.getEncoded()); } }
java
public static CertifiedPublicKey convertCertificate(CertificateFactory certFactory, X509CertificateHolder cert) { if (cert == null) { return null; } if (certFactory instanceof BcX509CertificateFactory) { return ((BcX509CertificateFactory) certFactory).convert(cert); ...
java
protected void addCachedExtension(E extension) { if (!this.extensions.containsKey(extension.getId())) { // extensions this.extensions.put(extension.getId(), extension); // versions addCachedExtensionVersion(extension.getId().getId(), extension); i...
java
protected void addCachedExtensionVersion(String feature, E extension) { // versions List<E> versions = this.extensionsVersions.get(feature); if (versions == null) { versions = new ArrayList<E>(); this.extensionsVersions.put(feature, versions); versions.a...
java
protected void removeCachedExtension(E extension) { // Remove the extension from the memory. this.extensions.remove(extension.getId()); // versions removeCachedExtensionVersion(extension.getId().getId(), extension); if (!this.strictId) { for (String feature : ext...
java
protected void removeCachedExtensionVersion(String feature, E extension) { // versions List<E> extensionVersions = this.extensionsVersions.get(feature); extensionVersions.remove(extension); if (extensionVersions.isEmpty()) { this.extensionsVersions.remove(feature); ...
java
public static byte[] convert(char[] password, ToBytesMode mode) { byte[] passwd; switch (mode) { case PKCS12: passwd = PBEParametersGenerator.PKCS12PasswordToBytes(password); break; case PKCS5: passwd = PBEParametersGenerator.P...
java
public static String getPrefix(String namespaceString) { Namespace namespace = toNamespace(namespaceString); return namespace != null ? namespace.getType() : null; }
java
private void filter(Element list) { // Iterate all the child nodes of the given list to see who's allowed and who's not allowed inside it. Node child = list.getFirstChild(); Node previousListItem = null; while (child != null) { Node nextSibling = child.getNextSibling(); ...
java
private boolean isAllowedInsideList(Node node) { return (node.getNodeType() != Node.ELEMENT_NODE || node.getNodeName().equalsIgnoreCase(TAG_LI)) && (node.getNodeType() != Node.TEXT_NODE || node.getNodeValue().trim().length() == 0); }
java
private ComponentDescriptor createComponentDescriptor(Class<?> componentClass, String hint, Type componentRoleType) { DefaultComponentDescriptor descriptor = new DefaultComponentDescriptor(); descriptor.setRoleType(componentRoleType); descriptor.setImplementation(componentClass); ...
java
public synchronized void flushEvents() { while (!this.events.isEmpty()) { ComponentEventEntry entry = this.events.pop(); sendEvent(entry.event, entry.descriptor, entry.componentManager); } }
java
private void notifyComponentEvent(Event event, ComponentDescriptor<?> descriptor, ComponentManager componentManager) { if (this.shouldStack) { synchronized (this) { this.events.push(new ComponentEventEntry(event, descriptor, componentManager)); } } els...
java
private void sendEvent(Event event, ComponentDescriptor<?> descriptor, ComponentManager componentManager) { if (this.observationManager != null) { this.observationManager.notify(event, componentManager, descriptor); } }
java
public static CertifyingSigner getInstance(boolean forSigning, CertifiedKeyPair certifier, SignerFactory factory) { return new CertifyingSigner(certifier.getCertificate(), factory.getInstance(forSigning, certifier.getPrivateKey())); }
java
protected void jobStarting() { this.jobContext.pushCurrentJob(this); this.observationManager.notify(new JobStartedEvent(getRequest().getId(), getType(), this.request), this); if (this.status instanceof AbstractJobStatus) { ((AbstractJobStatus<R>) this.status).setStartDate(new D...
java
protected void jobFinished(Throwable error) { this.lock.lock(); try { if (this.status instanceof AbstractJobStatus) { // Store error ((AbstractJobStatus) this.status).setError(error); } // Give a chance to any listener to do custo...
java
protected void initializeUberspector(String classname) { // Avoids direct recursive calls if (!StringUtils.isEmpty(classname) && !classname.equals(this.getClass().getCanonicalName())) { Uberspect u = instantiateUberspector(classname); if (u == null) { return; ...
java
protected Uberspect instantiateUberspector(String classname) { Object o = null; try { o = ClassUtils.getNewInstance(classname); } catch (ClassNotFoundException e) { this.log.warn(String.format("The specified uberspector [%s]" + " does not exist or is n...
java
private void validateExtension(LocalExtension localExtension, boolean dependencies) { Collection<String> namespaces = DefaultInstalledExtension.getNamespaces(localExtension); if (namespaces == null) { if (dependencies || !DefaultInstalledExtension.isDependency(localExtension, null)) { ...
java
private DefaultInstalledExtension validateExtension(LocalExtension localExtension, String namespace, Map<String, ExtensionDependency> managedDependencies) throws InvalidExtensionException { DefaultInstalledExtension installedExtension = this.extensions.get(localExtension.getId()); if (instal...
java
public static void setFieldValue(Object instanceContainingField, String fieldName, Object fieldValue) { // Find the class containing the field to set Class<?> targetClass = instanceContainingField.getClass(); while (targetClass != null) { for (Field field : targetClass.getDeclare...
java
public static Type resolveType(Type targetType, Type rootType) { Type resolvedType; if (targetType instanceof ParameterizedType && rootType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) targetType; resolvedType = r...
java
@Unstable public static String serializeType(Type type) { if (type == null) { return null; } StringBuilder sb = new StringBuilder(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Stri...
java
public V get(K key, V defaultValue) { // Check if we only know an equal entry V sharedValue = get(key); if (sharedValue == null) { // If no entry can be found, store and return the passed one sharedValue = defaultValue; // Make sure to remember the entry...
java
public void put(K key, V value) { this.lock.writeLock().lock(); try { this.map.put(key, new SoftReference<>(value)); } finally { this.lock.writeLock().unlock(); } }
java
private void cacheEntryInserted(String key, T value) { InfinispanCacheEntryEvent<T> event = new InfinispanCacheEntryEvent<>(new InfinispanCacheEntry<T>(this, key, value)); T previousValue = this.preEventData.get(key); if (previousValue != null) { if (previousValue !...
java
private void cacheEntryRemoved(String key, T value) { InfinispanCacheEntryEvent<T> event = new InfinispanCacheEntryEvent<>(new InfinispanCacheEntry<T>(this, key, value)); sendEntryRemovedEvent(event); }
java
private void checkNonCoreGroupId(Model model) throws EnforcerRuleException { String groupId = model.getGroupId(); if (groupId.equals(CORE_GROUP_ID) || (groupId.startsWith(CORE_GROUP_ID_PREFIX) && !groupId.equals(CONTRIB_GROUP_ID) && !groupId.startsWith(CONTRIB_GROUP_ID_PREFIX))) { ...
java
private void checkNonCoreArtifactId(Model model) throws EnforcerRuleException { String artifactId = model.getArtifactId(); for (String prefix : CORE_ARTIFACT_ID_PREFIXES) { if (artifactId.startsWith(prefix)) { throw new EnforcerRuleException("The [%s] artifact id prefix i...
java
public void writeStartDocument(String encoding, String version) throws FilterException { try { this.writer.writeStartDocument(encoding, version); } catch (XMLStreamException e) { throw new FilterException("Failed to write start document", e); } }
java
private String getTypeName(Type type) { String name; if (type instanceof Class) { name = ((Class<?>) type).getName(); } else if (type instanceof ParameterizedType) { name = ((Class<?>) ((ParameterizedType) type).getRawType()).getName(); } else { na...
java
private String getTypeGenericName(Type type) { StringBuilder sb = new StringBuilder(getTypeName(type)); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] generics = parameterizedType.getActualTypeArguments(); ...
java
public void updateExtensions() { // Start a background thread to get more details about the found extensions Thread thread = new Thread(new Runnable() { @Override public void run() { DefaultCoreExtensionRepository.this.scanner ...
java
public void startListening() { // Register progress listener this.observationManager.addListener(new WrappedThreadEventListener(this.progress)); // Isolate log for the job status this.logListener = new LoggerListener(LoggerListener.class.getName() + '_' + hashCode(), this.logs); ...
java
public void stopListening() { if (isIsolated()) { this.loggerManager.popLogListener(); } else { this.observationManager.removeListener(this.logListener.getName()); } this.observationManager.removeListener(this.progress.getName()); // Make sure the pro...
java
public <E> List<InlineDiffChunk<E>> inline(List<E> previous, List<E> next) { setError(null); try { return this.inlineDiffDisplayer.display(this.diffManager.diff(previous, next, null)); } catch (DiffException e) { setError(e); return null; } }
java
public List<InlineDiffChunk<Character>> inline(String previous, String next) { setError(null); try { return this.inlineDiffDisplayer .display(this.diffManager.diff(this.charSplitter.split(previous), this.charSplitter.split(next), null)); } catch (DiffException e)...
java
public X509CertificateHolder getCertificate(Selector selector) { try { return (X509CertificateHolder) this.store.getMatches(selector).iterator().next(); } catch (Throwable t) { return null; } }
java
public void initialize(ComponentManager manager, ClassLoader classLoader) { try { // Find all declared components by retrieving the list defined in COMPONENT_LIST. List<ComponentDeclaration> componentDeclarations = getDeclaredComponents(classLoader, COMPONENT_LIST); // F...
java
private Collection<ComponentDescriptor<?>> getComponentsDescriptors(ClassLoader classLoader, List<ComponentDeclaration> componentDeclarations) { // For each component class name found, load its class and use introspection to find the necessary // annotations required to create a Component De...
java
private List<ComponentDeclaration> getDeclaredComponents(ClassLoader classLoader, String location) throws IOException { List<ComponentDeclaration> annotatedClassNames = new ArrayList<>(); Enumeration<URL> urls = classLoader.getResources(location); while (urls.hasMoreElements()) { ...
java
public List<ComponentDeclaration> getDeclaredComponentsFromJAR(InputStream jarFile) throws IOException { ZipInputStream zis = new ZipInputStream(jarFile); List<ComponentDeclaration> componentDeclarations = null; List<ComponentDeclaration> componentOverrideDeclarations = null; for (...
java
public CertifiedPublicKey convert(X509CertificateHolder cert) { if (cert == null) { return null; } return new BcX509CertifiedPublicKey(cert, this.factory); }
java
private void surroundWithParagraph(Document document, Node body, Node beginNode, Node endNode) { // surround all the nodes starting with the marker node with a paragraph. Element paragraph = document.createElement(TAG_P); body.insertBefore(paragraph, beginNode); Node child = beginNod...
java
private void validateBean(Object bean) throws PropertyException { if (getValidatorFactory() != null) { Validator validator = getValidatorFactory().getValidator(); Set<ConstraintViolation<Object>> constraintViolations = validator.validate(bean); if (!constraintViolations.i...
java
public <E> DiffResult<E> diff(List<E> previous, List<E> next, DiffConfiguration<E> configuration) { DiffResult<E> result; try { result = this.diffManager.diff(previous, next, configuration); } catch (DiffException e) { result = new DefaultDiffResult<E>(previous, next)...
java
public <E> MergeResult<E> merge(List<E> commonAncestor, List<E> next, List<E> current, MergeConfiguration<E> configuration) { MergeResult<E> result; try { result = this.diffManager.merge(commonAncestor, next, current, configuration); } catch (MergeException e) { ...
java
void analyseRevision(R revision, List<E> previous) { if (currentRevision == null) { return; } if (previous == null || previous.isEmpty()) { resolveRemainingToCurrent(); } else { resolveToCurrent(DiffUtils.diff(currentRevisionContent, previous).get...
java
private void resolveToCurrent(List<Delta<E>> deltas) { int lineOffset = 0; for (Delta<E> d : deltas) { Chunk<E> original = d.getOriginal(); Chunk<E> revised = d.getRevised(); int pos = original.getPosition() + lineOffset; // delete lines ...
java
private void resolveRemainingToCurrent() { for (int i = 0; i < this.size; i++) { if (sourceRevisions.get(i) == null) { sourceRevisions.set(i, currentRevision); } } }
java
private void performArchive() throws Exception { // The source dir points to the target/classes directory where the Maven resources plugin // has copied the XAR files during the process-resources phase. // For package.xml, however, we look in the resources directory (i.e. src/main/resources)...
java
private void unpackDependentXARs() throws MojoExecutionException { Set<Artifact> artifacts = this.project.getArtifacts(); if (artifacts != null) { for (Artifact artifact : artifacts) { if (!artifact.isOptional() && "xar".equals(artifact.getType())) { u...
java
private void generatePackageXml(File packageFile, Collection<ArchiveEntry> files) throws Exception { getLog().info(String.format("Generating package.xml descriptor at [%s]", packageFile.getPath())); OutputFormat outputFormat = new OutputFormat("", true); outputFormat.setEncoding(this.encodi...
java
private Document toXML(Collection<ArchiveEntry> files) throws Exception { Document doc = new DOMDocument(); Element packageElement = new DOMElement("package"); doc.setRootElement(packageElement); Element infoElement = new DOMElement("infos"); packageElement.add(infoElement)...
java
private void addFilesToArchive(ZipArchiver archiver, File sourceDir) throws Exception { File generatedPackageFile = new File(sourceDir, PACKAGE_XML); if (generatedPackageFile.exists()) { generatedPackageFile.delete(); } archiver.addDirectory(sourceDir, getIncludes(), get...
java
private void addFilesToArchive(ZipArchiver archiver, File sourceDir, File packageXml) throws Exception { Collection<String> documentNames; getLog().info(String.format("Using the existing package.xml descriptor at [%s]", packageXml.getPath())); try { documentNames = getDocumentNam...
java
private static void addContentsToQueue(Queue<File> fileQueue, File sourceDir) throws MojoExecutionException { File[] files = sourceDir.listFiles(); if (files != null) { for (File currentFile : files) { fileQueue.add(currentFile); } } else { ...
java
public static void stripHTMLEnvelope(Document document) { org.w3c.dom.Element root = document.getDocumentElement(); if (root.getNodeName().equalsIgnoreCase(HTMLConstants.TAG_HTML)) { // Look for a head element below the root element and for a body element Node bodyNode = null...
java
public static void stripFirstElementInside(Document document, String parentTagName, String elementTagName) { NodeList parentNodes = document.getElementsByTagName(parentTagName); if (parentNodes.getLength() > 0) { Node parentNode = parentNodes.item(0); // Look for a p element ...
java
protected void store(BufferedWriter out, String type, byte[] data) throws IOException { write(out, type, data); out.close(); }
java
protected void write(BufferedWriter out, String type, byte[] data) throws IOException { writeHeader(out, type); out.write(this.base64.encode(data, 64)); out.newLine(); writeFooter(out, type); }
java
private static void writeHeader(BufferedWriter out, String type) throws IOException { out.write(PEM_BEGIN + type + DASHES); out.newLine(); }
java
private static void writeFooter(BufferedWriter out, String type) throws IOException { out.write(PEM_END + type + DASHES); out.newLine(); }
java
protected File getStoreFile(StoreReference store) { if (store instanceof FileStoreReference) { return ((FileStoreReference) store).getFile(); } throw new IllegalArgumentException(String.format("Unsupported store reference [%s] for this implementation.", store.getClass...
java
protected X509CertifiedPublicKey getPublicKey(CertifiedPublicKey publicKey) { if (publicKey instanceof X509CertifiedPublicKey) { return (X509CertifiedPublicKey) publicKey; } throw new IllegalArgumentException(String.format("Unsupported certificate [%s], expecting X509 certificat...
java
protected String getCertIdentifier(X509CertifiedPublicKey publicKey) throws IOException { byte[] keyId = publicKey.getSubjectKeyIdentifier(); if (keyId != null) { return this.hex.encode(keyId); } return publicKey.getSerialNumber().toString() + ", " + publicKey.getIssuer()...
java
protected Object readObject(BufferedReader in, byte[] password) throws IOException, GeneralSecurityException { String line; Object obj = null; while ((line = in.readLine()) != null) { obj = processObject(in, line, password); if (obj != null) { break; ...
java
protected Object processObject(BufferedReader in, String line, byte[] password) throws IOException, GeneralSecurityException { if (line.contains(PEM_BEGIN + CERTIFICATE + DASHES)) { return this.certificateFactory.decode(readBytes(in, PEM_END + CERTIFICATE + DASHES)); } re...
java
protected byte[] readBytes(BufferedReader in, String endMarker) throws IOException { String line; StringBuilder buf = new StringBuilder(); while ((line = in.readLine()) != null) { if (line.contains(endMarker)) { break; } buf.append(line.tr...
java
private void onPushLevelProgress(int steps, Object source, boolean singlesteplevel) { if (this.currentStep.isLevelFinished()) { // If current step is done move to next one this.currentStep = this.currentStep.getParent().nextStep(null, source); } // Add level ...
java
private void onEndStepProgress(Object source) { // Try to find the right step based on the source DefaultJobProgressStep step = findStep(this.currentStep, source); if (step == null) { LOGGER.warn("Could not find any matching step for source [{}]. Ignoring EndStepProgress.", ...
java
@Deprecated private void onStepProgress(Object source) { onStartStepProgress(null, source); // if there is only one step close it and move to the next one if (this.currentStep.getParent().getChildren().size() == 1) { this.currentStep = this.currentStep.getParent().nextStep(n...
java