index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/DirectoryImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.aries.util.filesystem.ICloseableDirectory; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; /** * An IDirectory representing a java.io.File whose isDirectory method returns true. */ public class DirectoryImpl extends FileImpl implements IDirectory { /** * @param dir the file to represent. * @param rootFile the file that represents the FS root. */ public DirectoryImpl(File dir, File rootFile) { super(dir, rootFile); } public IFile getFile(String name) { File desiredFile = new File(file, name); IFile result = null; if (desiredFile.exists()) { if(!desiredFile.isDirectory()) result = new FileImpl(desiredFile, rootDirFile); else result = new DirectoryImpl(desiredFile, rootDirFile); } return result; } public boolean isRoot() { boolean result = (rootDirFile == file); return result; } public List<IFile> listFiles() { List<IFile> files = new ArrayList<IFile>(); File[] filesInDir = file.listFiles(); if (filesInDir != null) { for (File f : filesInDir) { if (f.isFile()) { files.add(new FileImpl(f, rootDirFile)); } else if (f.isDirectory()) { files.add(new DirectoryImpl(f, rootDirFile)); } } } return files; } public List<IFile> listAllFiles() { List<IFile> files = new ArrayList<IFile>(); File[] filesInDir = file.listFiles(); if (filesInDir != null) { for (File f : filesInDir) { if (f.isFile()) { files.add(new FileImpl(f, rootDirFile)); } else if (f.isDirectory()) { IDirectory subdir = new DirectoryImpl(f, rootDirFile); files.add(subdir); files.addAll(subdir.listAllFiles()); } } } return files; } public Iterator<IFile> iterator() { return listFiles().iterator(); } public IDirectory getParent() { return isRoot() ? null : super.getParent(); } public IDirectory convert() { return this; } public InputStream open() throws IOException { throw new UnsupportedOperationException(); } public long getLastModified() { long result = super.getLastModified(); for (IFile aFile : this) { long tmpLastModified = aFile.getLastModified(); if (tmpLastModified > result) result = tmpLastModified; } return result; } public ICloseableDirectory toCloseable() { return new CloseableDirectory(this); } }
7,900
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/NestedZipFile.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; public class NestedZipFile implements IFile { private final String name; private final long size; private final long lastModified; private final IDirectory parent; protected final IFile archive; private final String nameInZip; protected final NestedCloseableDirectory cache; /** * Construct a nested zip file * @param archive * @param entry * @param parent */ public NestedZipFile(IFile archive, ZipEntry entry, NestedZipDirectory parent, NestedCloseableDirectory cache) { this.archive = archive; this.parent = parent; this.nameInZip = entry.getName(); name = archive.getName() + "/" + (nameInZip.endsWith("/") ? nameInZip.substring(0, nameInZip.length()-1) : nameInZip); size = entry.getSize(); lastModified = entry.getTime(); this.cache = cache; } public NestedZipFile(IFile archive, String pathInZip, NestedZipDirectory parent, NestedCloseableDirectory cache) { this.archive = archive; this.parent = parent; this.nameInZip = pathInZip; name = archive.getName() + "/" + (nameInZip.endsWith("/") ? nameInZip.substring(0, nameInZip.length()-1) : nameInZip); size = -1; lastModified = -1; this.cache = cache; } public NestedZipFile(IFile archive) { this.archive = archive; this.parent = archive.getParent(); this.nameInZip = ""; name = archive.getName(); lastModified = archive.getLastModified(); size = archive.getSize(); cache = null; } public NestedZipFile(NestedZipFile other, NestedCloseableDirectory cache) { name = other.name; size = other.size; lastModified = other.lastModified; parent = other.parent; archive = other.archive; nameInZip = other.nameInZip; this.cache = cache; } public String getNameInZip() { return nameInZip; } public String getName() { return name; } public boolean isDirectory() { return false; } public boolean isFile() { return true; } public long getLastModified() { return lastModified; } public long getSize() { return size; } public IDirectory convert() { return null; } public IDirectory convertNested() { if (isDirectory()) return convert(); else if (FileSystemImpl.isValidZip(this)) return new NestedZipDirectory(this); else return null; } public IDirectory getParent() { return parent; } public InputStream open() throws IOException, UnsupportedOperationException { if (cache != null && !!!cache.isClosed()) { ZipFile zip = cache.getZipFile(); ZipEntry ze = zip.getEntry(nameInZip); if (ze != null) return zip.getInputStream(ze); else return null; } else { final ZipInputStream zis = new ZipInputStream(archive.open()); ZipEntry entry = zis.getNextEntry(); while (entry != null && !!!entry.getName().equals(nameInZip)) { entry = zis.getNextEntry(); } if (entry != null) { return zis; } else { zis.close(); return null; } } } public IDirectory getRoot() { return archive.getRoot(); } public URL toURL() throws MalformedURLException { if (nameInZip.length() == 0) return archive.toURL(); else { String entryURL = "jar:" + archive.toURL() + "!/" + nameInZip; return new URL(entryURL); } } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() == getClass()) { return toString().equals(obj.toString()); } return false; } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { if (nameInZip.length() == 0) return archive.toString(); return archive.toString() + "/" + nameInZip; } }
7,901
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/ZipCloseableDirectory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import java.io.IOException; import java.util.zip.ZipFile; import org.apache.aries.util.io.IOUtils; public class ZipCloseableDirectory extends CloseableDirectory { private final ZipFile zip; public ZipCloseableDirectory(File archive, ZipDirectory parent) throws IOException { super(parent); this.zip = new ZipFile(archive); delegate = new ZipDirectory(parent, this); } public ZipFile getZipFile() { return zip; } @Override protected void cleanup() { try { IOUtils.close(zip); } catch (IOException e) {} } }
7,902
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/CloseableDirectory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.aries.util.filesystem.ICloseableDirectory; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.internal.MessageUtil; public class CloseableDirectory implements ICloseableDirectory { protected IDirectory delegate; private final AtomicBoolean closed = new AtomicBoolean(false); public CloseableDirectory(IDirectory delegate) { this.delegate = delegate; } public String getName() { checkNotClosed(); return delegate.getName(); } public boolean isDirectory() { checkNotClosed(); return delegate.isDirectory(); } public boolean isFile() { checkNotClosed(); return delegate.isFile(); } public long getLastModified() { checkNotClosed(); return delegate.getLastModified(); } public IFile getFile(String name) { checkNotClosed(); return delegate.getFile(name); } public long getSize() { checkNotClosed(); return delegate.getSize(); } public IDirectory convert() { checkNotClosed(); return delegate.convert(); } public IDirectory convertNested() { checkNotClosed(); return delegate.convertNested(); } public boolean isRoot() { checkNotClosed(); return delegate.isRoot(); } public IDirectory getParent() { checkNotClosed(); return delegate.getParent(); } public IDirectory getRoot() { checkNotClosed(); return delegate.getRoot(); } public Iterator<IFile> iterator() { checkNotClosed(); return delegate.iterator(); } public List<IFile> listFiles() { checkNotClosed(); return delegate.listFiles(); } public List<IFile> listAllFiles() { checkNotClosed(); return delegate.listAllFiles(); } public ICloseableDirectory toCloseable() { checkNotClosed(); return delegate.toCloseable(); } public InputStream open() throws IOException, UnsupportedOperationException { checkNotClosed(); return delegate.open(); } public URL toURL() throws MalformedURLException { checkNotClosed(); return delegate.toURL(); } public final void close() throws IOException { if (closed.compareAndSet(false, true)) { cleanup(); } } protected void cleanup() {} protected void checkNotClosed() { if (isClosed()) throw new IllegalStateException(MessageUtil.getMessage("UTIL0018E")); } public boolean isClosed() { return closed.get(); } }
7,903
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/NestedZipDirectory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import org.apache.aries.util.IORuntimeException; import org.apache.aries.util.filesystem.ICloseableDirectory; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.io.IOUtils; public class NestedZipDirectory extends NestedZipFile implements IDirectory { public NestedZipDirectory(IFile archive, ZipEntry entry, NestedZipDirectory parent, NestedCloseableDirectory cache) { super(archive, entry, parent, cache); } public NestedZipDirectory(IFile archive, String pathInZip, NestedZipDirectory parent, NestedCloseableDirectory cache) { super(archive, pathInZip, parent, cache); } public NestedZipDirectory(IFile archive) { super(archive); } public NestedZipDirectory(NestedZipDirectory other, NestedCloseableDirectory cache) { super(other, cache); } public IDirectory convert() { return this; } public Iterator<IFile> iterator() { return listFiles().iterator(); } public List<IFile> listFiles() { return listFiles(false); } public List<IFile> listAllFiles() { return listFiles(true); } private List<IFile> listFiles(boolean includeFilesInNestedSubdirs) { Map<String, ZipEntry> entriesByName = new LinkedHashMap<String, ZipEntry>(); for (ZipEntry entry : getAllEntries()) { if (ZipDirectory.isInDir(getNameInZip(), entry, includeFilesInNestedSubdirs)) { entriesByName.put(entry.getName(), entry); } } List<IFile> files = new ArrayList<IFile>(); for (ZipEntry ze : entriesByName.values()) { NestedZipDirectory parent = includeFilesInNestedSubdirs ? buildParent(ze, entriesByName) : this; if (ze.isDirectory()) files.add(new NestedZipDirectory(archive, ze, parent, cache)); else files.add(new NestedZipFile(archive, ze, parent, cache)); } return files; } private List<? extends ZipEntry> getAllEntries() { if (cache != null && !!!cache.isClosed()) { return Collections.list(cache.getZipFile().entries()); } else { ZipInputStream zis = null; try { zis = new ZipInputStream(archive.open()); List<ZipEntry> result = new ArrayList<ZipEntry>(); ZipEntry entry = zis.getNextEntry(); while (entry != null) { result.add(entry); entry = zis.getNextEntry(); } return result; } catch (IOException e) { throw new IORuntimeException("IOException reading nested ZipFile", e); } finally { IOUtils.close(zis); } } } private NestedZipDirectory buildParent(ZipEntry entry, Map<String,ZipEntry> entries) { NestedZipDirectory result = this; String path = entry.getName().substring(getNameInZip().length()); String[] segments = path.split("/"); if (segments != null && segments.length > 1) { StringBuilder entryPath = new StringBuilder(getNameInZip()); for (int i=0; i<segments.length-1; i++) { String p = segments[i]; entryPath.append(p).append("/"); ZipEntry ze = entries.get(entryPath.toString()); if (ze != null) { result = new NestedZipDirectory(archive, ze, result, cache); } else { result = new NestedZipDirectory(archive, entryPath.toString(), result, cache); } } } return result; } public IFile getFile(String name) { Map<String,ZipEntry> entries = new HashMap<String, ZipEntry>(); ZipEntry ze; if (cache != null && !!!cache.isClosed()) { ZipFile zip = cache.getZipFile(); String[] segments = name.split("/"); StringBuilder path = new StringBuilder(); for (String s : segments) { path.append(s).append('/'); ZipEntry p = zip.getEntry(path.toString()); if (p != null) entries.put(path.toString(), p); } ze = zip.getEntry(name); } else { ZipInputStream zis = null; try { zis = new ZipInputStream(archive.open()); ze = zis.getNextEntry(); while (ze != null && !!!ze.getName().equals(name)) { if (name.startsWith(ze.getName())) entries.put(ze.getName(), ze); ze = zis.getNextEntry(); } } catch (IOException e) { throw new IORuntimeException("IOException reading nested ZipFile", e); } finally { IOUtils.close(zis); } } if (ze != null) { NestedZipDirectory parent = buildParent(ze, entries); if (ze.isDirectory()) return new NestedZipDirectory(archive, ze, parent, cache); else return new NestedZipFile(archive, ze, parent, cache); } else { return null; } } public boolean isDirectory() { return true; } public InputStream open() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException(); } public boolean isFile() { return false; } public boolean isRoot() { return false; } public ICloseableDirectory toCloseable() { try { return new NestedCloseableDirectory(archive, this); } catch (IOException e) { throw new IORuntimeException("Exception while creating extracted version of nested zip file", e); } } }
7,904
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/ZipDirectory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.aries.util.IORuntimeException; import org.apache.aries.util.filesystem.ICloseableDirectory; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; /** * A directory in the zip. */ public class ZipDirectory extends ZipFileImpl implements IDirectory { /** The root of the zip FS. */ private final IDirectory root; private final boolean zipRoot; /** * Constructs a directory in the zip. * * @param zip1 the zip file. * @param entry1 the entry in the zip representing this dir. * @param parent the parent directory. */ public ZipDirectory(File zip1, ZipEntry entry1, ZipDirectory parent, ZipCloseableDirectory cache) { super(zip1, entry1, parent, cache); zipRoot = false; root = parent.getRoot(); } /** * This constructor creates the root of the zip. * @param fs * @param parent * @throws MalformedURLException */ public ZipDirectory(File fs, IDirectory parent) throws MalformedURLException { super(fs, parent); root = (parent == null) ? this : parent.getRoot(); zipRoot = true; } public ZipDirectory(ZipDirectory other, ZipCloseableDirectory cache) { super(other, cache); root = other.root; zipRoot = other.zipRoot; } public IFile getFile(String name) { IFile result = null; String entryName = isZipRoot() ? name : getNameInZip() + "/" + name; ZipEntry entryFile = getEntry(entryName); if (entryFile != null) { if (!!!entryFile.isDirectory()) { result = new ZipFileImpl(zip, entryFile, buildParent(entryFile), cache); } else { result = new ZipDirectory(zip, entryFile, buildParent(entryFile), cache); } } return result; } /** * This method builds the parent directory hierarchy for a file. * @param foundEntry * @return the parent of the entry. */ private ZipDirectory buildParent(ZipEntry foundEntry) { ZipDirectory result = this; String name = foundEntry.getName(); name = name.substring(getNameInZip().length()); String[] paths = name.split("/"); StringBuilder baseBuilderCrapThingToGetRoundFindBugs = new StringBuilder(getNameInZip()); if (!!!isZipRoot()) baseBuilderCrapThingToGetRoundFindBugs.append('/'); // Build 'result' as a chain of ZipDirectories. This will only work if java.util.ZipFile recognises every // directory in the chain as being a ZipEntry in its own right. outer: if (paths != null && paths.length > 1) { for (int i = 0; i < paths.length - 1; i++) { String path = paths[i]; baseBuilderCrapThingToGetRoundFindBugs.append(path); ZipEntry dirEntry = getEntry(baseBuilderCrapThingToGetRoundFindBugs.toString()); if (dirEntry == null) { result = this; break outer; } result = new ZipDirectory(zip, dirEntry, result, cache); baseBuilderCrapThingToGetRoundFindBugs.append('/'); } } return result; } public boolean isRoot() { return getParent() == null; } public List<IFile> listFiles() { return listFiles(false); } public List<IFile> listAllFiles() { return listFiles(true); } private List<IFile> listFiles(boolean includeFilesInNestedSubdirs) { List<IFile> files = new ArrayList<IFile>(); ZipFile z = openZipFile(); List<? extends ZipEntry> entries = Collections.list(z.entries()); for (ZipEntry possibleEntry : entries) { if (isInDir(getNameInZip(), possibleEntry, includeFilesInNestedSubdirs)) { ZipDirectory parent = includeFilesInNestedSubdirs ? buildParent(possibleEntry) : this; if (possibleEntry.isDirectory()) { files.add(new ZipDirectory(zip, possibleEntry, parent, cache)); } else { files.add(new ZipFileImpl(zip, possibleEntry, parent, cache)); } } } closeZipFile(z); return files; } /** * This method works out if the provided entry is inside this directory. It * returns false if it is not, or if it is in a sub-directory. * * @param parentDir * @param possibleEntry * @param allowSubDirs * @return true if it is in this directory. */ protected static boolean isInDir(String parentDir, ZipEntry possibleEntry, boolean allowSubDirs) { boolean result; String name = possibleEntry.getName(); if (name.endsWith("/")) name = name.substring(0, name.length() - 1); result = (name.startsWith(parentDir) && !!!name.equals(parentDir) && (allowSubDirs || name.substring(parentDir.length() + 1).indexOf('/') == -1)); return result; } public Iterator<IFile> iterator() { return listFiles().iterator(); } public IDirectory convert() { return this; } public boolean isDirectory() { return true; } public boolean isFile() { return false; } public InputStream open() { throw new UnsupportedOperationException(); } public IDirectory getRoot() { return root; } public boolean isZipRoot() { return zipRoot; } // Although we only delegate to our super class if we removed this Findbugs // would correctly point out that we add fields in this class, but do not // take them into account for the equals method. In fact this is not a problem // we do not care about the root when doing an equality check, but by including // an equals or hashCode in here we can clearly document that we did this // on purpose. Hence this comment. @Override public boolean equals(Object other) { return super.equals(other); } @Override public int hashCode() { return super.hashCode(); } private ZipEntry getEntry(String entryName) { ZipFile z = openZipFile(); ZipEntry entryFile = null; if (z != null) { entryFile = z.getEntry(entryName); closeZipFile(z); } return entryFile; } public ICloseableDirectory toCloseable() { try { return new ZipCloseableDirectory(zip, this); } catch (IOException e) { throw new IORuntimeException("IOException opening zip file: " + this, e); } } }
7,905
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/InputStreamClosableDirectory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import org.apache.aries.util.filesystem.IDirectory; public class InputStreamClosableDirectory extends CloseableDirectory { private final File tempFile; public InputStreamClosableDirectory(IDirectory delegate, File temp) { super(delegate); tempFile = temp; } @Override protected void cleanup() { tempFile.delete(); } }
7,906
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/ZipFileImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import org.apache.aries.util.IORuntimeException; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; /** * An implementation of IFile that represents a file entry in a zip. */ public class ZipFileImpl implements IFile { /** The name of the file */ private String name; /** The size of the file */ private final long size; /** The last time the file was updated */ private final long lastModified; /** The zip file this is contained in */ protected final File zip; /** The entry in the zip this IFile represents */ protected final ZipEntry entry; /** The parent directory */ private final IDirectory parent; /** The URL of the zip file we are looking inside of */ private final String url; /** The path of the zip archive to the VFS root */ private final String zipPathToRoot; /** The closeable directory that caches the open ZipFile */ protected final ZipCloseableDirectory cache; /** * This constructor is used to create a file entry within the zip. * * @param zip1 the zip file the entry is in. * @param entry1 the entry this IFile represents. * @param parent1 the parent directory. */ public ZipFileImpl(File zip1, ZipEntry entry1, ZipDirectory parent1, ZipCloseableDirectory cache) { this.zip = zip1; this.entry = entry1; this.zipPathToRoot = parent1.getZipPathToRoot(); name = zipPathToRoot + entry1.getName(); if (entry1.isDirectory()) name = name.substring(0, name.length() - 1); lastModified = entry1.getTime(); size = entry1.getSize(); url = ((ZipFileImpl)parent1).url; this.parent = parent1; this.cache = cache; } /** * This is called to construct the root directory of the zip. * * @param zip1 the zip file this represents. * @param parent * @throws MalformedURLException */ protected ZipFileImpl(File zip1, IDirectory parent) throws MalformedURLException { this.zip = zip1; this.entry = null; if (parent == null) { name = ""; zipPathToRoot = ""; this.parent = null; } else { this.parent = parent; name = parent.getName() + "/" + zip1.getName(); zipPathToRoot = name+"/"; } lastModified = zip1.lastModified(); size = zip1.length(); url = zip1.toURI().toURL().toExternalForm(); this.cache = null; } public ZipFileImpl(ZipFileImpl other, ZipCloseableDirectory cache) { name = other.name; size = other.size; lastModified = other.lastModified; zip = other.zip; entry = other.entry; parent = other.parent; url = other.url; zipPathToRoot = other.zipPathToRoot; this.cache = cache; } /** * Obtain the path of the zip file to the VFS root */ public String getZipPathToRoot() { return zipPathToRoot; } public IDirectory convert() { return null; } public IDirectory convertNested() { if (isDirectory()) return convert(); else if (FileSystemImpl.isValidZip(this)) return new NestedZipDirectory(this); else return null; } public long getLastModified() { return lastModified; } public String getName() { return name; } public String getNameInZip() { if (entry == null) return ""; else { String name = entry.getName(); if (isDirectory()) return name.substring(0, name.length()-1); else return name; } } public IDirectory getParent() { return parent; } public long getSize() { return size; } public boolean isDirectory() { return false; } public boolean isFile() { return true; } public InputStream open() throws IOException { InputStream is = new SpecialZipInputStream(entry); return is; } public IDirectory getRoot() { return parent.getRoot(); } public URL toURL() throws MalformedURLException { URL result; if(name.equals(zipPathToRoot)) result = new URL(url); else { String entryURL = "jar:" + url + "!/"; if(entry != null) entryURL += entry.getName(); else { entryURL += name.substring(zipPathToRoot.length()); } result = new URL(entryURL); } return result; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() == getClass()) { return toString().equals(obj.toString()); } return false; } @Override public int hashCode() { return toString().hashCode(); } @Override public String toString() { if (name != null && name.length() != 0) return url.substring(5)+ "/" + name; else return url.substring(5); } ZipFile openZipFile(){ ZipFile z = null; if (cache != null && !!!cache.isClosed()) { z = cache.getZipFile(); } else { try { z = new ZipFile(zip); } catch (IOException e) { throw new IORuntimeException("IOException in ZipFileImpl.openZipFile", e); } } return z; } void closeZipFile(ZipFile z){ if (cache != null && cache.getZipFile() == z) { // do nothing } else { try{ z.close(); } catch (IOException e) { throw new IORuntimeException("IOException in ZipFileImpl.closeZipFile", e); } } } /** * A simple class to delegate to the InputStream of the constructor * and to call close on the zipFile when we close the stream. * */ private class SpecialZipInputStream extends InputStream{ private ZipFile zipFile; private InputStream is; public SpecialZipInputStream(ZipEntry anEntry){ try{ this.zipFile = openZipFile(); this.is = zipFile.getInputStream(anEntry); } catch (ZipException e) { throw new IORuntimeException("ZipException in SpecialZipInputStream()", e); } catch (IOException e) { throw new IORuntimeException("IOException in SpecialZipInputStream()", e); } } @Override public int read(byte[] b) throws IOException { return is.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } @Override public int read() throws IOException { return is.read(); } @Override public void close() throws IOException{ //call close on the input stream, probably does nothing is.close(); //call close on the zip file, important for tidying up closeZipFile(zipFile); } } }
7,907
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/FileSystemImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import org.apache.aries.util.IORuntimeException; import org.apache.aries.util.filesystem.ICloseableDirectory; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; import org.apache.aries.util.io.IOUtils; public class FileSystemImpl { /** * This method gets the IDirectory that represents the root of a virtual file * system. The provided file can either identify a directory, or a zip file. * * @param fs the zip file. * @return the root of the virtual FS. */ public static IDirectory getFSRoot(File fs, IDirectory parent) { IDirectory dir = null; if (fs.exists()) { if (fs.isDirectory()) { dir = new DirectoryImpl(fs, fs); } else if (fs.isFile() && isValidZip(fs)) { try { dir = new ZipDirectory(fs, parent); } catch (IOException e) { throw new IORuntimeException("IOException in IDirectory.getFSRoot", e); } } } else { throw new IORuntimeException("File not found in IDirectory.getFSRoot", new FileNotFoundException(fs.getPath())); } return dir; } /** * Check whether a file is actually a valid zip * @param zip * @return */ public static boolean isValidZip(File zip) { try { ZipFile zf = new ZipFile(zip); zf.close(); return true; } catch (IOException e) { throw new IORuntimeException("Not a valid zip: "+zip, e); } } /** * Check whether a file is actually a valid zip * @param zip * @return */ public static boolean isValidZip(IFile zip) { ZipInputStream zis = null; try { // just opening the stream ain't enough, we have to check the first entry zis = new ZipInputStream(zip.open()); return zis.getNextEntry() != null; } catch (IOException e) { throw new IORuntimeException("Not a valid zip: "+zip, e); } finally { IOUtils.close(zis); } } public static ICloseableDirectory getFSRoot(InputStream is) { File tempFile = null; try { tempFile = File.createTempFile("inputStreamExtract", ".zip"); } catch (IOException e1) { throw new IORuntimeException("IOException in IDirectory.getFSRoot", e1); } FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); IOUtils.copy(is, fos); } catch (IOException e) { return null; } finally { IOUtils.close(fos); } IDirectory dir = getFSRoot(tempFile, null); if(dir == null) return null; else return new InputStreamClosableDirectory(dir, tempFile); } }
7,908
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem
Create_ds/aries/util/src/main/java/org/apache/aries/util/filesystem/impl/FileImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.filesystem.impl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import org.apache.aries.util.IORuntimeException; import org.apache.aries.util.filesystem.IDirectory; import org.apache.aries.util.filesystem.IFile; /** * An implementation of IFile that represents a java.io.File. */ public class FileImpl implements IFile { /** The name of the root directory of the file system */ protected String rootDir; /** This file in the file system */ protected File file; /** The root File in the file system */ protected File rootDirFile; /** The name of this file in the vFS */ private String name; /** * @param f this file. * @param rootFile the root of the vFS. */ public FileImpl(File f, File rootFile) { file = f; this.rootDirFile = rootFile; rootDir = rootFile.getAbsolutePath(); if (f.equals(rootFile)) name = ""; else name = file.getAbsolutePath().substring(rootDir.length() + 1).replace('\\', '/'); } public IDirectory convert() { return null; } public long getLastModified() { long result = file.lastModified(); return result; } public String getName() { return name; } public IDirectory getParent() { IDirectory parent = new DirectoryImpl(file.getParentFile(), rootDirFile); return parent; } public long getSize() { long size = file.length(); return size; } public boolean isDirectory() { boolean result = file.isDirectory(); return result; } public boolean isFile() { boolean result = file.isFile(); return result; } public InputStream open() throws IOException { InputStream is = new FileInputStream(file); return is; } public IDirectory getRoot() { IDirectory root = new DirectoryImpl(rootDirFile, rootDirFile); return root; } public URL toURL() throws MalformedURLException { URL result = file.toURI().toURL(); return result; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() == getClass()) { return file.equals(((FileImpl)obj).file); } return false; } @Override public int hashCode() { return file.hashCode(); } @Override public String toString() { return file.getAbsolutePath(); } public IDirectory convertNested() { if (isDirectory()) { return convert(); } else { try { return FileSystemImpl.getFSRoot(file, getParent()); } catch (IORuntimeException e) { return null; } } } }
7,909
0
Create_ds/aries/util/src/main/java/org/apache/aries/util
Create_ds/aries/util/src/main/java/org/apache/aries/util/log/Logger.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.log; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogService; import org.osgi.util.tracker.ServiceTracker; // Note this file originated in the JMX subproject. /** * <p>This <tt>Logger</tt> class represents ServiceTracker for LogService. * It provides a simple mechanism for interacting with the log service. * * @see org.osgi.service.log.LogService * @see org.osgi.util.tracker.ServiceTracker */ @SuppressWarnings({"rawtypes", "unchecked"}) public class Logger extends ServiceTracker implements LogService { /** * Constructs new Logger(ServiceTracker for LogService). * * @param context bundle context. */ public Logger(BundleContext context) { super(context, LogService.class.getName(), null); } /** * @see org.osgi.service.log.LogService#log(int, java.lang.String) */ public void log(int level, String message) { LogService logService = (LogService) getService(); if (logService != null) { logService.log(level, message); } } /** * @see org.osgi.service.log.LogService#log(int, java.lang.String, java.lang.Throwable) */ public void log(int level, String message, Throwable exception) { LogService logService = (LogService) getService(); if (logService != null) { logService.log(level, message, exception); } } /** * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String) */ public void log(ServiceReference ref, int level, String message) { LogService logService = (LogService) getService(); if (logService != null) { logService.log(ref, level, message); } } /** * @see org.osgi.service.log.LogService#log(org.osgi.framework.ServiceReference, int, java.lang.String, * java.lang.Throwable) */ public void log(ServiceReference ref, int level, String message, Throwable exception) { LogService logService = (LogService) getService(); if (logService != null) { logService.log(ref, level, message, exception); } } }
7,910
0
Create_ds/aries/util/src/main/java/org/apache/aries/util/service
Create_ds/aries/util/src/main/java/org/apache/aries/util/service/registry/ServicePair.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.util.service.registry; import java.security.AccessController; import java.security.PrivilegedAction; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; // TODO need to determine if this needs to be thread safe or not @SuppressWarnings({"rawtypes", "unchecked"}) public class ServicePair<T> { private BundleContext ctx; private ServiceReference ref; private T serviceObject; public ServicePair(BundleContext context, ServiceReference serviceRef) { ctx = context; ref = serviceRef; } public ServicePair(BundleContext context, ServiceReference serviceRef, T service) { ctx = context; ref = serviceRef; serviceObject = service; } public T get() { if (serviceObject == null && ref.getBundle() != null) { serviceObject = AccessController.doPrivileged(new PrivilegedAction<T>() { public T run() { return serviceObject = (T) ctx.getService(ref); } }); } return serviceObject; } public boolean isValid() { return (ref.getBundle() != null); } public void unget() { if (serviceObject != null) { ctx.ungetService(ref); serviceObject = null; } } public ServiceReference getReference() { return ref; } }
7,911
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushStreamBuilderImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; class PushStreamBuilderImpl<T, U extends BlockingQueue<PushEvent< ? extends T>>> extends AbstractBufferBuilder<PushStream<T>,T,U> implements PushStreamBuilder<T,U> { private final PushStreamProvider psp; private final PushEventSource<T> eventSource; private final Executor previousExecutor; private boolean unbuffered; PushStreamBuilderImpl(PushStreamProvider psp, Executor defaultExecutor, PushEventSource<T> eventSource) { this.psp = psp; this.previousExecutor = defaultExecutor; this.eventSource = eventSource; this.worker = defaultExecutor; } @Override public PushStreamBuilder<T,U> withBuffer(U queue) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withBuffer(queue); } @Override public PushStreamBuilder<T,U> withQueuePolicy( QueuePolicy<T,U> queuePolicy) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withQueuePolicy(queuePolicy); } @Override public PushStreamBuilder<T,U> withQueuePolicy( QueuePolicyOption queuePolicyOption) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withQueuePolicy( queuePolicyOption); } @Override public PushStreamBuilder<T,U> withPushbackPolicy( PushbackPolicy<T,U> pushbackPolicy) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withPushbackPolicy( pushbackPolicy); } @Override public PushStreamBuilder<T,U> withPushbackPolicy( PushbackPolicyOption pushbackPolicyOption, long time) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withPushbackPolicy( pushbackPolicyOption, time); } @Override public PushStreamBuilder<T,U> withParallelism(int parallelism) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withParallelism(parallelism); } @Override public PushStreamBuilder<T,U> withExecutor(Executor executor) { unbuffered = false; return (PushStreamBuilder<T,U>) super.withExecutor(executor); } @Override public PushStreamBuilder<T,U> unbuffered() { unbuffered = true; return this; } @Override public PushStream<T> create() { if (unbuffered) { return psp.createUnbufferedStream(eventSource, previousExecutor); } else { return psp.createStream(eventSource, concurrency, worker, buffer, bufferingPolicy, backPressure); } } }
7,912
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/QueuePolicyOption.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; /** * {@link QueuePolicyOption} provides a standard set of simple * {@link QueuePolicy} implementations. * * @see QueuePolicy */ public enum QueuePolicyOption { /** * Attempt to add the supplied event to the queue. If the queue is unable to * immediately accept the value then discard the value at the head of the * queue and try again. Repeat this process until the event is enqueued. */ DISCARD_OLDEST { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> QueuePolicy<T, U> getPolicy() { return (queue, event) -> { while (!queue.offer(event)) { queue.poll(); } }; } }, /** * Attempt to add the supplied event to the queue, blocking until the * enqueue is successful. */ BLOCK { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> QueuePolicy<T, U> getPolicy() { return (queue, event) -> { try { queue.put(event); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; } }, /** * Attempt to add the supplied event to the queue, throwing an exception if * the queue is full. */ FAIL { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> QueuePolicy<T, U> getPolicy() { return (queue, event) -> queue.add(event); } }; /** * @return a {@link QueuePolicy} implementation */ public abstract <T, U extends BlockingQueue<PushEvent<? extends T>>> QueuePolicy<T, U> getPolicy(); }
7,913
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/BufferBuilder.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; /** * Create a buffered section of a Push-based stream * * @param <R> The type of object being built * @param <T> The type of objects in the {@link PushEvent} * @param <U> The type of the Queue used in the user specified buffer */ public interface BufferBuilder<R, T, U extends BlockingQueue<PushEvent<? extends T>>> { /** * The BlockingQueue implementation to use as a buffer * * @param queue * @return this builder */ BufferBuilder<R, T, U> withBuffer(U queue); /** * Set the {@link QueuePolicy} of this Builder * * @param queuePolicy * @return this builder */ BufferBuilder<R,T,U> withQueuePolicy(QueuePolicy<T,U> queuePolicy); /** * Set the {@link QueuePolicy} of this Builder * * @param queuePolicyOption * @return this builder */ BufferBuilder<R, T, U> withQueuePolicy(QueuePolicyOption queuePolicyOption); /** * Set the {@link PushbackPolicy} of this builder * * @param pushbackPolicy * @return this builder */ BufferBuilder<R, T, U> withPushbackPolicy(PushbackPolicy<T, U> pushbackPolicy); /** * Set the {@link PushbackPolicy} of this builder * * @param pushbackPolicyOption * @param time * @return this builder */ BufferBuilder<R, T, U> withPushbackPolicy(PushbackPolicyOption pushbackPolicyOption, long time); /** * Set the maximum permitted number of concurrent event deliveries allowed * from this buffer * * @param parallelism * @return this builder */ BufferBuilder<R, T, U> withParallelism(int parallelism); /** * Set the {@link Executor} that should be used to deliver events from this * buffer * * @param executor * @return this builder */ BufferBuilder<R, T, U> withExecutor(Executor executor); /** * @return the object being built */ R create(); }
7,914
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushEventConsumer.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import org.osgi.annotation.versioning.ConsumerType; /** * An Async Event Consumer asynchronously receives Data events until it receives * either a Close or Error event. * * @param <T> * The type for the event payload */ @ConsumerType @FunctionalInterface public interface PushEventConsumer<T> { /** * If ABORT is used as return value, the sender should close the channel all * the way to the upstream source. The ABORT will not guarantee that no * more events are delivered since this is impossible in a concurrent * environment. The consumer should accept subsequent events and close/clean * up when the Close or Error event is received. * * Though ABORT has the value -1, any value less than 0 will act as an * abort. */ long ABORT = -1; /** * A 0 indicates that the consumer is willing to receive subsequent events * at full speeds. * * Any value more than 0 will indicate that the consumer is becoming * overloaded and wants a delay of the given milliseconds before the next * event is sent. This allows the consumer to pushback the event delivery * speed. */ long CONTINUE = 0; /** * Accept an event from a source. Events can be delivered on multiple * threads simultaneously. However, Close and Error events are the last * events received, no more events must be sent after them. * * @param event The event * @return less than 0 means abort, 0 means continue, more than 0 means * delay ms * @throws Exception to indicate that an error has occured and that no * further events should be delivered to this * {@link PushEventConsumer} */ long accept(PushEvent<? extends T> event) throws Exception; }
7,915
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushStream.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.time.Duration; import java.util.Collection; import java.util.Comparator; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; import org.osgi.annotation.versioning.ProviderType; import org.osgi.util.promise.Promise; /** * A Push Stream fulfills the same role as the Java 8 stream but it reverses the * control direction. The Java 8 stream is pull based and this is push based. A * Push Stream makes it possible to build a pipeline of transformations using a * builder kind of model. Just like streams, it provides a number of terminating * methods that will actually open the channel and perform the processing until * the channel is closed (The source sends a Close event). The results of the * processing will be send to a Promise, just like any error events. A stream * can be used multiple times. The Push Stream represents a pipeline. Upstream * is in the direction of the source, downstream is in the direction of the * terminating method. Events are sent downstream asynchronously with no * guarantee for ordering or concurrency. Methods are available to provide * serialization of the events and splitting in background threads. * * @param <T> The Payload type */ @ProviderType public interface PushStream<T> extends AutoCloseable { /** * Must be run after the channel is closed. This handler will run after the * downstream methods have processed the close event and before the upstream * methods have closed. * * @param closeHandler Will be called on close * @return This stream */ PushStream<T> onClose(Runnable closeHandler); /** * Must be run after the channel is closed. This handler will run after the * downstream methods have processed the close event and before the upstream * methods have closed. * * @param closeHandler Will be called on close * @return This stream */ PushStream<T> onError(Consumer< ? super Throwable> closeHandler); /** * Only pass events downstream when the predicate tests true. * * @param predicate The predicate that is tested (not null) * @return Builder style (can be a new or the same object) */ PushStream<T> filter(Predicate< ? super T> predicate); /** * Map a payload value. * * @param mapper The map function * @return Builder style (can be a new or the same object) */ <R> PushStream<R> map(Function< ? super T, ? extends R> mapper); /** * Flat map the payload value (turn one event into 0..n events of * potentially another type). * * @param mapper The flat map function * @return Builder style (can be a new or the same object) */ <R> PushStream<R> flatMap( Function< ? super T, ? extends PushStream< ? extends R>> mapper); /** * Remove any duplicates. Notice that this can be expensive in a large * stream since it must track previous payloads. * * @return Builder style (can be a new or the same object) */ PushStream<T> distinct(); /** * Sorted the elements, assuming that T extends Comparable. This is of * course expensive for large or infinite streams since it requires * buffering the stream until close. * * @return Builder style (can be a new or the same object) */ PushStream<T> sorted(); /** * Sorted the elements with the given comparator. This is of course * expensive for large or infinite streams since it requires buffering the * stream until close. * * @param comparator * @return Builder style (can be a new or the same object) */ PushStream<T> sorted(Comparator< ? super T> comparator); /** * Automatically close the channel after the maxSize number of elements is * received. * * @param maxSize Maximum number of elements has been received * @return Builder style (can be a new or the same object) */ PushStream<T> limit(long maxSize); /** * Skip a number of events in the channel. * * @param n number of elements to skip * @return Builder style (can be a new or the same object) */ PushStream<T> skip(long n); /** * Execute the downstream events in up to n background threads. If more * requests are outstanding apply delay * nr of delayed threads back * pressure. A downstream channel that is closed or throws an exception will * cause all execution to cease and the stream to close * * @param n number of simultaneous background threads to use * @param delay Nr of ms/thread that is queued back pressure * @param e an executor to use for the background threads. * @return Builder style (can be a new or the same object) * @throws IllegalArgumentException if the number of threads is < 1 or the * delay is < 0 * @throws NullPointerException if the Executor is null */ PushStream<T> fork(int n, int delay, Executor e) throws IllegalArgumentException, NullPointerException; /** * Buffer the events in a queue using default values for the queue size and * other behaviours. Buffered work will be processed asynchronously in the * rest of the chain. Buffering also blocks the transmission of back * pressure to previous elements in the chain, although back pressure is * honoured by the buffer. * <p> * Buffers are useful for "bursty" event sources which produce a number of * events close together, then none for some time. These bursts can * sometimes overwhelm downstream event consumers. Buffering will not, * however, protect downstream components from a source which produces * events faster than they can be consumed. For fast sources * {@link #filter(Predicate)} and {@link #coalesce(int, Function)} * {@link #fork(int, int, Executor)} are better choices. * * @return Builder style (can be a new or the same object) */ PushStream<T> buffer(); /** * Build a buffer to enqueue events in a queue using custom values for the * queue size and other behaviours. Buffered work will be processed * asynchronously in the rest of the chain. Buffering also blocks the * transmission of back pressure to previous elements in the chain, although * back pressure is honoured by the buffer. * <p> * Buffers are useful for "bursty" event sources which produce a number of * events close together, then none for some time. These bursts can * sometimes overwhelm downstream event consumers. Buffering will not, * however, protect downstream components from a source which produces * events faster than they can be consumed. For fast sources * {@link #filter(Predicate)} and {@link #coalesce(int, Function)} * {@link #fork(int, int, Executor)} are better choices. * <p> * Buffers are also useful as "circuit breakers" in the pipeline. If a * {@link QueuePolicyOption#FAIL} is used then a full buffer will trigger * the stream to close, preventing an event storm from reaching the client. * * @param parallelism * @param executor * @param queue * @param queuePolicy * @param pushbackPolicy * @return Builder style (can be a new or the same object) */ <U extends BlockingQueue<PushEvent< ? extends T>>> PushStreamBuilder<T,U> buildBuffer(); /** * Merge in the events from another source. The resulting channel is not * closed until this channel and the channel from the source are closed. * * @param source The source to merge in. * @return Builder style (can be a new or the same object) */ PushStream<T> merge(PushEventSource< ? extends T> source); /** * Merge in the events from another PushStream. The resulting channel is not * closed until this channel and the channel from the source are closed. * * @param source The source to merge in. * @return Builder style (can be a new or the same object) */ PushStream<T> merge(PushStream< ? extends T> source); /** * Split the events to different streams based on a predicate. If the * predicate is true, the event is dispatched to that channel on the same * position. All predicates are tested for every event. * <p> * This method differs from other methods of AsyncStream in three * significant ways: * <ul> * <li>The return value contains multiple streams.</li> * <li>This stream will only close when all of these child streams have * closed.</li> * <li>Event delivery is made to all open children that accept the event. * </li> * </ul> * * @param predicates the predicates to test * @return streams that map to the predicates */ @SuppressWarnings("unchecked") PushStream<T>[] split(Predicate< ? super T>... predicates); /** * Ensure that any events are delivered sequentially. That is, no * overlapping calls downstream. This can be used to turn a forked stream * (where for example a heavy conversion is done in multiple threads) back * into a sequential stream so a reduce is simple to do. * * @return Builder style (can be a new or the same object) */ PushStream<T> sequential(); /** * Coalesces a number of events into a new type of event. The input events * are forwarded to a accumulator function. This function returns an * Optional. If the optional is present, it's value is send downstream, * otherwise it is ignored. * * @param f * @return Builder style (can be a new or the same object) */ <R> PushStream<R> coalesce(Function< ? super T,Optional<R>> f); /** * Coalesces a number of events into a new type of event. A fixed number of * input events are forwarded to a accumulator function. This function * returns new event data to be forwarded on. * * @param count * @param f * @return Builder style (can be a new or the same object) */ public <R> PushStream<R> coalesce(int count, Function<Collection<T>,R> f); /** * Coalesces a number of events into a new type of event. A variable number * of input events are forwarded to a accumulator function. The number of * events to be forwarded is determined by calling the count function. The * accumulator function then returns new event data to be forwarded on. * * @param count * @param f * @return Builder style (can be a new or the same object) */ public <R> PushStream<R> coalesce(IntSupplier count, Function<Collection<T>,R> f); /** * Buffers a number of events over a fixed time interval and then forwards * the events to an accumulator function. This function returns new event * data to be forwarded on. Note that: * <ul> * <li>The collection forwarded to the accumulator function will be empty if * no events arrived during the time interval.</li> * <li>The accumulator function will be run and the forwarded event * delivered as a different task, (and therefore potentially on a different * thread) from the one that delivered the event to this {@link PushStream}. * </li> * <li>Due to the buffering and asynchronous delivery required, this method * prevents the propagation of back-pressure to earlier stages</li> * </ul> * * @param d * @param f * @return Builder style (can be a new or the same object) */ <R> PushStream<R> window(Duration d, Function<Collection<T>,R> f); /** * Buffers a number of events over a fixed time interval and then forwards * the events to an accumulator function. This function returns new event * data to be forwarded on. Note that: * <ul> * <li>The collection forwarded to the accumulator function will be empty if * no events arrived during the time interval.</li> * <li>The accumulator function will be run and the forwarded event * delivered by a task given to the supplied executor.</li> * <li>Due to the buffering and asynchronous delivery required, this method * prevents the propagation of back-pressure to earlier stages</li> * </ul> * * @param d * @param executor * @param f * @return Builder style (can be a new or the same object) */ <R> PushStream<R> window(Duration d, Executor executor, Function<Collection<T>,R> f); /** * Buffers a number of events over a variable time interval and then * forwards the events to an accumulator function. The length of time over * which events are buffered is determined by the time function. A maximum * number of events can also be requested, if this number of events is * reached then the accumulator will be called early. The accumulator * function returns new event data to be forwarded on. It is also given the * length of time for which the buffer accumulated data. This may be less * than the requested interval if the buffer reached the maximum number of * requested events early. Note that: * <ul> * <li>The collection forwarded to the accumulator function will be empty if * no events arrived during the time interval.</li> * <li>The accumulator function will be run and the forwarded event * delivered as a different task, (and therefore potentially on a different * thread) from the one that delivered the event to this {@link PushStream}. * </li> * <li>Due to the buffering and asynchronous delivery required, this method * prevents the propagation of back-pressure to earlier stages</li> * <li>If the window finishes by hitting the maximum number of events then * the remaining time in the window will be applied as back-pressure to the * previous stage, attempting to slow the producer to the expected windowing * threshold.</li> * </ul> * * @param timeSupplier * @param maxEvents * @param f * @return Builder style (can be a new or the same object) */ <R> PushStream<R> window(Supplier<Duration> timeSupplier, IntSupplier maxEvents, BiFunction<Long,Collection<T>,R> f); /** * Buffers a number of events over a variable time interval and then * forwards the events to an accumulator function. The length of time over * which events are buffered is determined by the time function. A maximum * number of events can also be requested, if this number of events is * reached then the accumulator will be called early. The accumulator * function returns new event data to be forwarded on. It is also given the * length of time for which the buffer accumulated data. This may be less * than the requested interval if the buffer reached the maximum number of * requested events early. Note that: * <ul> * <li>The collection forwarded to the accumulator function will be empty if * no events arrived during the time interval.</li> * <li>The accumulator function will be run and the forwarded event * delivered as a different task, (and therefore potentially on a different * thread) from the one that delivered the event to this {@link PushStream}. * </li> * <li>If the window finishes by hitting the maximum number of events then * the remaining time in the window will be applied as back-pressure to the * previous stage, attempting to slow the producer to the expected windowing * threshold.</li> * </ul> * * @param timeSupplier * @param maxEvents * @param executor * @param f * @return Builder style (can be a new or the same object) */ <R> PushStream<R> window(Supplier<Duration> timeSupplier, IntSupplier maxEvents, Executor executor, BiFunction<Long,Collection<T>,R> f); /** * Execute the action for each event received until the channel is closed. * This is a terminating method, the returned promise is resolved when the * channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param action The action to perform * @return A promise that is resolved when the channel closes. */ Promise<Void> forEach(Consumer< ? super T> action); /** * Collect the payloads in an Object array after the channel is closed. This * is a terminating method, the returned promise is resolved when the * channel is closed. * <p> * This is a <strong>terminal operation</strong> * * @return A promise that is resolved with all the payloads received over * the channel */ Promise<Object[]> toArray(); /** * Collect the payloads in an Object array after the channel is closed. This * is a terminating method, the returned promise is resolved when the * channel is closed. The type of the array is handled by the caller using a * generator function that gets the length of the desired array. * <p> * This is a <strong>terminal operation</strong> * * @param generator * @return A promise that is resolved with all the payloads received over * the channel */ <A extends T> Promise<A[]> toArray(IntFunction<A[]> generator); /** * Standard reduce, see Stream. The returned promise will be resolved when * the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param identity The identity/begin value * @param accumulator The accumulator * @return A */ Promise<T> reduce(T identity, BinaryOperator<T> accumulator); /** * Standard reduce without identity, so the return is an Optional. The * returned promise will be resolved when the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param accumulator The accumulator * @return an Optional */ Promise<Optional<T>> reduce(BinaryOperator<T> accumulator); /** * Standard reduce with identity, accumulator and combiner. The returned * promise will be resolved when the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param identity * @param accumulator * @param combiner combines to U's into one U (e.g. how combine two lists) * @return The promise */ <U> Promise<U> reduce(U identity, BiFunction<U, ? super T,U> accumulator, BinaryOperator<U> combiner); /** * See Stream. Will resolve onces the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param collector * @return A Promise representing the collected results */ <R, A> Promise<R> collect(Collector< ? super T,A,R> collector); /** * See Stream. Will resolve onces the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param comparator * @return A Promise representing the minimum value, or null if no values * are seen before the end of the stream */ Promise<Optional<T>> min(Comparator< ? super T> comparator); /** * See Stream. Will resolve onces the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @param comparator * @return A Promise representing the maximum value, or null if no values * are seen before the end of the stream */ Promise<Optional<T>> max(Comparator< ? super T> comparator); /** * See Stream. Will resolve onces the channel closes. * <p> * This is a <strong>terminal operation</strong> * * @return A Promise representing the number of values in the stream */ Promise<Long> count(); /** * Close the channel and resolve the promise with true when the predicate * matches a payload. If the channel is closed before the predicate matches, * the promise is resolved with false. * <p> * This is a <strong>short circuiting terminal operation</strong> * * @param predicate * @return A Promise that will resolve when an event matches the predicate, * or the end of the stream is reached */ Promise<Boolean> anyMatch(Predicate< ? super T> predicate); /** * Closes the channel and resolve the promise with false when the predicate * does not matches a pay load.If the channel is closed before, the promise * is resolved with true. * <p> * This is a <strong>short circuiting terminal operation</strong> * * @param predicate * @return A Promise that will resolve when an event fails to match the * predicate, or the end of the stream is reached */ Promise<Boolean> allMatch(Predicate< ? super T> predicate); /** * Closes the channel and resolve the promise with false when the predicate * matches any pay load. If the channel is closed before, the promise is * resolved with true. * <p> * This is a <strong>short circuiting terminal operation</strong> * * @param predicate * @return A Promise that will resolve when an event matches the predicate, * or the end of the stream is reached */ Promise<Boolean> noneMatch(Predicate< ? super T> predicate); /** * Close the channel and resolve the promise with the first element. If the * channel is closed before, the Optional will have no value. * * @return a promise */ Promise<Optional<T>> findFirst(); /** * Close the channel and resolve the promise with the first element. If the * channel is closed before, the Optional will have no value. * <p> * This is a <strong>terminal operation</strong> * * @return a promise */ Promise<Optional<T>> findAny(); /** * Pass on each event to another consumer until the stream is closed. * <p> * This is a <strong>terminal operation</strong> * * @param action * @return a promise */ Promise<Long> forEachEvent(PushEventConsumer< ? super T> action); }
7,916
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushbackPolicy.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import org.osgi.annotation.versioning.ConsumerType; /** * A {@link PushbackPolicy} is used to calculate how much back pressure to apply * based on the current buffer. The {@link PushbackPolicy} will be called after * an event has been queued, and the returned value will be used as back * pressure. * * @see PushbackPolicyOption * * * @param <T> The type of the data * @param <U> The type of the queue */ @ConsumerType @FunctionalInterface public interface PushbackPolicy<T, U extends BlockingQueue<PushEvent<? extends T>>> { /** * Given the current state of the queue, determine the level of back * pressure that should be applied * * @param queue * @return a back pressure value in nanoseconds * @throws Exception */ public long pushback(U queue) throws Exception; }
7,917
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushStreamProvider.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.aries.pushstream.AbstractPushStreamImpl.State.CLOSED; import static org.osgi.util.pushstream.PushEvent.data; import static org.osgi.util.pushstream.PushEvent.error; import static org.osgi.util.pushstream.PushbackPolicyOption.LINEAR; import static org.osgi.util.pushstream.QueuePolicyOption.FAIL; import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; import java.util.stream.Stream; import org.apache.aries.pushstream.BufferedPushStreamImpl; import org.apache.aries.pushstream.SimplePushEventSourceImpl; import org.apache.aries.pushstream.UnbufferedPushStreamImpl; /** * A factory for {@link PushStream} instances, and utility methods for handling * {@link PushEventSource}s and {@link PushEventConsumer}s */ public final class PushStreamProvider { private final Lock lock = new ReentrantLock(true); private int schedulerReferences; private ScheduledExecutorService scheduler; private ScheduledExecutorService acquireScheduler() { try { lock.lockInterruptibly(); try { schedulerReferences += 1; if (schedulerReferences == 1) { scheduler = Executors.newSingleThreadScheduledExecutor(); } return scheduler; } finally { lock.unlock(); } } catch (InterruptedException e) { throw new IllegalStateException("Unable to acquire the Scheduler", e); } } private void releaseScheduler() { try { lock.lockInterruptibly(); try { schedulerReferences -= 1; if (schedulerReferences == 0) { scheduler.shutdown(); scheduler = null; } } finally { lock.unlock(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Create a stream with the default configured buffer, executor size, queue, * queue policy and pushback policy. This is equivalent to calling * * <code> * buildStream(source).create(); * </code> * * <p> * This stream will be buffered from the event producer, and will honour * back pressure even if the source does not. * * <p> * Buffered streams are useful for "bursty" event sources which produce a * number of events close together, then none for some time. These bursts * can sometimes overwhelm downstream processors. Buffering will not, * however, protect downstream components from a source which produces * events faster (on average) than they can be consumed. * * <p> * Event delivery will not begin until a terminal operation is reached on * the chain of AsyncStreams. Once a terminal operation is reached the * stream will be connected to the event source. * * @param eventSource * @return A {@link PushStream} with a default initial buffer */ public <T> PushStream<T> createStream(PushEventSource<T> eventSource) { return createStream(eventSource, 1, null, new ArrayBlockingQueue<>(32), FAIL.getPolicy(), LINEAR.getPolicy(1000)); } /** * Builds a push stream with custom configuration. * * <p> * * The resulting {@link PushStream} may be buffered or unbuffered depending * on how it is configured. * * @param eventSource The source of the events * * @return A {@link PushStreamBuilder} for the stream */ public <T, U extends BlockingQueue<PushEvent< ? extends T>>> PushStreamBuilder<T,U> buildStream( PushEventSource<T> eventSource) { return new PushStreamBuilderImpl<T,U>(this, null, eventSource); } @SuppressWarnings({ "rawtypes", "unchecked" }) <T, U extends BlockingQueue<PushEvent< ? extends T>>> PushStream<T> createStream( PushEventSource<T> eventSource, int parallelism, Executor executor, U queue, QueuePolicy<T,U> queuePolicy, PushbackPolicy<T,U> pushbackPolicy) { if (eventSource == null) { throw new NullPointerException("There is no source of events"); } if (parallelism < 0) { throw new IllegalArgumentException( "The supplied parallelism cannot be less than zero. It was " + parallelism); } else if (parallelism == 0) { parallelism = 1; } boolean closeExecutorOnClose; Executor toUse; if (executor == null) { toUse = Executors.newFixedThreadPool(parallelism); closeExecutorOnClose = true; } else { toUse = executor; closeExecutorOnClose = false; } if (queue == null) { queue = (U) new ArrayBlockingQueue(32); } if (queuePolicy == null) { queuePolicy = FAIL.getPolicy(); } if (pushbackPolicy == null) { pushbackPolicy = LINEAR.getPolicy(1000); } @SuppressWarnings("resource") PushStream<T> stream = new BufferedPushStreamImpl<>(this, acquireScheduler(), queue, parallelism, toUse, queuePolicy, pushbackPolicy, aec -> { try { return eventSource.open(aec); } catch (Exception e) { throw new RuntimeException( "Unable to connect to event source", e); } }); stream = stream.onClose(() -> { if (closeExecutorOnClose) { ((ExecutorService) toUse).shutdown(); } releaseScheduler(); }).map(Function.identity()); return stream; } <T> PushStream<T> createUnbufferedStream(PushEventSource<T> eventSource, Executor executor) { boolean closeExecutorOnClose; Executor toUse; if (executor == null) { toUse = Executors.newFixedThreadPool(2); closeExecutorOnClose = true; } else { toUse = executor; closeExecutorOnClose = false; } @SuppressWarnings("resource") PushStream<T> stream = new UnbufferedPushStreamImpl<>(this, toUse, acquireScheduler(), aec -> { try { return eventSource.open(aec); } catch (Exception e) { throw new RuntimeException( "Unable to connect to event source", e); } }); stream = stream.onClose(() -> { if (closeExecutorOnClose) { ((ExecutorService) toUse).shutdown(); } releaseScheduler(); }).map(Function.identity()); return stream; } /** * Convert an {@link PushStream} into an {@link PushEventSource}. The first * call to {@link PushEventSource#open(PushEventConsumer)} will begin event * processing. * * The {@link PushEventSource} will remain active until the backing stream * is closed, and permits multiple consumers to * {@link PushEventSource#open(PushEventConsumer)} it. * * This is equivalent to: <code> * buildEventSourceFromStream(stream).create(); * </code> * * @param stream * @return a {@link PushEventSource} backed by the {@link PushStream} */ public <T> PushEventSource<T> createEventSourceFromStream( PushStream<T> stream) { return buildEventSourceFromStream(stream).create(); } /** * Convert an {@link PushStream} into an {@link PushEventSource}. The first * call to {@link PushEventSource#open(PushEventConsumer)} will begin event * processing. * * The {@link PushEventSource} will remain active until the backing stream * is closed, and permits multiple consumers to * {@link PushEventSource#open(PushEventConsumer)} it. * * @param stream * * @return a {@link PushEventSource} backed by the {@link PushStream} */ public <T, U extends BlockingQueue<PushEvent< ? extends T>>> BufferBuilder<PushEventSource<T>,T,U> buildEventSourceFromStream( PushStream<T> stream) { return new AbstractBufferBuilder<PushEventSource<T>,T,U>() { @Override public PushEventSource<T> create() { SimplePushEventSource<T> spes = createSimplePushEventSource( concurrency, worker, buffer, bufferingPolicy, () -> { try { stream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }); spes.connectPromise() .then(p -> stream.forEach(t -> spes.publish(t)) .onResolve(() -> spes.close())); return spes; } }; } /** * Create a {@link SimplePushEventSource} with the supplied type and default * buffering behaviours. The SimplePushEventSource will respond to back * pressure requests from the consumers connected to it. * * This is equivalent to: <code> * buildSimpleEventSource(type).create(); * </code> * * @param type * @return a {@link SimplePushEventSource} */ public <T> SimplePushEventSource<T> createSimpleEventSource(Class<T> type) { return createSimplePushEventSource(1, null, new ArrayBlockingQueue<>(32), FAIL.getPolicy(), () -> { /* Nothing else to do */ }); } /** * * Build a {@link SimplePushEventSource} with the supplied type and custom * buffering behaviours. The SimplePushEventSource will respond to back * pressure requests from the consumers connected to it. * * @param type * * @return a {@link SimplePushEventSource} */ public <T, U extends BlockingQueue<PushEvent< ? extends T>>> BufferBuilder<SimplePushEventSource<T>,T,U> buildSimpleEventSource( Class<T> type) { return new AbstractBufferBuilder<SimplePushEventSource<T>,T,U>() { @Override public SimplePushEventSource<T> create() { return createSimplePushEventSource(concurrency, worker, buffer, bufferingPolicy, () -> { /* Nothing else to do */ }); } }; } @SuppressWarnings({ "unchecked", "rawtypes" }) <T, U extends BlockingQueue<PushEvent< ? extends T>>> SimplePushEventSource<T> createSimplePushEventSource( int parallelism, Executor executor, U queue, QueuePolicy<T,U> queuePolicy, Runnable onClose) { if (parallelism < 0) { throw new IllegalArgumentException( "The supplied parallelism cannot be less than zero. It was " + parallelism); } else if (parallelism == 0) { parallelism = 1; } boolean closeExecutorOnClose; Executor toUse; if (executor == null) { toUse = Executors.newFixedThreadPool(2); closeExecutorOnClose = true; } else { toUse = executor; closeExecutorOnClose = false; } if (queue == null) { queue = (U) new ArrayBlockingQueue(32); } if (queuePolicy == null) { queuePolicy = FAIL.getPolicy(); } SimplePushEventSourceImpl<T,U> spes = new SimplePushEventSourceImpl<T,U>( toUse, acquireScheduler(), queuePolicy, queue, parallelism, () -> { try { onClose.run(); } catch (Exception e) { // TODO log this? } if (closeExecutorOnClose) { ((ExecutorService) toUse).shutdown(); } releaseScheduler(); }); return spes; } /** * Create a buffered {@link PushEventConsumer} with the default configured * buffer, executor size, queue, queue policy and pushback policy. This is * equivalent to calling * * <code> * buildBufferedConsumer(delegate).create(); * </code> * * <p> * The returned consumer will be buffered from the event source, and will * honour back pressure requests from its delegate even if the event source * does not. * * <p> * Buffered consumers are useful for "bursty" event sources which produce a * number of events close together, then none for some time. These bursts * can sometimes overwhelm the consumer. Buffering will not, however, * protect downstream components from a source which produces events faster * than they can be consumed. * * @param delegate * @return a {@link PushEventConsumer} with a buffer directly before it */ public <T> PushEventConsumer<T> createBufferedConsumer( PushEventConsumer<T> delegate) { return buildBufferedConsumer(delegate).create(); } /** * Build a buffered {@link PushEventConsumer} with custom configuration. * <p> * The returned consumer will be buffered from the event source, and will * honour back pressure requests from its delegate even if the event source * does not. * <p> * Buffered consumers are useful for "bursty" event sources which produce a * number of events close together, then none for some time. These bursts * can sometimes overwhelm the consumer. Buffering will not, however, * protect downstream components from a source which produces events faster * than they can be consumed. * <p> * Buffers are also useful as "circuit breakers". If a * {@link QueuePolicyOption#FAIL} is used then a full buffer will request * that the stream close, preventing an event storm from reaching the * client. * <p> * Note that this buffered consumer will close when it receives a terminal * event, or if the delegate returns negative backpressure. No further * events will be propagated after this time. * * @param delegate * @return a {@link PushEventConsumer} with a buffer directly before it */ public <T, U extends BlockingQueue<PushEvent< ? extends T>>> BufferBuilder<PushEventConsumer<T>,T,U> buildBufferedConsumer( PushEventConsumer<T> delegate) { return new AbstractBufferBuilder<PushEventConsumer<T>,T,U>() { @Override public PushEventConsumer<T> create() { PushEventPipe<T> pipe = new PushEventPipe<>(); createStream(pipe, concurrency, worker, buffer, bufferingPolicy, backPressure) .forEachEvent(delegate); return pipe; } }; } static final class PushEventPipe<T> implements PushEventConsumer<T>, PushEventSource<T> { volatile PushEventConsumer< ? super T> delegate; @Override public AutoCloseable open(PushEventConsumer< ? super T> pec) throws Exception { return () -> { /* Nothing else to do */ }; } @Override public long accept(PushEvent< ? extends T> event) throws Exception { return delegate.accept(event); } } /** * Create an Unbuffered {@link PushStream} from a Java {@link Stream} The * data from the stream will be pushed into the PushStream synchronously as * it is opened. This may make terminal operations blocking unless a buffer * has been added to the {@link PushStream}. Care should be taken with * infinite {@link Stream}s to avoid blocking indefinitely. * * @param items The items to push into the PushStream * @return A PushStream containing the items from the Java Stream */ public <T> PushStream<T> streamOf(Stream<T> items) { PushEventSource<T> pes = aec -> { AtomicBoolean closed = new AtomicBoolean(false); items.mapToLong(i -> { try { long returnValue = closed.get() ? -1 : aec.accept(data(i)); if (returnValue < 0) { aec.accept(PushEvent.<T>close()); } return returnValue; } catch (Exception e) { try { aec.accept(PushEvent.<T>error(e)); } catch (Exception e2) {/* No further events needed */} return -1; } }).filter(i -> i < 0).findFirst().orElseGet(() -> { try { return aec.accept(PushEvent.<T>close()); } catch (Exception e) { return -1; } }); return () -> closed.set(true); }; return this.<T> createUnbufferedStream(pes, null); } /** * Create an Unbuffered {@link PushStream} from a Java {@link Stream} The * data from the stream will be pushed into the PushStream asynchronously * using the supplied Executor. * * @param executor The worker to use to push items from the Stream into the * PushStream * @param items The items to push into the PushStream * @return A PushStream containing the items from the Java Stream */ public <T> PushStream<T> streamOf(Executor executor, Stream<T> items) { boolean closeExecutorOnClose; Executor toUse; if (executor == null) { toUse = Executors.newFixedThreadPool(2); closeExecutorOnClose = true; } else { toUse = executor; closeExecutorOnClose = false; } @SuppressWarnings("resource") PushStream<T> stream = new UnbufferedPushStreamImpl<T,BlockingQueue<PushEvent< ? extends T>>>( this, toUse, acquireScheduler(), aec -> { return () -> { /* No action to take */ }; }) { @Override protected boolean begin() { if (super.begin()) { Iterator<T> it = items.iterator(); toUse.execute(() -> pushData(it)); return true; } return false; } private void pushData(Iterator<T> it) { while (it.hasNext()) { try { long returnValue = closed.get() == CLOSED ? -1 : handleEvent(data(it.next())); if (returnValue != 0) { if (returnValue < 0) { close(); return; } else { scheduler.schedule( () -> toUse.execute(() -> pushData(it)), returnValue, MILLISECONDS); return; } } } catch (Exception e) { close(error(e)); } } close(); } }; stream = stream.onClose(() -> { if (closeExecutorOnClose) { ((ExecutorService) toUse).shutdown(); } releaseScheduler(); }).map(Function.identity()); return stream; } }
7,918
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushbackPolicyOption.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * {@link PushbackPolicyOption} provides a standard set of simple * {@link PushbackPolicy} implementations. * * @see PushbackPolicy */ public enum PushbackPolicyOption { /** * Returns a fixed amount of back pressure, independent of how full the * buffer is */ FIXED { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) { return q -> value; } }, /** * Returns zero back pressure until the buffer is full, then it returns a * fixed value */ ON_FULL_FIXED { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) { return q -> q.remainingCapacity() == 0 ? value : 0; } }, /** * Returns zero back pressure until the buffer is full, then it returns an * exponentially increasing amount, starting with the supplied value and * doubling it each time. Once the buffer is no longer full the back * pressure returns to zero. */ ON_FULL_EXPONENTIAL { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) { AtomicInteger backoffCount = new AtomicInteger(0); return q -> { if (q.remainingCapacity() == 0) { return value << backoffCount.getAndIncrement(); } backoffCount.set(0); return 0; }; } }, /** * Returns zero back pressure when the buffer is empty, then it returns a * linearly increasing amount of back pressure based on how full the buffer * is. The maximum value will be returned when the buffer is full. */ LINEAR { @Override public <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value) { return q -> { long remainingCapacity = q.remainingCapacity(); long used = q.size(); return (value * used) / (used + remainingCapacity); }; } }; /** * Create a {@link PushbackPolicy} instance configured with a base back * pressure time in nanoseconds * * The actual backpressure returned will vary based on the selected * implementation, the base value, and the state of the buffer. * * @param value * @return A {@link PushbackPolicy} to use */ public abstract <T, U extends BlockingQueue<PushEvent<? extends T>>> PushbackPolicy<T, U> getPolicy(long value); }
7,919
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/SimplePushEventSource.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import org.osgi.annotation.versioning.ProviderType; import org.osgi.util.promise.Promise; /** * A {@link SimplePushEventSource} is a helper that makes it simpler to write a * {@link PushEventSource}. Users do not need to manage multiple registrations * to the stream, nor do they have to be concerned with back pressure. * * @param <T> The type of the events produced by this source */ @ProviderType public interface SimplePushEventSource<T> extends PushEventSource<T>, AutoCloseable { /** * Close this source. Calling this method indicates that there will never be * any more events published by it. Calling this method sends a close event * to all connected consumers. After calling this method any * {@link PushEventConsumer} that tries to {@link #open(PushEventConsumer)} * this source will immediately receive a close event. */ @Override void close(); /** * Asynchronously publish an event to this stream and all connected * {@link PushEventConsumer} instances. When this method returns there is no * guarantee that all consumers have been notified. Events published by a * single thread will maintain their relative ordering, however they may be * interleaved with events from other threads. * * @param t * @throws IllegalStateException if the source is closed */ void publish(T t); /** * Close this source for now, but potentially reopen it later. Calling this * method asynchronously sends a close event to all connected consumers. * After calling this method any {@link PushEventConsumer} that wishes may * {@link #open(PushEventConsumer)} this source, and will receive subsequent * events. */ void endOfStream(); /** * Close this source for now, but potentially reopen it later. Calling this * method asynchronously sends an error event to all connected consumers. * After calling this method any {@link PushEventConsumer} that wishes may * {@link #open(PushEventConsumer)} this source, and will receive subsequent * events. * * @param e the error */ void error(Exception e); /** * Determine whether there are any {@link PushEventConsumer}s for this * {@link PushEventSource}. This can be used to skip expensive event * creation logic when there are no listeners. * * @return true if any consumers are currently connected */ boolean isConnected(); /** * This method can be used to delay event generation until an event source * has connected. The returned promise will resolve as soon as one or more * {@link PushEventConsumer} instances have opened the * SimplePushEventSource. * <p> * The returned promise may already be resolved if this * {@link SimplePushEventSource} already has connected consumers. If the * {@link SimplePushEventSource} is closed before the returned Promise * resolves then it will be failed with an {@link IllegalStateException}. * <p> * Note that the connected consumers are able to asynchronously close their * connections to this {@link SimplePushEventSource}, and therefore it is * possible that once the promise resolves this * {@link SimplePushEventSource} may no longer be connected to any * consumers. * * @return A promise representing the connection state of this EventSource */ Promise<Void> connectPromise(); }
7,920
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushStreamBuilder.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; /** * A Builder for a PushStream. This Builder extends the support of a standard * BufferBuilder by allowing the PushStream to be unbuffered. * * * @param <T> The type of objects in the {@link PushEvent} * @param <U> The type of the Queue used in the user specified buffer */ public interface PushStreamBuilder<T, U extends BlockingQueue<PushEvent< ? extends T>>> extends BufferBuilder<PushStream<T>,T,U> { /** * Tells this {@link PushStreamBuilder} to create an unbuffered stream which * delivers events directly to its consumer using the incoming delivery * thread. * * @return the builder */ PushStreamBuilder<T,U> unbuffered(); /* * Overridden methods to allow the covariant return of a PushStreamBuilder */ @Override PushStreamBuilder<T,U> withBuffer(U queue); @Override PushStreamBuilder<T,U> withQueuePolicy(QueuePolicy<T,U> queuePolicy); @Override PushStreamBuilder<T,U> withQueuePolicy(QueuePolicyOption queuePolicyOption); @Override PushStreamBuilder<T,U> withPushbackPolicy( PushbackPolicy<T,U> pushbackPolicy); @Override PushStreamBuilder<T,U> withPushbackPolicy( PushbackPolicyOption pushbackPolicyOption, long time); @Override PushStreamBuilder<T,U> withParallelism(int parallelism); @Override PushStreamBuilder<T,U> withExecutor(Executor executor); }
7,921
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushEvent.java
/* * Copyright (c) OSGi Alliance (2015, 2016). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import static org.osgi.util.pushstream.PushEvent.EventType.*; /** * A PushEvent is an immutable object that is transferred through a * communication channel to push information to a downstream consumer. The event * has three different types: * <ul> * <li>{@link EventType#DATA} – Provides access to a typed data element in the * stream. * <li>{@link EventType#CLOSE} – The stream is closed. After receiving this * event, no more events will follow. * <li>{@link EventType#ERROR} – The stream ran into an unrecoverable problem * and is sending the reason downstream. The stream is closed and no more events * will follow after this event. * </ul> * * @param <T> The payload type of the event. * @Immutable */ public abstract class PushEvent<T> { /** * The type of a {@link PushEvent}. */ public static enum EventType { /** * A data event forming part of the stream */ DATA, /** * An error event that indicates streaming has failed and that no more * events will arrive */ ERROR, /** * An event that indicates that the stream has terminated normally */ CLOSE } /** * Package private default constructor. */ PushEvent() {} /** * Get the type of this event. * * @return The type of this event. */ public abstract EventType getType(); /** * Return the data for this event. * * @return The data payload. * @throws IllegalStateException if this event is not a * {@link EventType#DATA} event. */ public T getData() throws IllegalStateException { throw new IllegalStateException( "Not a DATA event, the event type is " + getType()); } /** * Return the error that terminated the stream. * * @return The error that terminated the stream. * @throws IllegalStateException if this event is not an * {@link EventType#ERROR} event. */ public Exception getFailure() throws IllegalStateException { throw new IllegalStateException( "Not an ERROR event, the event type is " + getType()); } /** * Answer if no more events will follow after this event. * * @return {@code false} if this is a data event, otherwise {@code true}. */ public boolean isTerminal() { return true; } /** * Create a new data event. * * @param <T> The payload type. * @param payload The payload. * @return A new data event wrapping the specified payload. */ public static <T> PushEvent<T> data(T payload) { return new DataEvent<T>(payload); } /** * Create a new error event. * * @param <T> The payload type. * @param e The error. * @return A new error event with the specified error. */ public static <T> PushEvent<T> error(Exception e) { return new ErrorEvent<T>(e); } /** * Create a new close event. * * @param <T> The payload type. * @return A new close event. */ public static <T> PushEvent<T> close() { return new CloseEvent<T>(); } /** * Convenience to cast a close/error event to another payload type. Since * the payload type is not needed for these events this is harmless. This * therefore allows you to forward the close/error event downstream without * creating anew event. * * @param <X> The new payload type. * @return The current error or close event mapped to a new payload type. * @throws IllegalStateException if the event is a {@link EventType#DATA} * event. */ public <X> PushEvent<X> nodata() throws IllegalStateException { @SuppressWarnings("unchecked") PushEvent<X> result = (PushEvent<X>) this; return result; } static final class DataEvent<T> extends PushEvent<T> { private final T data; DataEvent(T data) { this.data = data; } @Override public T getData() throws IllegalStateException { return data; } @Override public EventType getType() { return DATA; } @Override public boolean isTerminal() { return false; } @Override public <X> PushEvent<X> nodata() throws IllegalStateException { throw new IllegalStateException("This event is a DATA event"); } } static final class ErrorEvent<T> extends PushEvent<T> { private final Exception error; ErrorEvent(Exception error) { this.error = error; } @Override public Exception getFailure() { return error; } @Override public EventType getType() { return ERROR; } } static final class CloseEvent<T> extends PushEvent<T> { @Override public EventType getType() { return CLOSE; } } }
7,922
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/AbstractBufferBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; abstract class AbstractBufferBuilder<R, T, U extends BlockingQueue<PushEvent< ? extends T>>> implements BufferBuilder<R,T,U> { protected Executor worker; protected int concurrency; protected PushbackPolicy<T,U> backPressure; protected QueuePolicy<T,U> bufferingPolicy; protected U buffer; @Override public BufferBuilder<R,T,U> withBuffer(U queue) { this.buffer = queue; return this; } @Override public BufferBuilder<R,T,U> withQueuePolicy( QueuePolicy<T,U> queuePolicy) { this.bufferingPolicy = queuePolicy; return this; } @Override public BufferBuilder<R,T,U> withQueuePolicy( QueuePolicyOption queuePolicyOption) { this.bufferingPolicy = queuePolicyOption.getPolicy(); return this; } @Override public BufferBuilder<R,T,U> withPushbackPolicy( PushbackPolicy<T,U> pushbackPolicy) { this.backPressure = pushbackPolicy; return this; } @Override public BufferBuilder<R,T,U> withPushbackPolicy( PushbackPolicyOption pushbackPolicyOption, long time) { this.backPressure = pushbackPolicyOption.getPolicy(time); return this; } @Override public BufferBuilder<R,T,U> withParallelism(int parallelism) { this.concurrency = parallelism; return this; } @Override public BufferBuilder<R,T,U> withExecutor(Executor executor) { this.worker = executor; return this; } }
7,923
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/package-info.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * Push Stream Package Version 1.0. * * <p> * Bundles wishing to use this package must list the package in the * Import-Package header of the bundle's manifest. * * <p> * Example import for consumers using the API in this package: * <p> * {@code Import-Package: org.osgi.util.pushstream; version="[1.0,2.0)"} * <p> * Example import for providers implementing the API in this package: * <p> * {@code Import-Package: org.osgi.util.pushstream; version="[1.0,1.1)"} * * @author $Id: 6a28fa0b5c2036486a22a7ca1254729d7848ca43 $ */ @Version("1.0") package org.osgi.util.pushstream; import org.osgi.annotation.versioning.Version;
7,924
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/PushEventSource.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import org.osgi.annotation.versioning.ConsumerType; /** * An event source. An event source can open a channel between a source and a * consumer. Once the channel is opened (even before it returns) the source can * send events to the consumer. * * A source should stop sending and automatically close the channel when sending * an event returns a negative value, see {@link PushEventConsumer#ABORT}. * Values that are larger than 0 should be treated as a request to delay the * next events with those number of milliseconds. * * @param <T> * The payload type */ @ConsumerType @FunctionalInterface public interface PushEventSource<T> { /** * Open the asynchronous channel between the source and the consumer. The * call returns an {@link AutoCloseable}. This can be closed, and should * close the channel, including sending a Close event if the channel was not * already closed. The returned object must be able to be closed multiple * times without sending more than one Close events. * * @param aec the consumer (not null) * @return a {@link AutoCloseable} that can be used to close the stream * @throws Exception */ AutoCloseable open(PushEventConsumer< ? super T> aec) throws Exception; }
7,925
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util
Create_ds/aries/pushstream/pushstream/src/main/java/org/osgi/util/pushstream/QueuePolicy.java
/* * Copyright (c) OSGi Alliance (2015). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.util.pushstream; import java.util.concurrent.BlockingQueue; import org.osgi.annotation.versioning.ConsumerType; import org.osgi.util.pushstream.PushEvent.EventType; /** * A {@link QueuePolicy} is used to control how events should be queued in the * current buffer. The {@link QueuePolicy} will be called when an event has * arrived. * * @see QueuePolicyOption * * * @param <T> The type of the data * @param <U> The type of the queue */ @ConsumerType @FunctionalInterface public interface QueuePolicy<T, U extends BlockingQueue<PushEvent<? extends T>>> { /** * Enqueue the event and return the remaining capacity available for events * * @param queue * @param event * @throws Exception If an error ocurred adding the event to the queue. This * exception will cause the connection between the * {@link PushEventSource} and the {@link PushEventConsumer} to be * closed with an {@link EventType#ERROR} */ public void doOffer(U queue, PushEvent<? extends T> event) throws Exception; }
7,926
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries/pushstream/IntermediatePushStreamImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.pushstream; import static org.apache.aries.pushstream.AbstractPushStreamImpl.State.*; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import org.osgi.util.pushstream.PushStream; import org.osgi.util.pushstream.PushStreamProvider; public class IntermediatePushStreamImpl<T> extends AbstractPushStreamImpl<T> implements PushStream<T> { private final AbstractPushStreamImpl< ? > previous; protected IntermediatePushStreamImpl(PushStreamProvider psp, Executor executor, ScheduledExecutorService scheduler, AbstractPushStreamImpl< ? > previous) { super(psp, executor, scheduler); this.previous = previous; } @Override protected boolean begin() { if(closed.compareAndSet(BUILDING, STARTED)) { beginning(); previous.begin(); return true; } return false; } protected void beginning() { // The base implementation has nothing to do, but // this method is used in windowing } }
7,927
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries/pushstream/UnbufferedPushStreamImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.pushstream; import static java.util.Optional.ofNullable; import static org.apache.aries.pushstream.AbstractPushStreamImpl.State.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import org.osgi.util.pushstream.PushEvent; import org.osgi.util.pushstream.PushEventConsumer; import org.osgi.util.pushstream.PushStream; import org.osgi.util.pushstream.PushStreamProvider; public class UnbufferedPushStreamImpl<T, U extends BlockingQueue<PushEvent< ? extends T>>> extends AbstractPushStreamImpl<T> implements PushStream<T> { protected final Function<PushEventConsumer<T>,AutoCloseable> connector; protected final AtomicReference<AutoCloseable> upstream = new AtomicReference<AutoCloseable>(); public UnbufferedPushStreamImpl(PushStreamProvider psp, Executor executor, ScheduledExecutorService scheduler, Function<PushEventConsumer<T>,AutoCloseable> connector) { super(psp, executor, scheduler); this.connector = connector; } @Override protected boolean close(PushEvent<T> event) { if(super.close(event)) { ofNullable(upstream.getAndSet(() -> { // This block doesn't need to do anything, but the presence // of the Closable is needed to prevent duplicate begins })).ifPresent(c -> { try { c.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }); return true; } return false; } @Override protected boolean begin() { if(closed.compareAndSet(BUILDING, STARTED)) { AutoCloseable toClose = connector.apply(this::handleEvent); if(!upstream.compareAndSet(null,toClose)) { //TODO log that we tried to connect twice... try { toClose.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (closed.get() == CLOSED && upstream.compareAndSet(toClose, null)) { // We closed before setting the upstream - close it now try { toClose.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true; } return false; } }
7,928
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries/pushstream/BufferedPushStreamImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.pushstream; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.aries.pushstream.AbstractPushStreamImpl.State.CLOSED; import static org.osgi.util.pushstream.PushEventConsumer.ABORT; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import org.osgi.util.pushstream.PushEvent; import org.osgi.util.pushstream.PushEventConsumer; import org.osgi.util.pushstream.PushStream; import org.osgi.util.pushstream.PushStreamProvider; import org.osgi.util.pushstream.PushbackPolicy; import org.osgi.util.pushstream.QueuePolicy; public class BufferedPushStreamImpl<T, U extends BlockingQueue<PushEvent< ? extends T>>> extends UnbufferedPushStreamImpl<T,U> implements PushStream<T> { private final U eventQueue; private final Semaphore semaphore; private final Executor worker; private final QueuePolicy<T, U> queuePolicy; private final PushbackPolicy<T, U> pushbackPolicy; /** * Indicates that a terminal event has been received, that we should stop * collecting new events, and that we must drain the buffer before * continuing */ private final AtomicBoolean softClose = new AtomicBoolean(); private final int parallelism; public BufferedPushStreamImpl(PushStreamProvider psp, ScheduledExecutorService scheduler, U eventQueue, int parallelism, Executor worker, QueuePolicy<T,U> queuePolicy, PushbackPolicy<T,U> pushbackPolicy, Function<PushEventConsumer<T>,AutoCloseable> connector) { super(psp, worker, scheduler, connector); this.eventQueue = eventQueue; this.parallelism = parallelism; this.semaphore = new Semaphore(parallelism); this.worker = worker; this.queuePolicy = queuePolicy; this.pushbackPolicy = pushbackPolicy; } @Override protected long handleEvent(PushEvent< ? extends T> event) { // If we have already been soft closed, or hard closed then abort if (!softClose.compareAndSet(false, event.isTerminal()) || closed.get() == CLOSED) { return ABORT; } try { queuePolicy.doOffer(eventQueue, event); long backPressure = pushbackPolicy.pushback(eventQueue); if(backPressure < 0) { close(); return ABORT; } if(semaphore.tryAcquire()) { startWorker(); } return backPressure; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } } private void startWorker() { worker.execute(() -> { try { PushEvent< ? extends T> event; while ((event = eventQueue.poll()) != null) { if (event.isTerminal()) { // Wait for the other threads to finish semaphore.acquire(parallelism - 1); } long backpressure = super.handleEvent(event); if(backpressure < 0) { close(); return; } else if(backpressure > 0) { scheduler.schedule(this::startWorker, backpressure, MILLISECONDS); return; } } semaphore.release(); } catch (Exception e) { close(PushEvent.error(e)); } if(eventQueue.peek() != null && semaphore.tryAcquire()) { try { startWorker(); } catch (Exception e) { close(PushEvent.error(e)); } } }); } }
7,929
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries/pushstream/SimplePushEventSourceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.pushstream; import static java.util.Collections.emptyList; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.osgi.util.promise.Promises; import org.osgi.util.pushstream.PushEvent; import org.osgi.util.pushstream.PushEventConsumer; import org.osgi.util.pushstream.QueuePolicy; import org.osgi.util.pushstream.SimplePushEventSource; public class SimplePushEventSourceImpl<T, U extends BlockingQueue<PushEvent< ? extends T>>> implements SimplePushEventSource<T> { private final Object lock = new Object(); private final Executor worker; private final ScheduledExecutorService scheduler; private final QueuePolicy<T,U> queuePolicy; private final U queue; private final int parallelism; private final Semaphore semaphore; private final List<PushEventConsumer< ? super T>> connected = new ArrayList<>(); private final Runnable onClose; private boolean closed; private Deferred<Void> connectPromise; private boolean waitForFinishes; public SimplePushEventSourceImpl(Executor worker, ScheduledExecutorService scheduler, QueuePolicy<T,U> queuePolicy, U queue, int parallelism, Runnable onClose) { this.worker = worker; this.scheduler = scheduler; this.queuePolicy = queuePolicy; this.queue = queue; this.parallelism = parallelism; this.semaphore = new Semaphore(parallelism); this.onClose = onClose; this.closed = false; this.connectPromise = null; } @Override public AutoCloseable open(PushEventConsumer< ? super T> pec) throws Exception { Deferred<Void> toResolve = null; synchronized (lock) { if (closed) { throw new IllegalStateException( "This PushEventConsumer is closed"); } toResolve = connectPromise; connectPromise = null; connected.add(pec); } if (toResolve != null) { toResolve.resolve(null); } return () -> { closeConsumer(pec, PushEvent.close()); }; } private void closeConsumer(PushEventConsumer< ? super T> pec, PushEvent<T> event) { boolean sendClose; synchronized (lock) { sendClose = connected.remove(pec); } if (sendClose) { doSend(pec, event); } } private void doSend(PushEventConsumer< ? super T> pec, PushEvent<T> event) { try { worker.execute(() -> safePush(pec, event)); } catch (RejectedExecutionException ree) { // TODO log? if (!event.isTerminal()) { close(PushEvent.error(ree)); } else { safePush(pec, event); } } } @SuppressWarnings("boxing") private Promise<Long> doSendWithBackPressure( PushEventConsumer< ? super T> pec, PushEvent<T> event) { Deferred<Long> d = new Deferred<>(); try { worker.execute( () -> d.resolve(System.nanoTime() + safePush(pec, event))); } catch (RejectedExecutionException ree) { // TODO log? if (!event.isTerminal()) { close(PushEvent.error(ree)); return Promises.resolved(System.nanoTime()); } else { return Promises .resolved(System.nanoTime() + safePush(pec, event)); } } return d.getPromise(); } private long safePush(PushEventConsumer< ? super T> pec, PushEvent<T> event) { try { long backpressure = pec.accept(event) * 1000000; if (backpressure < 0 && !event.isTerminal()) { closeConsumer(pec, PushEvent.close()); return -1; } return backpressure; } catch (Exception e) { // TODO log? if (!event.isTerminal()) { closeConsumer(pec, PushEvent.error(e)); } return -1; } } @Override public void close() { close(PushEvent.close()); } private void close(PushEvent<T> event) { List<PushEventConsumer< ? super T>> toClose; Deferred<Void> toFail = null; synchronized (lock) { if(!closed) { closed = true; toClose = new ArrayList<>(connected); connected.clear(); queue.clear(); if(connectPromise != null) { toFail = connectPromise; connectPromise = null; } } else { toClose = emptyList(); } } toClose.stream().forEach(pec -> doSend(pec, event)); if (toFail != null) { toFail.resolveWith(closedConnectPromise()); } onClose.run(); } @Override public void publish(T t) { enqueueEvent(PushEvent.data(t)); } @Override public void endOfStream() { enqueueEvent(PushEvent.close()); } @Override public void error(Exception e) { enqueueEvent(PushEvent.error(e)); } private void enqueueEvent(PushEvent<T> event) { synchronized (lock) { if (closed || connected.isEmpty()) { return; } } try { queuePolicy.doOffer(queue, event); boolean start; synchronized (lock) { start = !waitForFinishes && semaphore.tryAcquire(); } if (start) { startWorker(); } } catch (Exception e) { close(PushEvent.error(e)); throw new IllegalStateException( "The queue policy threw an exception", e); } } @SuppressWarnings({ "unchecked", "boxing" }) private void startWorker() { worker.execute(() -> { try { for(;;) { PushEvent<T> event; List<PushEventConsumer< ? super T>> toCall; boolean resetWait = false; synchronized (lock) { if(waitForFinishes) { semaphore.release(); while(waitForFinishes) { lock.notifyAll(); lock.wait(); } semaphore.acquire(); } event = (PushEvent<T>) queue.poll(); if(event == null) { break; } toCall = new ArrayList<>(connected); if (event.isTerminal()) { waitForFinishes = true; resetWait = true; connected.clear(); while (!semaphore.tryAcquire(parallelism - 1)) { lock.wait(); } } } List<Promise<Long>> calls = toCall.stream().map(pec -> { if (semaphore.tryAcquire()) { try { return doSendWithBackPressure(pec, event); } finally { semaphore.release(); } } else { return Promises.resolved( System.nanoTime() + safePush(pec, event)); } }).collect(toList()); long toWait = Promises.<Long,Long>all(calls) .map(l -> l.stream() .max((a,b) -> a.compareTo(b)) .orElseGet(() -> System.nanoTime())) .getValue() - System.nanoTime(); if (toWait > 0) { scheduler.schedule(this::startWorker, toWait, NANOSECONDS); return; } if (resetWait == true) { synchronized (lock) { waitForFinishes = false; lock.notifyAll(); } } } semaphore.release(); } catch (Exception e) { close(PushEvent.error(e)); } if (queue.peek() != null && semaphore.tryAcquire()) { try { startWorker(); } catch (Exception e) { close(PushEvent.error(e)); } } }); } @Override public boolean isConnected() { synchronized (lock) { return !connected.isEmpty(); } } @Override public Promise<Void> connectPromise() { synchronized (lock) { if (closed) { return closedConnectPromise(); } if (connected.isEmpty()) { if (connectPromise == null) { connectPromise = new Deferred<>(); } return connectPromise.getPromise(); } else { return Promises.resolved(null); } } } private Promise<Void> closedConnectPromise() { return Promises.failed(new IllegalStateException( "This SimplePushEventSource is closed")); } }
7,930
0
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries
Create_ds/aries/pushstream/pushstream/src/main/java/org/apache/aries/pushstream/AbstractPushStreamImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.pushstream; import static java.util.Collections.emptyList; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static org.apache.aries.pushstream.AbstractPushStreamImpl.State.*; import static org.osgi.util.pushstream.PushEventConsumer.*; import java.time.Duration; import java.util.AbstractQueue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; import org.osgi.util.promise.Deferred; import org.osgi.util.promise.Promise; import org.osgi.util.pushstream.PushEvent; import org.osgi.util.pushstream.PushEventConsumer; import org.osgi.util.pushstream.PushEventSource; import org.osgi.util.pushstream.PushStream; import org.osgi.util.pushstream.PushStreamBuilder; import org.osgi.util.pushstream.PushStreamProvider; import org.osgi.util.pushstream.PushEvent.EventType; public abstract class AbstractPushStreamImpl<T> implements PushStream<T> { public static enum State { BUILDING, STARTED, CLOSED } protected final PushStreamProvider psp; protected final Executor defaultExecutor; protected final ScheduledExecutorService scheduler; protected final AtomicReference<State> closed = new AtomicReference<>(BUILDING); protected final AtomicReference<PushEventConsumer<T>> next = new AtomicReference<>(); protected final AtomicReference<Runnable> onCloseCallback = new AtomicReference<>(); protected final AtomicReference<Consumer<? super Throwable>> onErrorCallback = new AtomicReference<>(); protected abstract boolean begin(); protected AbstractPushStreamImpl(PushStreamProvider psp, Executor executor, ScheduledExecutorService scheduler) { this.psp = psp; this.defaultExecutor = executor; this.scheduler = scheduler; } protected long handleEvent(PushEvent< ? extends T> event) { if(closed.get() != CLOSED) { try { if(event.isTerminal()) { close(event.nodata()); return ABORT; } else { PushEventConsumer<T> consumer = next.get(); long val; if(consumer == null) { //TODO log a warning val = CONTINUE; } else { val = consumer.accept(event); } if(val < 0) { close(); } return val; } } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } } return ABORT; } @Override public void close() { close(PushEvent.close()); } protected boolean close(PushEvent<T> event) { if(!event.isTerminal()) { throw new IllegalArgumentException("The event " + event + " is not a close event."); } if(closed.getAndSet(CLOSED) != CLOSED) { PushEventConsumer<T> aec = next.getAndSet(null); if(aec != null) { try { aec.accept(event); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } Runnable handler = onCloseCallback.getAndSet(null); if(handler != null) { try { handler.run(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (event.getType() == EventType.ERROR) { Consumer<? super Throwable> errorHandler = onErrorCallback.getAndSet(null); if(errorHandler != null) { try { errorHandler.accept(event.getFailure()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return true; } return false; } @Override public PushStream<T> onClose(Runnable closeHandler) { if(onCloseCallback.compareAndSet(null, closeHandler)) { if(closed.get() == State.CLOSED && onCloseCallback.compareAndSet(closeHandler, null)) { closeHandler.run(); } } else { throw new IllegalStateException("A close handler has already been defined for this stream object"); } return this; } @Override public PushStream<T> onError(Consumer< ? super Throwable> closeHandler) { if(onErrorCallback.compareAndSet(null, closeHandler)) { if(closed.get() == State.CLOSED) { //TODO log already closed onErrorCallback.set(null); } } else { throw new IllegalStateException("A close handler has already been defined for this stream object"); } return this; } private void updateNext(PushEventConsumer<T> consumer) { if(!next.compareAndSet(null, consumer)) { throw new IllegalStateException("This stream has already been chained"); } else if(closed.get() == CLOSED && next.compareAndSet(consumer, null)) { try { consumer.accept(PushEvent.close()); } catch (Exception e) { //TODO log e.printStackTrace(); } } } @Override public PushStream<T> filter(Predicate< ? super T> predicate) { AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); updateNext((event) -> { try { if (!event.isTerminal()) { if (predicate.test(event.getData())) { return eventStream.handleEvent(event); } else { return CONTINUE; } } return eventStream.handleEvent(event); } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public <R> PushStream<R> map(Function< ? super T, ? extends R> mapper) { AbstractPushStreamImpl<R> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); updateNext(event -> { try { if (!event.isTerminal()) { return eventStream.handleEvent( PushEvent.data(mapper.apply(event.getData()))); } else { return eventStream.handleEvent(event.nodata()); } } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public <R> PushStream<R> flatMap( Function< ? super T, ? extends PushStream< ? extends R>> mapper) { AbstractPushStreamImpl<R> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); PushEventConsumer<R> consumer = e -> { switch (e.getType()) { case ERROR : close(e.nodata()); return ABORT; case CLOSE : // Close should allow the next flat mapped entry // without closing the stream; return ABORT; case DATA : long returnValue = eventStream.handleEvent(e); if (returnValue < 0) { close(); return ABORT; } return returnValue; default : throw new IllegalArgumentException( "The event type " + e.getType() + " is unknown"); } }; updateNext(event -> { try { if (!event.isTerminal()) { PushStream< ? extends R> mappedStream = mapper .apply(event.getData()); return mappedStream.forEachEvent(consumer) .getValue() .longValue(); } else { return eventStream.handleEvent(event.nodata()); } } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public PushStream<T> distinct() { Set<T> set = Collections.<T>newSetFromMap(new ConcurrentHashMap<>()); return filter(set::add); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public PushStream<T> sorted() { return sorted((Comparator)Comparator.naturalOrder()); } @Override public PushStream<T> sorted(Comparator< ? super T> comparator) { List<T> list = Collections.synchronizedList(new ArrayList<>()); AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); updateNext(event -> { try { switch(event.getType()) { case DATA : list.add(event.getData()); return CONTINUE; case CLOSE : list.sort(comparator); for(T t : list) { eventStream.handleEvent(PushEvent.data(t)); } return ABORT; case ERROR : return eventStream.handleEvent(event.nodata()); } return eventStream.handleEvent(event.nodata()); } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public PushStream<T> limit(long maxSize) { if(maxSize <= 0) { throw new IllegalArgumentException("The limit must be greater than zero"); } AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); AtomicLong counter = new AtomicLong(maxSize); updateNext(event -> { try { if (!event.isTerminal()) { long count = counter.decrementAndGet(); if (count > 0) { return eventStream.handleEvent(event); } else if (count == 0) { eventStream.handleEvent(event); } return ABORT; } else { return eventStream.handleEvent(event.nodata()); } } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public PushStream<T> skip(long n) { if(n <= 0) { throw new IllegalArgumentException("The number to skip must be greater than zero"); } AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); AtomicLong counter = new AtomicLong(n); updateNext(event -> { try { if (!event.isTerminal()) { if (counter.get() > 0 && counter.decrementAndGet() >= 0) { return CONTINUE; } else { return eventStream.handleEvent(event); } } else { return eventStream.handleEvent(event.nodata()); } } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public PushStream<T> fork(int n, int delay, Executor ex) { AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, ex, scheduler, this); Semaphore s = new Semaphore(n); updateNext(event -> { try { if (event.isTerminal()) { s.acquire(n); eventStream.close(event.nodata()); return ABORT; } s.acquire(1); ex.execute(() -> { try { if (eventStream.handleEvent(event) < 0) { eventStream.close(PushEvent.close()); } } catch (Exception e1) { close(PushEvent.error(e1)); } finally { s.release(1); } }); return s.getQueueLength() * delay; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public PushStream<T> buffer() { return psp.createStream(c -> { forEachEvent(c); return this; }); } @Override public <U extends BlockingQueue<PushEvent< ? extends T>>> PushStreamBuilder<T,U> buildBuffer() { return psp.buildStream(c -> { forEachEvent(c); return this; }); } @Override public PushStream<T> merge( PushEventSource< ? extends T> source) { AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); AtomicInteger count = new AtomicInteger(2); PushEventConsumer<T> consumer = event -> { try { if (!event.isTerminal()) { return eventStream.handleEvent(event); } if (count.decrementAndGet() == 0) { eventStream.handleEvent(event.nodata()); return ABORT; } return CONTINUE; } catch (Exception e) { PushEvent<T> error = PushEvent.error(e); close(error); eventStream.close(event.nodata()); return ABORT; } }; updateNext(consumer); AutoCloseable second; try { second = source.open((PushEvent< ? extends T> event) -> { return consumer.accept(event); }); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new IllegalStateException( "Unable to merge events as the event source could not be opened.", e); } return eventStream.onClose(() -> { try { second.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }).map(Function.identity()); } @Override public PushStream<T> merge(PushStream< ? extends T> source) { AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); AtomicInteger count = new AtomicInteger(2); PushEventConsumer<T> consumer = event -> { try { if (!event.isTerminal()) { return eventStream.handleEvent(event); } if (count.decrementAndGet() == 0) { eventStream.handleEvent(event.nodata()); return ABORT; } return CONTINUE; } catch (Exception e) { PushEvent<T> error = PushEvent.error(e); close(error); eventStream.close(event.nodata()); return ABORT; } }; updateNext(consumer); try { source.forEachEvent(event -> { return consumer.accept(event); }).then(p -> { count.decrementAndGet(); consumer.accept(PushEvent.close()); return null; }, p -> { count.decrementAndGet(); consumer.accept(PushEvent.error((Exception) p.getFailure())); }); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new IllegalStateException( "Unable to merge events as the event source could not be opened.", e); } return eventStream.onClose(() -> { try { source.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }).map(Function.identity()); } @SuppressWarnings("unchecked") @Override public PushStream<T>[] split(Predicate< ? super T>... predicates) { Predicate<? super T>[] tests = Arrays.copyOf(predicates, predicates.length); AbstractPushStreamImpl<T>[] rsult = new AbstractPushStreamImpl[tests.length]; for(int i = 0; i < tests.length; i++) { rsult[i] = new IntermediatePushStreamImpl<>(psp, defaultExecutor, scheduler, this); } AtomicReferenceArray<Boolean> off = new AtomicReferenceArray<>(tests.length); AtomicInteger count = new AtomicInteger(tests.length); updateNext(event -> { if (!event.isTerminal()) { long delay = CONTINUE; for (int i = 0; i < tests.length; i++) { try { if (off.get(i).booleanValue() && tests[i].test(event.getData())) { long accept = rsult[i].handleEvent(event); if (accept < 0) { off.set(i, Boolean.TRUE); count.decrementAndGet(); } else if (accept > delay) { accept = delay; } } } catch (Exception e) { try { rsult[i].close(PushEvent.error(e)); } catch (Exception e2) { //TODO log } off.set(i, Boolean.TRUE); } } if (count.get() == 0) return ABORT; return delay; } for (AbstractPushStreamImpl<T> as : rsult) { try { as.handleEvent(event.nodata()); } catch (Exception e) { try { as.close(PushEvent.error(e)); } catch (Exception e2) { //TODO log } } } return ABORT; }); return Arrays.copyOf(rsult, tests.length); } @Override public PushStream<T> sequential() { AbstractPushStreamImpl<T> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); Lock lock = new ReentrantLock(); updateNext((event) -> { try { lock.lock(); try { return eventStream.handleEvent(event); } finally { lock.unlock(); } } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public <R> PushStream<R> coalesce( Function< ? super T,Optional<R>> accumulator) { AbstractPushStreamImpl<R> eventStream = new IntermediatePushStreamImpl<>( psp, defaultExecutor, scheduler, this); updateNext((event) -> { try { if (!event.isTerminal()) { Optional<PushEvent<R>> coalesced = accumulator .apply(event.getData()).map(PushEvent::data); if (coalesced.isPresent()) { try { return eventStream.handleEvent(coalesced.get()); } catch (Exception ex) { close(PushEvent.error(ex)); return ABORT; } } else { return CONTINUE; } } return eventStream.handleEvent(event.nodata()); } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } @Override public <R> PushStream<R> coalesce(int count, Function<Collection<T>,R> f) { if (count <= 0) throw new IllegalArgumentException( "A coalesce operation must collect a positive number of events"); // This could be optimised to only use a single collection queue. // It would save some GC, but is it worth it? return coalesce(() -> count, f); } @Override public <R> PushStream<R> coalesce(IntSupplier count, Function<Collection<T>,R> f) { AtomicReference<Queue<T>> queueRef = new AtomicReference<Queue<T>>( null); Runnable init = () -> queueRef .set(getQueueForInternalBuffering(count.getAsInt())); @SuppressWarnings("resource") AbstractPushStreamImpl<R> eventStream = new IntermediatePushStreamImpl<R>( psp, defaultExecutor, scheduler, this) { @Override protected void beginning() { init.run(); } }; AtomicBoolean endPending = new AtomicBoolean(); Object lock = new Object(); updateNext((event) -> { try { Queue<T> queue; if (!event.isTerminal()) { synchronized (lock) { for (;;) { queue = queueRef.get(); if (queue == null) { if (endPending.get()) { return ABORT; } else { continue; } } else if (queue.offer(event.getData())) { return CONTINUE; } else { queueRef.lazySet(null); break; } } } queueRef.set( getQueueForInternalBuffering(count.getAsInt())); // This call is on the same thread and so must happen // outside // the synchronized block. return aggregateAndForward(f, eventStream, event, queue); } else { synchronized (lock) { queue = queueRef.get(); queueRef.lazySet(null); endPending.set(true); } if (queue != null) { eventStream.handleEvent( PushEvent.data(f.apply(queue))); } } return eventStream.handleEvent(event.nodata()); } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } private <R> long aggregateAndForward(Function<Collection<T>,R> f, AbstractPushStreamImpl<R> eventStream, PushEvent< ? extends T> event, Queue<T> queue) { if (!queue.offer(event.getData())) { ((ArrayQueue<T>) queue).forcePush(event.getData()); } return eventStream.handleEvent(PushEvent.data(f.apply(queue))); } @Override public <R> PushStream<R> window(Duration time, Function<Collection<T>,R> f) { return window(time, defaultExecutor, f); } @Override public <R> PushStream<R> window(Duration time, Executor executor, Function<Collection<T>,R> f) { return window(() -> time, () -> 0, executor, (t, c) -> f.apply(c)); } @Override public <R> PushStream<R> window(Supplier<Duration> time, IntSupplier maxEvents, BiFunction<Long,Collection<T>,R> f) { return window(time, maxEvents, defaultExecutor, f); } @Override public <R> PushStream<R> window(Supplier<Duration> time, IntSupplier maxEvents, Executor ex, BiFunction<Long,Collection<T>,R> f) { AtomicLong timestamp = new AtomicLong(); AtomicLong counter = new AtomicLong(); Object lock = new Object(); AtomicReference<Queue<T>> queueRef = new AtomicReference<Queue<T>>( null); // This code is declared as a separate block to avoid any confusion // about which instance's methods and variables are in scope Consumer<AbstractPushStreamImpl<R>> begin = p -> { synchronized (lock) { timestamp.lazySet(System.nanoTime()); long count = counter.get(); scheduler.schedule( getWindowTask(p, f, time, maxEvents, lock, count, queueRef, timestamp, counter, ex), time.get().toNanos(), NANOSECONDS); } queueRef.set(getQueueForInternalBuffering(maxEvents.getAsInt())); }; @SuppressWarnings("resource") AbstractPushStreamImpl<R> eventStream = new IntermediatePushStreamImpl<R>( psp, ex, scheduler, this) { @Override protected void beginning() { begin.accept(this); } }; AtomicBoolean endPending = new AtomicBoolean(false); updateNext((event) -> { try { if (eventStream.closed.get() == CLOSED) { return ABORT; } Queue<T> queue; if (!event.isTerminal()) { long elapsed; long newCount; synchronized (lock) { for (;;) { queue = queueRef.get(); if (queue == null) { if (endPending.get()) { return ABORT; } else { continue; } } else if (queue.offer(event.getData())) { return CONTINUE; } else { queueRef.lazySet(null); break; } } long now = System.nanoTime(); elapsed = now - timestamp.get(); timestamp.lazySet(now); newCount = counter.get() + 1; counter.lazySet(newCount); // This is a non-blocking call, and must happen in the // synchronized block to avoid re=ordering the executor // enqueue with a subsequent incoming close operation aggregateAndForward(f, eventStream, event, queue, ex, elapsed); } // These must happen outside the synchronized block as we // call out to user code queueRef.set( getQueueForInternalBuffering(maxEvents.getAsInt())); scheduler.schedule( getWindowTask(eventStream, f, time, maxEvents, lock, newCount, queueRef, timestamp, counter, ex), time.get().toNanos(), NANOSECONDS); return CONTINUE; } else { long elapsed; synchronized (lock) { queue = queueRef.get(); queueRef.lazySet(null); endPending.set(true); long now = System.nanoTime(); elapsed = now - timestamp.get(); counter.lazySet(counter.get() + 1); } Collection<T> collected = queue == null ? emptyList() : queue; ex.execute(() -> { try { eventStream .handleEvent(PushEvent.data(f.apply( Long.valueOf(NANOSECONDS .toMillis(elapsed)), collected))); } catch (Exception e) { close(PushEvent.error(e)); } }); } ex.execute(() -> eventStream.handleEvent(event.nodata())); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); return eventStream; } protected Queue<T> getQueueForInternalBuffering(int size) { if (size == 0) { return new LinkedList<T>(); } else { return new ArrayQueue<>(size - 1); } } @SuppressWarnings("unchecked") /** * A special queue that keeps one element in reserve and can have that last * element set using forcePush. After the element is set the capacity is * permanently increased by one and cannot grow further. * * @param <E> The element type */ private static class ArrayQueue<E> extends AbstractQueue<E> implements Queue<E> { final Object[] store; int normalLength; int nextIndex; int size; ArrayQueue(int capacity) { store = new Object[capacity + 1]; normalLength = store.length - 1; } @Override public boolean offer(E e) { if (e == null) throw new NullPointerException("Null values are not supported"); if (size < normalLength) { store[nextIndex] = e; size++; nextIndex++; nextIndex = nextIndex % normalLength; return true; } return false; } public void forcePush(E e) { store[normalLength] = e; normalLength++; size++; } @Override public E poll() { if (size == 0) { return null; } else { int idx = nextIndex - size; if (idx < 0) { idx += normalLength; } E value = (E) store[idx]; store[idx] = null; size--; return value; } } @Override public E peek() { if (size == 0) { return null; } else { int idx = nextIndex - size; if (idx < 0) { idx += normalLength; } return (E) store[idx]; } } @Override public Iterator<E> iterator() { final int previousNext = nextIndex; return new Iterator<E>() { int idx; int remaining = size; { idx = nextIndex - size; if (idx < 0) { idx += normalLength; } } @Override public boolean hasNext() { if (nextIndex != previousNext) { throw new ConcurrentModificationException( "The queue was concurrently modified"); } return remaining > 0; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException( "The iterator has no more values"); } E value = (E) store[idx]; idx++; remaining--; if (idx == normalLength) { idx = 0; } return value; } }; } @Override public int size() { return size; } } private <R> Runnable getWindowTask(AbstractPushStreamImpl<R> eventStream, BiFunction<Long,Collection<T>,R> f, Supplier<Duration> time, IntSupplier maxEvents, Object lock, long expectedCounter, AtomicReference<Queue<T>> queueRef, AtomicLong timestamp, AtomicLong counter, Executor executor) { return () -> { Queue<T> queue = null; long elapsed; synchronized (lock) { if (counter.get() != expectedCounter) { return; } counter.lazySet(expectedCounter + 1); long now = System.nanoTime(); elapsed = now - timestamp.get(); timestamp.lazySet(now); queue = queueRef.get(); queueRef.lazySet(null); // This is a non-blocking call, and must happen in the // synchronized block to avoid re=ordering the executor // enqueue with a subsequent incoming close operation Collection<T> collected = queue == null ? emptyList() : queue; executor.execute(() -> { try { eventStream.handleEvent(PushEvent.data(f.apply( Long.valueOf(NANOSECONDS.toMillis(elapsed)), collected))); } catch (Exception e) { close(PushEvent.error(e)); } }); } // These must happen outside the synchronized block as we // call out to user code queueRef.set(getQueueForInternalBuffering(maxEvents.getAsInt())); scheduler.schedule( getWindowTask(eventStream, f, time, maxEvents, lock, expectedCounter + 1, queueRef, timestamp, counter, executor), time.get().toNanos(), NANOSECONDS); }; } private <R> void aggregateAndForward(BiFunction<Long,Collection<T>,R> f, AbstractPushStreamImpl<R> eventStream, PushEvent< ? extends T> event, Queue<T> queue, Executor executor, long elapsed) { executor.execute(() -> { try { if (!queue.offer(event.getData())) { ((ArrayQueue<T>) queue).forcePush(event.getData()); } long result = eventStream.handleEvent(PushEvent.data( f.apply(Long.valueOf(NANOSECONDS.toMillis(elapsed)), queue))); if (result < 0) { close(); } } catch (Exception e) { close(PushEvent.error(e)); } }); } @Override public Promise<Void> forEach(Consumer< ? super T> action) { Deferred<Void> d = new Deferred<>(); updateNext((event) -> { try { switch(event.getType()) { case DATA: action.accept(event.getData()); return CONTINUE; case CLOSE: d.resolve(null); break; case ERROR: d.fail(event.getFailure()); break; } close(event.nodata()); return ABORT; } catch (Exception e) { d.fail(e); return ABORT; } }); begin(); return d.getPromise(); } @Override public Promise<Object[]> toArray() { return collect(Collectors.toList()) .map(List::toArray); } @Override public <A extends T> Promise<A[]> toArray(IntFunction<A[]> generator) { return collect(Collectors.toList()) .map(l -> l.toArray(generator.apply(l.size()))); } @Override public Promise<T> reduce(T identity, BinaryOperator<T> accumulator) { Deferred<T> d = new Deferred<>(); AtomicReference<T> iden = new AtomicReference<T>(identity); updateNext(event -> { try { switch(event.getType()) { case DATA: iden.accumulateAndGet(event.getData(), accumulator); return CONTINUE; case CLOSE: d.resolve(iden.get()); break; case ERROR: d.fail(event.getFailure()); break; } close(event.nodata()); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } @Override public Promise<Optional<T>> reduce(BinaryOperator<T> accumulator) { Deferred<Optional<T>> d = new Deferred<>(); AtomicReference<T> iden = new AtomicReference<T>(null); updateNext(event -> { try { switch(event.getType()) { case DATA: if (!iden.compareAndSet(null, event.getData())) iden.accumulateAndGet(event.getData(), accumulator); return CONTINUE; case CLOSE: d.resolve(Optional.ofNullable(iden.get())); break; case ERROR: d.fail(event.getFailure()); break; } close(event.nodata()); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } @Override public <U> Promise<U> reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) { Deferred<U> d = new Deferred<>(); AtomicReference<U> iden = new AtomicReference<>(identity); updateNext(event -> { try { switch(event.getType()) { case DATA: iden.updateAndGet((e) -> accumulator.apply(e, event.getData())); return CONTINUE; case CLOSE: d.resolve(iden.get()); break; case ERROR: d.fail(event.getFailure()); break; } close(event.nodata()); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } @Override public <R, A> Promise<R> collect(Collector<? super T, A, R> collector) { A result = collector.supplier().get(); Deferred<R> d = new Deferred<>(); updateNext(event -> { try { switch(event.getType()) { case DATA: collector.accumulator().accept(result, event.getData()); return CONTINUE; case CLOSE: d.resolve(collector.finisher().apply(result)); break; case ERROR: d.fail(event.getFailure()); break; } close(event.nodata()); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } @Override public Promise<Optional<T>> min(Comparator<? super T> comparator) { return reduce((a, b) -> comparator.compare(a, b) <= 0 ? a : b); } @Override public Promise<Optional<T>> max(Comparator<? super T> comparator) { return reduce((a, b) -> comparator.compare(a, b) > 0 ? a : b); } @Override public Promise<Long> count() { Deferred<Long> d = new Deferred<>(); LongAdder counter = new LongAdder(); updateNext((event) -> { try { switch(event.getType()) { case DATA: counter.add(1); return CONTINUE; case CLOSE: d.resolve(Long.valueOf(counter.sum())); break; case ERROR: d.fail(event.getFailure()); break; } close(event.nodata()); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } @Override public Promise<Boolean> anyMatch(Predicate<? super T> predicate) { return filter(predicate).findAny() .map(Optional::isPresent); } @Override public Promise<Boolean> allMatch(Predicate<? super T> predicate) { return filter(x -> !predicate.test(x)).findAny() .map(o -> Boolean.valueOf(!o.isPresent())); } @Override public Promise<Boolean> noneMatch(Predicate<? super T> predicate) { return filter(predicate).findAny() .map(o -> Boolean.valueOf(!o.isPresent())); } @Override public Promise<Optional<T>> findFirst() { Deferred<Optional<T>> d = new Deferred<>(); updateNext((event) -> { try { Optional<T> o = null; switch(event.getType()) { case DATA: o = Optional.of(event.getData()); break; case CLOSE: o = Optional.empty(); break; case ERROR: d.fail(event.getFailure()); return ABORT; } if(!d.getPromise().isDone()) d.resolve(o); return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } @Override public Promise<Optional<T>> findAny() { return findFirst(); } @Override public Promise<Long> forEachEvent(PushEventConsumer< ? super T> action) { Deferred<Long> d = new Deferred<>(); LongAdder la = new LongAdder(); updateNext((event) -> { try { switch(event.getType()) { case DATA: long value = action.accept(event); la.add(value); return value; case CLOSE: try { action.accept(event); } finally { d.resolve(Long.valueOf(la.sum())); } break; case ERROR: try { action.accept(event); } finally { d.fail(event.getFailure()); } break; } return ABORT; } catch (Exception e) { close(PushEvent.error(e)); return ABORT; } }); begin(); return d.getPromise(); } }
7,931
0
Create_ds/aries/web/web-itests/src/test/java/org/apache/aries/web
Create_ds/aries/web/web-itests/src/test/java/org/apache/aries/web/test/TestClass.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.web.test; import javax.naming.InitialContext; import javax.naming.NamingException; public class TestClass { private InitialContext ctx; public TestClass() throws NamingException { ctx = new InitialContext(); } }
7,932
0
Create_ds/aries/web/web-itests/src/test/java/org/apache/aries/web/converter
Create_ds/aries/web/web-itests/src/test/java/org/apache/aries/web/converter/itest/WabConverterITest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.web.converter.itest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Dictionary; import javax.inject.Inject; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.unittest.fixture.ArchiveFixture; import org.apache.aries.unittest.fixture.ArchiveFixture.ZipFixture; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class WabConverterITest extends AbstractIntegrationTest { @Inject protected BundleContext bundleContext; private void createTestWar(File warFile) throws IOException { ZipFixture testWar = ArchiveFixture.newJar().binary( "WEB-INF/classes/org/apache/aries/web/test/TestClass.class", getClass().getClassLoader().getResourceAsStream( "org/apache/aries/web/test/TestClass.class")); FileOutputStream fout = new FileOutputStream(warFile); testWar.writeOut(fout); fout.close(); } @Test public void getStarted() throws Exception { File testWar = File.createTempFile("test", ".war"); createTestWar(testWar); String baseUrl = "webbundle:" + testWar.toURI().toURL().toExternalForm(); assertTrue("Time out waiting for webbundle URL handler", waitForURLHandler(baseUrl)); Bundle converted = bundleContext.installBundle(baseUrl + "?Bundle-SymbolicName=test.war.bundle&Web-ContextPath=foo"); assertNotNull(converted); Dictionary<String, String> man = converted.getHeaders(); assertEquals("test.war.bundle", man.get(Constants.BUNDLE_SYMBOLICNAME)); assertEquals("/foo", man.get("Web-ContextPath")); assertTrue(man.get(Constants.IMPORT_PACKAGE).contains("javax.naming")); new File("test.war").delete(); } private boolean waitForURLHandler(String url) { int maxRepetition = 100; for (int i = 0; i < maxRepetition; i++) { try { new URL(url); return true; } catch (MalformedURLException e) { try { Thread.sleep(100); } catch (InterruptedException ee) { return false; } } } return false; } public Option baseOptions() { String localRepo = getLocalRepo(); return composite( junitBundles(), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), when(localRepo != null).useOptions( vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo))); } @Configuration public Option[] configuration() { return options( // bootDelegation(), baseOptions(), mavenBundle("org.osgi", "org.osgi.compendium"), mavenBundle("org.apache.felix", "org.apache.felix.configadmin"), // Bundles mavenBundle("org.apache.aries.web", "org.apache.aries.web.urlhandler"), mavenBundle("org.apache.aries", "org.apache.aries.util"), mavenBundle("org.ow2.asm", "asm-debug-all"), mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy"), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit")); } private MavenArtifactProvisionOption mavenBundle(String groupId, String artifactId) { return CoreOptions.mavenBundle().groupId(groupId) .artifactId(artifactId).versionAsInProject(); } }
7,933
0
Create_ds/aries/web/web-urlhandler/src/test/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/test/java/org/apache/aries/web/converter/impl/WabConverterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.apache.aries.web.converter.WarToWabConverter; import org.apache.aries.web.converter.WarToWabConverter.InputStreamProvider; import org.junit.Test; import org.osgi.framework.Constants; /** * These tests do not cover the complete functionality (as yet). Rather this gives a place for adding * smaller tests for individual units of work that don't need to be tested by converting a whole WAR file. */ public class WabConverterTest { public static final String WAR_FILE_NAME_WO_SUFFIX = "test"; public static final String WAR_FILE_NAME = WAR_FILE_NAME_WO_SUFFIX + ".war"; private static final String SERVLET_IMPORTS = "javax.servlet;version=2.5," + "javax.servlet.http;version=2.5"; private static final String JSP_IMPORTS = "javax.servlet.jsp;version=2.1," + "javax.servlet.jsp.el;version=2.1," + "javax.servlet.jsp.tagext;version=2.1," + "javax.servlet.jsp.resources;version=2.1"; private static final String DEFAULT_IMPORTS = SERVLET_IMPORTS + "," + JSP_IMPORTS; /** * Test that we can handle a null manifest (in case a jar archive was created without manifest) */ @Test public void testNullManifest() throws Exception { Properties properties = new Properties(); properties.put(WarToWabConverter.WEB_CONTEXT_PATH, "/test"); WarToWabConverterImpl sut = new WarToWabConverterImpl(makeTestFile(new byte[0]), WAR_FILE_NAME, properties); Manifest res = sut.updateManifest(null); Attributes attrs = res.getMainAttributes(); assertTrue(attrs.getValue("Import-Package").contains("javax.servlet")); } @Test public void testImportPackageMerge() throws Exception { Properties properties = new Properties(); properties.put(WarToWabConverter.WEB_CONTEXT_PATH, "/test"); WarToWabConverterImpl sut = new WarToWabConverterImpl(makeTestFile(new byte[0]), WAR_FILE_NAME, properties); Manifest input = new Manifest(); input.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, "com.ibm.test,javax.servlet.http"); Manifest res = sut.updateManifest(input); Attributes attrs = res.getMainAttributes(); assertEquals( "com.ibm.test,"+ "javax.servlet.http,"+ "javax.servlet;version=2.5,"+ JSP_IMPORTS, attrs.getValue(Constants.IMPORT_PACKAGE)); } @Test public void testImportPackageWithAttributesMerge() throws Exception { Attributes attrs = convertWithProperties( WarToWabConverter.WEB_CONTEXT_PATH, "/test", Constants.IMPORT_PACKAGE, "javax.servlet.jsp; version=\"[2.0,2.1]\",javax.servlet.jsp.tagext; version=\"[2.0,2.1]\""); String actual = attrs.getValue(Constants.IMPORT_PACKAGE); System.out.println(actual); assertEquals( "javax.servlet.jsp; version=\"[2.0,2.1]\"," + "javax.servlet.jsp.tagext; version=\"[2.0,2.1]\"," + "javax.servlet;version=2.5," + "javax.servlet.http;version=2.5," + "javax.servlet.jsp.el;version=2.1," + "javax.servlet.jsp.resources;version=2.1", actual); } @Test public void testAcceptNoManifest() throws Exception { final ByteArrayOutputStream bout = new ByteArrayOutputStream(); JarOutputStream out = new JarOutputStream(bout); out.putNextEntry(new ZipEntry("random.html")); out.write("hello world".getBytes()); out.close(); InputStreamProvider input = makeTestFile(bout.toByteArray()); Properties props = new Properties(); props.put(WarToWabConverter.WEB_CONTEXT_PATH, "/test"); props.put(Constants.BUNDLE_SYMBOLICNAME, "test.bundle"); WarToWabConverterImpl sut = new WarToWabConverterImpl(input, WAR_FILE_NAME, props); @SuppressWarnings("resource") Manifest m = new JarInputStream(sut.getWAB()).getManifest(); assertEquals("test.bundle", m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME)); } @Test public void testDefaultProperties() throws Exception { Attributes attrs = convertWithProperties( WarToWabConverter.WEB_CONTEXT_PATH, "/test"); assertTrue(attrs.getValue(Constants.BUNDLE_SYMBOLICNAME).startsWith(WAR_FILE_NAME_WO_SUFFIX)); assertEquals("1.0", attrs.getValue(Constants.BUNDLE_VERSION)); assertEquals(DEFAULT_IMPORTS, attrs.getValue(Constants.IMPORT_PACKAGE)); assertEquals("WEB-INF/classes",attrs.getValue(Constants.BUNDLE_CLASSPATH)); } @Test public void testPropertySupport() throws Exception { Attributes attrs = convertWithProperties( WarToWabConverter.WEB_CONTEXT_PATH, "WebFiles", Constants.BUNDLE_VERSION, "2.0", Constants.IMPORT_PACKAGE, "org.apache.aries.test;version=2.5,org.apache.aries.test.eba;version=1.0"); assertEquals("/WebFiles", attrs.getValue(WarToWabConverter.WEB_CONTEXT_PATH)); assertEquals("2.0", attrs.getValue(Constants.BUNDLE_VERSION)); assertEquals("org.apache.aries.test;version=2.5,org.apache.aries.test.eba;version=1.0," + DEFAULT_IMPORTS, attrs.getValue(Constants.IMPORT_PACKAGE)); } @Test public void testPropertyCaseInsensitiveSupport() throws Exception { Attributes attrs = convertWithProperties( "web-contextpath", "WebFiles", "bundle-VErsion", "1.0", "import-PACKAGE", "org.apache.aries.test;version=2.5,org.apache.aries.test.eba;version=1.0"); assertEquals("/WebFiles", attrs.getValue(WarToWabConverter.WEB_CONTEXT_PATH)); assertEquals("1.0", attrs.getValue(Constants.BUNDLE_VERSION)); assertEquals("org.apache.aries.test;version=2.5,org.apache.aries.test.eba;version=1.0," + DEFAULT_IMPORTS, attrs.getValue(Constants.IMPORT_PACKAGE)); } @Test public void testBundleContextPathOverride() throws Exception { Manifest m = new Manifest(); Attributes attrs = m.getMainAttributes(); attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.test"); attrs.putValue(Constants.BUNDLE_VERSION, "1.0"); attrs.putValue(Constants.IMPORT_PACKAGE, "org.apache.util,org.apache.test;version=1.0"); attrs.putValue(Constants.BUNDLE_CLASSPATH, "jsp/classes"); attrs = convertWithProperties(m, WarToWabConverter.WEB_CONTEXT_PATH, "WebFiles"); assertEquals("org.apache.test", attrs.getValue(Constants.BUNDLE_SYMBOLICNAME)); assertEquals("1.0", attrs.getValue(Constants.BUNDLE_VERSION)); assertTrue(attrs.getValue(Constants.IMPORT_PACKAGE).contains("org.apache.util")); assertTrue(attrs.getValue(Constants.IMPORT_PACKAGE).contains("org.apache.test;version=1.0")); assertEquals("jsp/classes", attrs.getValue(Constants.BUNDLE_CLASSPATH)); assertEquals("/WebFiles", attrs.getValue(WarToWabConverter.WEB_CONTEXT_PATH)); } @Test public void testBundleContextPathManifestOverride() throws Exception { Manifest m = new Manifest(); Attributes attrs = m.getMainAttributes(); attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.test"); attrs.putValue(WarToWabConverter.WEB_CONTEXT_PATH, "test"); attrs.putValue(Constants.BUNDLE_VERSION, "1.0"); attrs.putValue(Constants.IMPORT_PACKAGE, "org.apache.util,org.apache.test;version=1.0"); attrs.putValue(Constants.BUNDLE_CLASSPATH, "jsp/classes"); attrs = convertWithProperties(m, WarToWabConverter.WEB_CONTEXT_PATH, "WebFiles"); assertEquals("org.apache.test", attrs.getValue(Constants.BUNDLE_SYMBOLICNAME)); assertEquals("1.0", attrs.getValue(Constants.BUNDLE_VERSION)); assertTrue(attrs.getValue(Constants.IMPORT_PACKAGE).contains("org.apache.util")); assertTrue(attrs.getValue(Constants.IMPORT_PACKAGE).contains("org.apache.test;version=1.0")); assertEquals("jsp/classes", attrs.getValue(Constants.BUNDLE_CLASSPATH)); assertEquals("/WebFiles", attrs.getValue(WarToWabConverter.WEB_CONTEXT_PATH)); } @Test public void testBundleManifestOverride() throws Exception { Manifest m = new Manifest(); Attributes attrs = m.getMainAttributes(); attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "org.apache.test"); attrs.putValue(WarToWabConverter.WEB_CONTEXT_PATH, "test"); attrs.putValue(Constants.BUNDLE_VERSION, "1.0"); attrs.putValue(Constants.IMPORT_PACKAGE, "org.apache.util,org.apache.test;version=1.0"); attrs.putValue(Constants.BUNDLE_CLASSPATH, "jsp/classes"); try { convertWithProperties(m, WarToWabConverter.WEB_CONTEXT_PATH, "WebFiles", Constants.BUNDLE_SYMBOLICNAME, "foobar"); fail("Conversion did not fail as expected"); } catch (IOException e) { // that's expected } } private Attributes convertWithProperties(Manifest m, String ... props) throws Exception { Properties properties = new Properties(); for (int i=0;i<props.length;i+=2) { properties.put(props[i], props[i+1]); } byte[] bytes = new byte[0]; if (m != null) { m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1"); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); JarOutputStream out = new JarOutputStream(bout,m); out.close(); bytes = bout.toByteArray(); } WarToWabConverterImpl sut = new WarToWabConverterImpl(makeTestFile(bytes), WAR_FILE_NAME, properties); return sut.getWABManifest().getMainAttributes(); } private Attributes convertWithProperties(String ... props) throws Exception { return convertWithProperties(null, props); } private InputStreamProvider makeTestFile(final byte[] content) { return new InputStreamProvider() { public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(content); } }; } }
7,934
0
Create_ds/aries/web/web-urlhandler/src/test/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/test/java/org/apache/aries/web/converter/impl/JSPImportParserTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Collection; import org.apache.aries.web.converter.impl.JSPImportParser; import org.junit.Test; public class JSPImportParserTest { @Test public void testJSPImportParser () throws Exception { InputStream helloImport = getClass().getClassLoader().getResourceAsStream("JSPs/helloImport.jsp"); Collection<String> imports = JSPImportParser.getImports(helloImport); assertTrue("Four imports expected", imports.size() == 4); assertTrue(imports.contains("javax.jms")); assertTrue(imports.contains("javax.mystuff")); assertTrue(imports.contains("javax.transaction")); assertTrue(imports.contains("a.b")); assertFalse(imports.contains("java.util")); } }
7,935
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/WabConversion.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter; import java.io.IOException; import java.io.InputStream; import java.util.jar.Manifest; public interface WabConversion { /** * @return The WAB Manifest of the converted WAB */ public Manifest getWABManifest() throws IOException; /** * @return The InputStream to read the bytes of the converted WAB */ public InputStream getWAB() throws IOException; }
7,936
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/WarToWabConverter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Service interface for WAR to WAB conversion */ public interface WarToWabConverter { /** * Support class for WabConverter to allow multiple passes over an input war * archive without requiring in-memory buffering. */ public static interface InputStreamProvider { InputStream getInputStream() throws IOException; } public static final String WEB_CONTEXT_PATH = "Web-ContextPath"; /** * Generate the converter WAB file. This file includes all the files from the input * and has the new manifest. * @param input * @param name The name of the war file * @param properties Properties to influence the conversion as defined in RFC66. The following * properties are supported * <ul> * <li>Bundle-ClassPath</li> * <li>Bundle-ManifestVersion</li> * <li>Bundle-SymbolicName</li> * <li>Bundle-Version</li> * <li>Import-Package</li> * <li>Web-ContextPath</li> * <li>Web-JSPExtractLocation</li> * </ul> * Except for Bundle-ClassPath and Import-Package any supplied properties will * overwrite values specified in an existing bundle manifest. For Bundle-ClassPath and Import-Package * the supplied values will be joined to those specified in a bundle manifest * (if it exists) and also the results of the scan of the WAR file. * @return */ WabConversion convert(InputStreamProvider input, String name, Properties properties) throws IOException; }
7,937
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/JSPImportParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collection; import java.util.LinkedList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JSPImportParser { /** * * @param is * An input stream of character-based text. We expect this to be JSP * source code. * @return Each java package found within valid JSP import tags * @throws IOException */ public static Collection<String> getImports (InputStream is) throws IOException { Collection<String> importedPackages = new LinkedList<String>(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; do { line = reader.readLine(); // searchMatchedGroupForImports could take (line): I've not done that because // the entry trace, once working, will print out lots of useless information. if (line != null) { Matcher hasJSPimport = lineWithJSPimport.matcher(line); if (hasJSPimport.find()) { Collection<String> foundImports = searchMatchedGroupForImports (hasJSPimport.group()); for (String found : foundImports) { if (!importedPackages.contains(found)) { importedPackages.add(found); } } } } } while (line != null); return importedPackages; } private static final Pattern lineWithJSPimport = Pattern.compile("<%@\\s*page\\s*import.*%>"); private static final Pattern stanzaEnd = Pattern.compile("%>"); private static final Pattern imports = Pattern.compile("import\\s*=\\s*\"(.*?)\""); /** * * @param groupExtent a block of text known to contain a JSP import * @return Each package found within valid JSP import tags */ private static LinkedList<String> searchMatchedGroupForImports (String groupExtent) { LinkedList<String> packagesFound = new LinkedList<String>(); String importStanzas[] = stanzaEnd.split(groupExtent); for (String s: importStanzas){ Matcher oneImport = imports.matcher(s); if (oneImport.find()) { String thisStanzasImports = oneImport.group(); String allPackages = thisStanzasImports.substring(thisStanzasImports.indexOf("\"")+1, thisStanzasImports.lastIndexOf("\"")); String [] imports = allPackages.split(","); for (String p : imports) { String thisPackage = p.substring(0,p.lastIndexOf('.')).trim(); if (!!!thisPackage.startsWith("java.")) packagesFound.add(thisPackage); } } } return packagesFound; } }
7,938
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/PackageFinder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.signature.SignatureReader; import org.objectweb.asm.signature.SignatureVisitor; public class PackageFinder extends ClassVisitor//AnnotationVisitor, SignatureVisitor, ClassVisitor, //FieldVisitor, MethodVisitor { private static int asmVersion = Opcodes.ASM4; private PackageFinderSignatureVisitor pfsv; private PackageFinderAnnotationVisitor pfav; private PackageFinderFieldVisitor pffv; private PackageFinderMethodVisitor pfmv; public PackageFinder() { super(asmVersion); this.pfsv = new PackageFinderSignatureVisitor(); this.pfav = new PackageFinderAnnotationVisitor(); this.pffv = new PackageFinderFieldVisitor(); this.pfmv = new PackageFinderMethodVisitor(); } private Set<String> packages = new HashSet<String>(); private Set<String> exemptPackages = new HashSet<String>(); // stored value of the signature class name private String signatureOuterClass = null; public Set<String> getImportPackages() { // Remove entries that will be imported by default for (Iterator<String> i = packages.iterator(); i.hasNext();) { if (i.next().startsWith("java.")) i.remove(); } return packages; } public Set<String> getExemptPackages() { return exemptPackages; } private String getPackageName(String name) { String packageName = null; if (name != null) { int index = name.lastIndexOf('/'); if (index > 0) packageName = name.substring(0, index); } return packageName; } private String canonizePackage(String rawPackage) { String result = rawPackage.replace('/', '.'); // handle arrays return result.replaceFirst("^\\[+L", ""); } private void addPackage(String packageName) { if (packageName != null) { packages.add(canonizePackage(packageName)); } } private void addExemptPackage(String packageName) { if (packageName != null) exemptPackages.add(canonizePackage(packageName)); } private void addPackages(String[] packageNames) { if (packageNames != null) { for (String s : packageNames) if (s != null) { packages.add(canonizePackage(s)); } } } private String getResolvedPackageName(String name) { String resolvedName = null; if (name != null) resolvedName = getPackageName(name); return resolvedName; } private String[] getResolvedPackageNames(String[] names) { String[] resolvedNames = null; if (names != null) { resolvedNames = new String[names.length]; int i = 0; for (String s : names) resolvedNames[i++] = getResolvedPackageName(s); } return resolvedNames; } private String getDescriptorInfo(String descriptor) { String type = null; if (descriptor != null) type = getType(Type.getType(descriptor)); return type; } private String[] getMethodDescriptorInfo(String descriptor) { String[] descriptors = null; if (descriptor != null) { Type[] types = Type.getArgumentTypes(descriptor); descriptors = new String[types.length + 1]; descriptors[0] = getType(Type.getReturnType(descriptor)); int i = 1; for (Type t : types) descriptors[i++] = getType(t); } return descriptors; } private String getType(Type t) { String type = null; switch (t.getSort()) { case Type.ARRAY: type = getType(t.getElementType()); break; case Type.OBJECT: type = getPackageName(t.getInternalName()); break; } return type; } private void addSignaturePackages(String signature) { if (signature != null) new SignatureReader(signature).accept(pfsv); } private void addResolvedSignaturePackages(String signature) { if (signature != null) new SignatureReader(signature).acceptType(pfsv); } // // ClassVisitor methods // public void visit(int arg0, int arg1, String name, String signature, String parent, String[] interfaces) { // We dont want to import our own packages so we add this classes package name to the // list of exempt packages. addExemptPackage(getPackageName(name)); if (signature == null) { addPackage(getResolvedPackageName(parent)); addPackages(getResolvedPackageNames(interfaces)); } else addSignaturePackages(signature); } public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { addPackage(getDescriptorInfo(descriptor)); return pfav; } public void visitAttribute(Attribute arg0) { // No-op } public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) { if (signature == null) addPackage(getDescriptorInfo(descriptor)); else addResolvedSignaturePackages(signature); if (value instanceof Type) addPackage(getType((Type) value)); return pffv; } public void visitInnerClass(String arg0, String arg1, String arg2, int arg3) { // no-op } public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { if (signature == null) addPackages(getMethodDescriptorInfo(descriptor)); else addSignaturePackages(signature); addPackages(getResolvedPackageNames(exceptions)); return pfmv; } public void visitOuterClass(String arg0, String arg1, String arg2) { // no-op } public void visitSource(String arg0, String arg1) { // no-op } public void visitEnd() { // no-op } public class PackageFinderSignatureVisitor extends SignatureVisitor { public PackageFinderSignatureVisitor() { super(asmVersion); } // // SignatureVisitor methods // public SignatureVisitor visitArrayType() { return pfsv; } public void visitBaseType(char arg0) { // no-op } public SignatureVisitor visitClassBound() { return pfsv; } public void visitClassType(String name) { signatureOuterClass = name; addPackage(getResolvedPackageName(name)); } public void visitInnerClassType(String name) { addPackage(getResolvedPackageName(signatureOuterClass + "$" + name)); } public SignatureVisitor visitExceptionType() { return pfsv; } public void visitFormalTypeParameter(String arg0) { // no-op } public SignatureVisitor visitInterface() { return pfsv; } public SignatureVisitor visitParameterType() { return pfsv; } public SignatureVisitor visitReturnType() { return pfsv; } public SignatureVisitor visitSuperclass() { return pfsv; } public void visitTypeArgument() { // no-op } public SignatureVisitor visitTypeArgument(char arg0) { return pfsv; } public void visitTypeVariable(String arg0) { // no-op } public SignatureVisitor visitInterfaceBound() { return pfsv; } } public class PackageFinderAnnotationVisitor extends AnnotationVisitor { public PackageFinderAnnotationVisitor() { super(asmVersion); } // // AnnotationVisitor Methods // public void visit(String arg0, Object value) { if (value instanceof Type) { addPackage(getType((Type) value)); } } public AnnotationVisitor visitAnnotation(String arg0, String descriptor) { addPackage(getDescriptorInfo(descriptor)); return pfav; } public AnnotationVisitor visitArray(String arg0) { return pfav; } public void visitEnum(String name, String desc, String value) { addPackage(getDescriptorInfo(desc)); } } public class PackageFinderFieldVisitor extends FieldVisitor { public PackageFinderFieldVisitor() { super(asmVersion); } } public class PackageFinderMethodVisitor extends MethodVisitor { public PackageFinderMethodVisitor() { super(asmVersion); } // // MethodVisitor methods // public AnnotationVisitor visitAnnotationDefault() { return pfav; } public void visitCode() { // no-op } public void visitFrame(int arg0, int arg1, Object[] arg2, int arg3, Object[] arg4) { // no-op } public void visitIincInsn(int arg0, int arg1) { // no-op } public void visitInsn(int arg0) { // no-op } public void visitIntInsn(int arg0, int arg1) { // no-op } public void visitJumpInsn(int arg0, Label arg1) { // no-op } public void visitLabel(Label arg0) { // no-op } public void visitLdcInsn(Object type) { if (type instanceof Type) addPackage(getType((Type) type)); } public void visitLineNumber(int arg0, Label arg1) { // no-op } public void visitLocalVariable(String name, String descriptor, String signature, Label start, Label end, int index) { addResolvedSignaturePackages(signature); } public void visitLookupSwitchInsn(Label arg0, int[] arg1, Label[] arg2) { // no-op } public void visitMaxs(int arg0, int arg1) { // no-op } public void visitMethodInsn(int opcode, String owner, String name, String descriptor) { addPackage(getResolvedPackageName(owner)); addPackages(getMethodDescriptorInfo(descriptor)); } public void visitMultiANewArrayInsn(String descriptor, int arg1) { addPackage(getDescriptorInfo(descriptor)); } public AnnotationVisitor visitParameterAnnotation(int arg0, String descriptor, boolean arg2) { addPackage(getDescriptorInfo(descriptor)); return pfav; } public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { //no-op } public void visitTryCatchBlock(Label arg0, Label arg1, Label arg2, String type) { addPackage(getResolvedPackageName(type)); } public void visitTypeInsn(int arg0, String type) { addPackage(getResolvedPackageName(type)); } public void visitVarInsn(int arg0, int arg1) { // no-op } public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { addPackage(getResolvedPackageName(owner)); addPackage(getDescriptorInfo(descriptor)); } } }
7,939
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/WarToWabConverterService.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.io.IOException; import java.util.Properties; import org.apache.aries.web.converter.WabConversion; import org.apache.aries.web.converter.WarToWabConverter; public class WarToWabConverterService implements WarToWabConverter { public WabConversion convert(InputStreamProvider input, String name, Properties properties) throws IOException { return new WarToWabConverterImpl(input, name, properties); } }
7,940
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/ClassPathBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.StringTokenizer; import java.util.jar.Manifest; public class ClassPathBuilder { private Map<String, Manifest> manifests; /** * This class takes a map of <jarFileName, manifest> pairs which are contained in * a particular jar file. * The updatePath method then uses this list to analyse the contents of the manifests * and looks for any dependencies in the other manifests in the jar. * @param manifests */ public ClassPathBuilder(Map<String, Manifest> manifests) { this.manifests = manifests; } /** * We take a full qualified jar file name and search its manifest for any other classpath * dependencies within the other manifest in the parent jar file. * @param jarFile * @param classPath * @return * @throws IOException */ public ArrayList<String> updatePath(String jarFile, ArrayList<String> classPath) throws IOException { // Get the classpath entries from this manifest and merge them into ours Manifest manifest = manifests.get(jarFile); if (manifest == null) return classPath; String dependencies = manifest.getMainAttributes().getValue("Class-Path"); if (dependencies == null) dependencies = manifest.getMainAttributes().getValue("Class-path"); if (dependencies != null) { // Search through the entries in the classpath StringTokenizer tok = new StringTokenizer(dependencies, ";"); while (tok.hasMoreTokens()) { String path = jarFile.substring(0, jarFile.lastIndexOf('/'));; String entry = tok.nextToken(); // Resolve the path to its canonical form path = new File("/"+path+"/"+entry).getCanonicalPath().replace('\\','/'); path = path.substring(path.indexOf('/')+1); // If we havent already located this dependency before then we add this to our // list of dependencies if (entry.endsWith(".jar") && manifests.keySet().contains(path) && !classPath.contains(path) && !path.startsWith("WEB-INF/lib/")) { classPath.add(path); // Recursively search the new classpath entry for more dependencies classPath = updatePath(path, classPath); } } } return classPath; } }
7,941
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/CaseInsensitiveMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.aries.web.converter.WarToWabConverter; import org.osgi.framework.Constants; /** * Simple key case-insensitive map where only selected set of keys are * treated in case-insensitive way. */ @SuppressWarnings("serial") public class CaseInsensitiveMap extends HashMap<String, String> { private static final Map<String, String> DEFAULT_KEY_MAP = new HashMap<String, String>(); static { addKeyMapping(DEFAULT_KEY_MAP, Constants.BUNDLE_SYMBOLICNAME); addKeyMapping(DEFAULT_KEY_MAP, Constants.BUNDLE_VERSION); addKeyMapping(DEFAULT_KEY_MAP, Constants.BUNDLE_MANIFESTVERSION); addKeyMapping(DEFAULT_KEY_MAP, Constants.IMPORT_PACKAGE); addKeyMapping(DEFAULT_KEY_MAP, Constants.BUNDLE_CLASSPATH); addKeyMapping(DEFAULT_KEY_MAP, WarToWabConverter.WEB_CONTEXT_PATH); } private static void addKeyMapping(Map<String, String> mappings, String name) { mappings.put(name.toLowerCase(), name); } private Map<String, String> keyMap; public CaseInsensitiveMap() { this.keyMap = new HashMap<String, String>(DEFAULT_KEY_MAP); } public CaseInsensitiveMap(Map<String, String> source) { this(); putAll(source); } public CaseInsensitiveMap(Properties source) { this(); for (Map.Entry<Object, Object> entry : source.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); put(key, value); } } @Override public String put(String name, String value) { return super.put(getMappedName(name), value); } @Override public String get(Object name) { if (!(name instanceof String)) { return null; } return super.get(getMappedName((String) name)); } @Override public boolean containsKey(Object name) { if (!(name instanceof String)) { return false; } return super.containsKey(getMappedName((String) name)); } private String getMappedName(String name) { String mappedName = keyMap.get(name.toLowerCase()); if (mappedName == null) { mappedName = name; } return mappedName; } }
7,942
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/CachedOutputStream.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class CachedOutputStream extends OutputStream { private static final int DEFAULT_THRESHOLD = 64 * 1024; private OutputStream currentStream; private long threshold; private int totalLength; private boolean inmem; private List<InputStream> streams; private File tempFile; private File outputDir; public CachedOutputStream() { this(DEFAULT_THRESHOLD, null); } public CachedOutputStream(long threshold, File outputDir) { this.threshold = threshold; this.outputDir = outputDir; this.currentStream = new ByteArrayOutputStream(2048); this.inmem = true; this.streams = new ArrayList<InputStream>(1); } public void flush() throws IOException { currentStream.flush(); } public void close() throws IOException { currentStream.flush(); currentStream.close(); } public void write(byte[] b) throws IOException { write(b, 0, b.length); } public void write(byte[] b, int off, int len) throws IOException { totalLength += len; if (inmem && totalLength > threshold) { createFileOutputStream(); } currentStream.write(b, off, len); } public void write(int b) throws IOException { totalLength++; if (inmem && totalLength > threshold) { createFileOutputStream(); } currentStream.write(b); } private void createFileOutputStream() throws IOException { ByteArrayOutputStream bout = (ByteArrayOutputStream) currentStream; if (outputDir == null) { tempFile = File.createTempFile("cos", "tmp"); } else { tempFile = File.createTempFile("cos", "tmp", outputDir); } currentStream = new BufferedOutputStream(new FileOutputStream(tempFile)); bout.writeTo(currentStream); inmem = false; } public void destroy() { streams.clear(); if (tempFile != null) { tempFile.delete(); } } public int size() { return totalLength; } public InputStream getInputStream() throws IOException { close(); if (inmem) { return new ByteArrayInputStream(((ByteArrayOutputStream) currentStream).toByteArray()); } else { try { FileInputStream fileInputStream = new FileInputStream(tempFile) { public void close() throws IOException { super.close(); maybeDeleteTempFile(this); } }; streams.add(fileInputStream); return fileInputStream; } catch (FileNotFoundException e) { throw new IOException("Cached file was deleted, " + e.toString()); } } } private void maybeDeleteTempFile(Object stream) { streams.remove(stream); if (tempFile != null && streams.isEmpty()) { tempFile.delete(); tempFile = null; } } }
7,943
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/Activator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import java.util.Dictionary; import java.util.Hashtable; import org.apache.aries.web.converter.WarToWabConverter; import org.apache.aries.web.url.WAR_URLServiceHandler; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.service.url.URLStreamHandlerService; public class Activator implements BundleActivator { @Override public void start(BundleContext context) throws Exception { Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("url.handler.protocol", new String[]{"webbundle"}); context.registerService(URLStreamHandlerService.class, new WAR_URLServiceHandler(), props); context.registerService(WarToWabConverter.class, new WarToWabConverterService(), null); } @Override public void stop(BundleContext context) throws Exception { // Services will be unregistered by framework } }
7,944
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/converter/impl/WarToWabConverterImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.converter.impl; import static org.apache.aries.web.converter.WarToWabConverter.WEB_CONTEXT_PATH; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.TreeSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import org.apache.aries.web.converter.WabConversion; import org.apache.aries.web.converter.WarToWabConverter.InputStreamProvider; import org.objectweb.asm.ClassReader; import org.osgi.framework.Constants; public class WarToWabConverterImpl implements WabConversion { private static final String DEFAULT_BUNDLE_VERSION = "1.0"; private static final String DEFAULT_BUNDLE_MANIFESTVERSION = "2"; private static final String INITIAL_CLASSPATH_ENTRY = "WEB-INF/classes"; private static final String CLASSPATH_LIB_PREFIX = "WEB-INF/lib/"; private static final String SERVLET_IMPORTS = "javax.servlet;version=2.5," + "javax.servlet.http;version=2.5"; private static final String JSP_IMPORTS = "javax.servlet.jsp;version=2.1," + "javax.servlet.jsp.el;version=2.1," + "javax.servlet.jsp.tagext;version=2.1," + "javax.servlet.jsp.resources;version=2.1"; private static final String DEFAULT_IMPORT_PACKAGE_LIST = SERVLET_IMPORTS + "," + JSP_IMPORTS; private CaseInsensitiveMap properties; // InputStream for the new WAB file private CachedOutputStream wab; private Manifest wabManifest; private String warName; private InputStreamProvider input; // State used for updating the manifest private Set<String> importPackages; private Set<String> exemptPackages; private Map<String, Manifest> manifests; private ArrayList<String> classPath; private boolean signed; public WarToWabConverterImpl(InputStreamProvider warFile, String name, Properties properties) throws IOException { this(warFile, name, new CaseInsensitiveMap(properties)); } public WarToWabConverterImpl(InputStreamProvider warFile, String name, CaseInsensitiveMap properties) throws IOException { this.properties = properties; classPath = new ArrayList<String>(); importPackages = new TreeSet<String>(); exemptPackages = new TreeSet<String>(); input = warFile; this.warName = name; } private void generateManifest() throws IOException { if (wabManifest != null) { // WAB manifest is already generated return; } JarInputStream jarInput = null; try { jarInput = new JarInputStream(input.getInputStream()); Manifest manifest = jarInput.getManifest(); if (isBundle(manifest)) { wabManifest = updateBundleManifest(manifest); } else { scanForDependencies(jarInput); // Add the new properties to the manifest byte stream wabManifest = updateManifest(manifest); } } finally { try { if (jarInput != null) jarInput.close(); } catch (IOException e) { e.printStackTrace(); } } } private void convert() throws IOException { if (wab != null) { // WAB is already converted return; } generateManifest(); CachedOutputStream output = new CachedOutputStream(); JarOutputStream jarOutput = null; JarInputStream jarInput = null; ZipEntry entry = null; // Copy across all entries from the original jar int val; try { jarOutput = new JarOutputStream(output, wabManifest); jarInput = new JarInputStream(input.getInputStream()); byte[] buffer = new byte[2048]; while ((entry = jarInput.getNextEntry()) != null) { // skip signature files if war is signed if (signed && isSignatureFile(entry.getName())) { continue; } jarOutput.putNextEntry(entry); while ((val = jarInput.read(buffer)) > 0) { jarOutput.write(buffer, 0, val); } } } finally { if (jarOutput != null) { jarOutput.close(); } if (jarInput != null) { jarInput.close(); } } wab = output; } private boolean isBundle(Manifest manifest) { if (manifest == null) { return false; } // Presence of _any_ of these headers indicates a bundle... Attributes attributes = manifest.getMainAttributes(); if (attributes.getValue(Constants.BUNDLE_SYMBOLICNAME) != null || attributes.getValue(Constants.BUNDLE_VERSION) != null || attributes.getValue(Constants.BUNDLE_MANIFESTVERSION) != null || attributes.getValue(Constants.IMPORT_PACKAGE) != null || attributes.getValue(WEB_CONTEXT_PATH) != null) { return true; } return false; } private void scanRecursive(final JarInputStream jarInput, boolean topLevel) throws IOException { ZipEntry entry; while ((entry = jarInput.getNextEntry()) != null) { if (entry.getName().endsWith(".class")) { PackageFinder pkgFinder = new PackageFinder(); new ClassReader(jarInput).accept(pkgFinder, ClassReader.SKIP_DEBUG); importPackages.addAll(pkgFinder.getImportPackages()); exemptPackages.addAll(pkgFinder.getExemptPackages()); } else if (entry.getName().endsWith(".jsp")) { Collection<String> thisJSPsImports = JSPImportParser.getImports(jarInput); importPackages.addAll(thisJSPsImports); } else if (entry.getName().endsWith(".jar")) { JarInputStream newJar = new JarInputStream(new InputStream() { @Override public int read() throws IOException { return jarInput.read(); } }); // discard return, we only care about the top level jars scanRecursive(newJar,false); // do not add jar embedded in already embedded jars if (topLevel) { manifests.put(entry.getName(), newJar.getManifest()); } } } } /** * * Read in the filenames inside the war (used for manifest update) Also * analyse the bytecode of any .class files in order to find any required * imports */ private void scanForDependencies(final JarInputStream jarInput) throws IOException { manifests = new HashMap<String, Manifest>(); scanRecursive(jarInput, true); // Process manifests from jars in order to work out classpath dependencies ClassPathBuilder classPathBuilder = new ClassPathBuilder(manifests); for (String fileName : manifests.keySet()) if (fileName.startsWith(CLASSPATH_LIB_PREFIX)) { classPath.add(fileName); classPath = classPathBuilder.updatePath(fileName, classPath); } // Remove packages that are part of the classes we searched through for (String s : exemptPackages) if (importPackages.contains(s)) importPackages.remove(s); } protected Manifest updateBundleManifest(Manifest manifest) throws IOException { String webCPath = properties.get(WEB_CONTEXT_PATH); if (webCPath == null) { webCPath = manifest.getMainAttributes().getValue(WEB_CONTEXT_PATH); } if (webCPath == null) { throw new IOException("Must specify " + WEB_CONTEXT_PATH + " parameter. The " + WEB_CONTEXT_PATH + " header is not defined in the source bundle."); } else { webCPath = addSlash(webCPath); manifest.getMainAttributes().put(new Attributes.Name(WEB_CONTEXT_PATH), webCPath); } // converter is not allowed to specify and override the following properties // when source is already a bundle checkParameter(Constants.BUNDLE_VERSION); checkParameter(Constants.BUNDLE_MANIFESTVERSION); checkParameter(Constants.BUNDLE_SYMBOLICNAME); checkParameter(Constants.IMPORT_PACKAGE); checkParameter(Constants.BUNDLE_CLASSPATH); return manifest; } private void checkParameter(String parameter) throws IOException { if (properties.containsKey(parameter)) { throw new IOException("Cannot override " + parameter + " header when converting a bundle"); } } protected Manifest updateManifest(Manifest manifest) throws IOException { // If for some reason no manifest was generated, we start our own so that we don't null pointer later on if (manifest == null) { manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1"); } else { // remove digest attributes if was is signed signed = removeDigestAttributes(manifest); } // Compare the manifest and the supplied properties // // Web-ContextPath // String webCPath = properties.get(WEB_CONTEXT_PATH); if (webCPath == null) { throw new IOException(WEB_CONTEXT_PATH + " parameter is missing."); } properties.put(WEB_CONTEXT_PATH, addSlash(webCPath)); // // Bundle-Version // if (manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION) == null && !properties.containsKey(Constants.BUNDLE_VERSION)) { properties.put(Constants.BUNDLE_VERSION, DEFAULT_BUNDLE_VERSION); } // // Bundle-ManifestVersion // String manifestVersion = properties.get(Constants.BUNDLE_MANIFESTVERSION); if (manifestVersion == null) { manifestVersion = manifest.getMainAttributes().getValue(Constants.BUNDLE_MANIFESTVERSION); if (manifestVersion == null) { manifestVersion = DEFAULT_BUNDLE_MANIFESTVERSION; } } else if (!manifestVersion.equals("2")) { throw new IOException("Unsupported bundle manifest version " + manifestVersion); } properties.put(Constants.BUNDLE_MANIFESTVERSION, manifestVersion); // // Bundle-ClassPath // ArrayList<String> classpath = new ArrayList<String>(); // Set initial entry into classpath classpath.add(INITIAL_CLASSPATH_ENTRY); // Add any files from the WEB-INF/lib directory + their dependencies classpath.addAll(classPath); // Get the list from the URL and add to classpath (removing duplicates) mergePathList(properties.get(Constants.BUNDLE_CLASSPATH), classpath, ","); // Get the existing list from the manifest file and add to classpath // (removing duplicates) mergePathList(manifest.getMainAttributes().getValue(Constants.BUNDLE_CLASSPATH), classpath, ","); // Construct the classpath string and set it into the properties StringBuffer classPathValue = new StringBuffer(); for (String entry : classpath) { classPathValue.append(","); classPathValue.append(entry); } if (!classpath.isEmpty()) { properties.put(Constants.BUNDLE_CLASSPATH, classPathValue.toString().substring(1)); } @SuppressWarnings("serial") ArrayList<String> packages = new ArrayList<String>() { @Override public boolean contains(Object elem) { // Check for exact match of export list if (super.contains(elem)) return true; if (!!!(elem instanceof String)) return false; String expPackageStmt = (String) elem; String expPackage = expPackageStmt.split("\\s*;\\s*")[0]; Pattern p = Pattern.compile("^\\s*"+Pattern.quote(expPackage)+"((;|\\s).*)?\\s*$"); for (String s : this) { Matcher m = p.matcher(s); if (m.matches()) { return true; } } return false; } }; // // Import-Package // packages.clear(); // Get the list from the URL and add to classpath (removing duplicates) mergePathList(properties.get(Constants.IMPORT_PACKAGE), packages, ","); // Get the existing list from the manifest file and add to classpath // (removing duplicates) mergePathList(manifest.getMainAttributes().getValue(Constants.IMPORT_PACKAGE), packages, ","); // Add the default set of packages mergePathList(DEFAULT_IMPORT_PACKAGE_LIST, packages, ","); // Analyse the bytecode of any .class files in the jar to find any other // required imports if (!!!importPackages.isEmpty()) { StringBuffer generatedImports = new StringBuffer(); for (String entry : importPackages) { generatedImports.append(','); generatedImports.append(entry); generatedImports.append(";resolution:=optional"); } mergePathList(generatedImports.substring(1), packages, ","); } // Construct the string and set it into the properties StringBuffer importValues = new StringBuffer(); for (String entry : packages) { importValues.append(","); importValues.append(entry); } if (!packages.isEmpty()) { properties.put(Constants.IMPORT_PACKAGE, importValues.toString().substring(1)); } // Take the properties map and add them to the manifest file for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); manifest.getMainAttributes().putValue(key, value); } // // Bundle-SymbolicName // if (manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME) == null) { manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, warName + "_" + manifest.hashCode()); } return manifest; } private static String addSlash(String contextPath) { if (!contextPath.startsWith("/")) { contextPath = "/" + contextPath; } return contextPath; } // pathlist = A "delim" delimitted list of path entries private static void mergePathList(String pathlist, ArrayList<String> paths, String delim) { if (pathlist != null) { List<String> tokens = parseDelimitedString(pathlist, delim, true); for (String token : tokens) { if (!paths.contains(token)) { paths.add(token); } } } } private static List<String> parseDelimitedString(String value, String delim, boolean includeQuotes) { if (value == null) { value = ""; } List<String> list = new ArrayList<String>(); int CHAR = 1; int DELIMITER = 2; int STARTQUOTE = 4; int ENDQUOTE = 8; StringBuffer sb = new StringBuffer(); int expecting = (CHAR | DELIMITER | STARTQUOTE); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); boolean isDelimiter = (delim.indexOf(c) >= 0); boolean isQuote = (c == '"'); if (isDelimiter && ((expecting & DELIMITER) > 0)) { list.add(sb.toString().trim()); sb.delete(0, sb.length()); expecting = (CHAR | DELIMITER | STARTQUOTE); } else if (isQuote && ((expecting & STARTQUOTE) > 0)) { if (includeQuotes) { sb.append(c); } expecting = CHAR | ENDQUOTE; } else if (isQuote && ((expecting & ENDQUOTE) > 0)) { if (includeQuotes) { sb.append(c); } expecting = (CHAR | STARTQUOTE | DELIMITER); } else if ((expecting & CHAR) > 0) { sb.append(c); } else { throw new IllegalArgumentException("Invalid delimited string: " + value); } } if (sb.length() > 0) { list.add(sb.toString().trim()); } return list; } private static boolean removeDigestAttributes(Manifest manifest) { boolean foundDigestAttribute = false; for (Map.Entry<String, Attributes> entry : manifest.getEntries().entrySet()) { Attributes attributes = entry.getValue(); for (Object attributeName : attributes.keySet()) { String name = ((Attributes.Name) attributeName).toString(); name = name.toLowerCase(); if (name.endsWith("-digest") || name.contains("-digest-")) { attributes.remove(attributeName); foundDigestAttribute = true; } } } return foundDigestAttribute; } private static boolean isSignatureFile(String entryName) { String[] parts = entryName.split("/"); if (parts.length == 2) { String name = parts[1].toLowerCase(); return (parts[0].equals("META-INF") && (name.endsWith(".sf") || name.endsWith(".dsa") || name.endsWith(".rsa") || name.startsWith("sig-"))); } else { return false; } } public InputStream getWAB() throws IOException { convert(); return wab.getInputStream(); } public Manifest getWABManifest() throws IOException { generateManifest(); return wabManifest; } public int getWabLength() throws IOException { convert(); return wab.size(); } }
7,945
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/url/WARConnection.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.url; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.apache.aries.web.converter.WarToWabConverter.InputStreamProvider; import org.apache.aries.web.converter.impl.CaseInsensitiveMap; import org.apache.aries.web.converter.impl.WarToWabConverterImpl; public class WARConnection extends URLConnection { private WarToWabConverterImpl converter = null; private CaseInsensitiveMap properties; protected WARConnection(URL url, CaseInsensitiveMap properties) throws MalformedURLException { super(url); this.properties = properties; } @Override public void connect() throws IOException { int fileNameIndex = url.getFile().lastIndexOf("/") + 1; String warName; if (fileNameIndex != 0) warName = url.getFile().substring(fileNameIndex); else warName = url.getFile(); converter = new WarToWabConverterImpl(new InputStreamProvider() { public InputStream getInputStream() throws IOException { return url.openStream(); } }, warName, properties); } @Override public InputStream getInputStream() throws IOException { if (converter == null) connect(); return converter.getWAB(); } @Override public int getContentLength() { try { if (converter == null) connect(); return converter.getWabLength(); } catch (IOException e) { return -1; } } }
7,946
0
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web
Create_ds/aries/web/web-urlhandler/src/main/java/org/apache/aries/web/url/WAR_URLServiceHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.web.url; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.Dictionary; import java.util.Hashtable; import java.util.StringTokenizer; import org.apache.aries.web.converter.impl.CaseInsensitiveMap; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.service.url.AbstractURLStreamHandlerService; import org.osgi.service.url.URLConstants; import org.osgi.service.url.URLStreamHandlerService; public class WAR_URLServiceHandler extends AbstractURLStreamHandlerService implements BundleActivator { private static final String urlScheme = "webbundle"; public WAR_URLServiceHandler() { super(); } public URLConnection openConnection(URL url) throws IOException { // Create properties object CaseInsensitiveMap properties = new CaseInsensitiveMap(); if (url.getQuery() != null) { String propString = url.getQuery(); StringTokenizer tok = new StringTokenizer(propString); boolean firstProperty = true; // We now parse the property pairs query string. // This has the format name=value&name=value...(etc) while (tok.hasMoreElements()) { String name = tok.nextToken("="); // "name" will now contain the name of the property we are trying to // set. Property pairs are seperated by the '&' symbol. The tokenizer // will include this symbol in the token so we need to return it from // all property names except the first. if (!!!firstProperty) name = name.substring(1); String value = tok.nextToken("&").substring(1); properties.put(name, value); firstProperty = false; } } return new WARConnection(new URL(url.getPath()), properties); } @Override public void parseURL(URL u, String spec, int start, int limit) { int propertyStart = spec.lastIndexOf('?') + 1; String propertyString = null; if (propertyStart > 0) { propertyString = spec.substring(propertyStart, spec.length()); propertyStart--; } else propertyStart = spec.length(); String warURL = spec.substring(start, propertyStart); // For our war url, we use the "path" field to specify the full url path to the WAR file, // and we use the "query" field to specify the properties for the WAB manifest setURL(u, urlScheme, null, 0, null, null, warURL, propertyString, null); } public void start(BundleContext context) throws Exception { Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put( URLConstants.URL_HANDLER_PROTOCOL, new String[] {urlScheme}); context.registerService(URLStreamHandlerService.class.getName(), this, properties); } public void stop(BundleContext arg0) throws Exception { // TODO Auto-generated method stub } }
7,947
0
Create_ds/aries/quiesce/quiesce-api/src/main/java/org/apache/aries/quiesce
Create_ds/aries/quiesce/quiesce-api/src/main/java/org/apache/aries/quiesce/participant/QuiesceParticipant.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.quiesce.participant; import java.util.List; import org.apache.aries.quiesce.manager.QuiesceCallback; import org.osgi.framework.Bundle; /** * Interface for OSGi containers / extenders to hook into the quiesce mechanism. An extender such * as Blueprint should implement a {@link QuiesceParticipant} and register it as a service in the service * registry. */ public interface QuiesceParticipant { /** * Request a number of bundles to be quiesced by this participant * * This method must be non-blocking. * @param callback The callback with which to alert the manager of successful quiesce completion (from the view of this * participant) * @param bundlesToQuiesce The bundles scheduled to be quiesced */ public void quiesce(QuiesceCallback callback, List<Bundle> bundlesToQuiesce); }
7,948
0
Create_ds/aries/quiesce/quiesce-api/src/main/java/org/apache/aries/quiesce
Create_ds/aries/quiesce/quiesce-api/src/main/java/org/apache/aries/quiesce/manager/QuiesceManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.quiesce.manager; import java.util.List; import java.util.concurrent.Future; import org.apache.aries.quiesce.participant.QuiesceParticipant; import org.osgi.framework.Bundle; /** * Interface for the quiesce manager. A quiesce manager provides the functionality to stop * bundles in such a manner that currently running work can be safely finished. To exploit this * above the quiesce manager individual containers / extenders (such as blueprint, jpa etc) need to * quiesce aware and register {@link QuiesceParticipant} appropriately. */ public interface QuiesceManager { /** * Request a collection of bundles to be quiesced * * @param timeout time to wait (in milliseconds) for all the quiesce participants to finish * before stopping the bundles. If some quiesce participants do not finish within the given timeout the bundles * are stopped regardless at the timeout * @param bundlesToQuiesce */ public void quiesce(long timeout, List<Bundle> bundlesToQuiesce); /** * Request a collection of bundles to be quiesced using the default timeout * * @param bundlesToQuiesce */ public void quiesce(List<Bundle> bundlesToQuiesce); /** * Request a collection of bundles to be quiesced like <code>quiesce(long, List&lt;Bundle&gt;)</code> * return a {@link Future} that the caller can block on instead of void * * @param bundlesToQuiesce * @return a {@link Future} that captures the execution of quiesce. The returned {@link Future} does * not support the cancel operation. */ public Future<?> quiesceWithFuture(List<Bundle> bundlesToQuiesce); /** * Request a collection of bundles to be quiesced like <code>quiesce(long, List&lt;Bundle&gt;)</code> * return a {@link Future} that the caller can block on instead of void * * @param timeout time to wait (in milliseconds) for all the quiesce participants to finish * before stopping the bundles. If some quiesce participants do not finish within the given timeout the bundles * are stopped regardless at the timeout * @param bundlesToQuiesce * @return a {@link Future} that captures the execution of quiesce. The returned {@link Future} does * not support the cancel operation. */ public Future<?> quiesceWithFuture(long timeout, List<Bundle> bundlesToQuiesce); }
7,949
0
Create_ds/aries/quiesce/quiesce-api/src/main/java/org/apache/aries/quiesce
Create_ds/aries/quiesce/quiesce-api/src/main/java/org/apache/aries/quiesce/manager/QuiesceCallback.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.quiesce.manager; import org.apache.aries.quiesce.participant.QuiesceParticipant; import org.osgi.framework.Bundle; /** * Callback that allows a {@link QuiesceParticipant} to alert the {@link QuiesceManager} that * bundles are quiesced (from the point of view of the participant) */ public interface QuiesceCallback { /** * Notify the quiesce manager that the given bundles are quiesced * (from the point of view of the calling participant) * @param bundlesQuiesced */ public void bundleQuiesced(Bundle ... bundlesQuiesced); }
7,950
0
Create_ds/aries/quiesce/quiesce-manager-itest/src/test/java/org/apache/aries/quiesce/manager
Create_ds/aries/quiesce/quiesce-manager-itest/src/test/java/org/apache/aries/quiesce/manager/itest/MockQuiesceParticipant.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.quiesce.manager.itest; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import org.apache.aries.quiesce.manager.QuiesceCallback; import org.apache.aries.quiesce.participant.QuiesceParticipant; import org.osgi.framework.Bundle; public class MockQuiesceParticipant implements QuiesceParticipant { public static final int RETURNIMMEDIATELY = 0; public static final int NEVERRETURN = 1; public static final int WAIT = 2; private int behaviour; private List<QuiesceCallback> callbacks = new ArrayList<QuiesceCallback>(); private ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "Test"); t.setDaemon(true); return t; } }); private int started = 0; private int finished = 0; public MockQuiesceParticipant( int i ) { behaviour = i; } public void quiesce(final QuiesceCallback callback, final List<Bundle> bundlesToQuiesce) { Runnable command = new Runnable() { public void run() { started += 1; callbacks.add(callback); switch (behaviour) { case 0: //return immediately System.out.println("MockParticipant: return immediately"); finished += 1; callback.bundleQuiesced(bundlesToQuiesce.toArray(new Bundle[bundlesToQuiesce.size()])); callbacks.remove(callback); break; case 1: //just don't do anything System.out.println("MockParticipant: just don't do anything"); break; case 2: //Wait for 1s then quiesce System.out.println("MockParticipant: Wait for 1s then quiesce"); try { Thread.sleep(1000); } catch (InterruptedException e) { } finished += 1; callback.bundleQuiesced(bundlesToQuiesce.toArray(new Bundle[bundlesToQuiesce.size()])); callbacks.remove(callback); break; default: //Unknown behaviour, don't do anything } } }; executor.execute(command); } public int getStartedCount() { return started; } public int getFinishedCount() { return finished; } public synchronized void reset() { started = 0; finished = 0; } }
7,951
0
Create_ds/aries/quiesce/quiesce-manager-itest/src/test/java/org/apache/aries/quiesce/manager
Create_ds/aries/quiesce/quiesce-manager-itest/src/test/java/org/apache/aries/quiesce/manager/itest/QuiesceManagerTest.java
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.quiesce.manager.itest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.aries.itest.AbstractIntegrationTest; import org.apache.aries.quiesce.manager.QuiesceManager; import org.apache.aries.quiesce.participant.QuiesceParticipant; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.exam.spi.reactors.PerMethod; import org.osgi.framework.Bundle; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; @RunWith(PaxExam.class) @ExamReactorStrategy(PerMethod.class) public class QuiesceManagerTest extends AbstractIntegrationTest { private QuiesceManager manager; private Bundle b1; private Bundle b2; private Bundle b3; private long timeoutTime; private List<Bundle> bundleList; private MockQuiesceParticipant participant1; private MockQuiesceParticipant participant2; private MockQuiesceParticipant participant3; @Before public void setup() { manager = context().getService(QuiesceManager.class); b1 = bundleContext.getBundle(5); b2 = bundleContext.getBundle(6); b3 = bundleContext.getBundle(10); participant1 = new MockQuiesceParticipant(MockQuiesceParticipant.RETURNIMMEDIATELY); participant2 = new MockQuiesceParticipant(MockQuiesceParticipant.NEVERRETURN); participant3 = new MockQuiesceParticipant(MockQuiesceParticipant.WAIT); } @After public void after() { participant1.reset(); participant2.reset(); participant3.reset(); } @Test public void testNullSafe() throws Exception { //Check we're null safe manager.quiesce(null); } @Test public void testNoParticipants() throws Exception { bundleList = new ArrayList<Bundle>(); bundleList.add(b1); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); //Try quiescing one bundle with no participants manager.quiesceWithFuture(2000, bundleList).get(5000, TimeUnit.MILLISECONDS); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); } @Test public void testImmediateReturn() throws Exception { bundleList = new ArrayList<Bundle>(); bundleList.add(b1); //Register a mock participant which will report back quiesced immediately bundleContext.registerService(QuiesceParticipant.class.getName(), participant1, null); //Try quiescing the bundle with immediate return assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); manager.quiesceWithFuture(1000,bundleList).get(5000, TimeUnit.MILLISECONDS); assertEquals("Participant should have finished once", 1, participant1.getFinishedCount()); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); } @Test public void testNoReturn() throws Exception { //Register a mock participant which won't respond bundleContext.registerService(QuiesceParticipant.class.getName(), participant2, null); //recreate the list as it may have been emptied? bundleList = new ArrayList<Bundle>(); bundleList.add(b1); //Try quiescing the bundle with no return assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); manager.quiesce(1000,bundleList); timeoutTime = System.currentTimeMillis()+5000; while (System.currentTimeMillis() < timeoutTime && b1.getState() == Bundle.ACTIVE){ Thread.sleep(500); } assertEquals("Participant should have started once", 1, participant2.getStartedCount()); assertEquals("Participant should not have finished", 0, participant2.getFinishedCount()); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); } @Test public void testWaitAShortTime() throws Exception { //Try quiescing where participant takes 5s to do the work. We should get InterruptedException bundleContext.registerService(QuiesceParticipant.class.getName(), participant3, null); //recreate the list as it may have been emptied? bundleList = new ArrayList<Bundle>(); bundleList.add(b1); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); // we should be finishing in about 5000 millis not 10000 manager.quiesceWithFuture(10000,bundleList).get(7000, TimeUnit.MILLISECONDS); assertEquals("Participant should have started once", 1, participant3.getStartedCount()); assertEquals("Participant should finished once", 1, participant3.getFinishedCount()); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); } @Test public void testThreeParticipants() throws Exception { //Register three participants. One returns immediately, one waits 5s then returns, one never returns bundleContext.registerService(QuiesceParticipant.class.getName(), participant1, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant2, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant3, null); //recreate the list as it may have been emptied bundleList = new ArrayList<Bundle>(); bundleList.add(b1); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); manager.quiesceWithFuture(10000,bundleList).get(15000, TimeUnit.MILLISECONDS); assertEquals("Participant 1 should have started once", 1, participant1.getStartedCount()); assertEquals("Participant 1 should finished once", 1, participant1.getFinishedCount()); assertEquals("Participant 2 should have started once", 1, participant2.getStartedCount()); assertEquals("Participant 2 should not have finished", 0, participant2.getFinishedCount()); assertEquals("Participant 3 should have started once", 1, participant3.getStartedCount()); assertEquals("Participant 3 should finished once", 1, participant3.getFinishedCount()); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); } @Test public void testFuture() throws Exception { bundleContext.registerService(QuiesceParticipant.class.getName(), participant2, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant3, null); bundleList = new ArrayList<Bundle>(); bundleList.add(b1); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); Future<?> future = manager.quiesceWithFuture(2000, Arrays.asList(b1)); // causes us to wait future.get(); assertEquals("Participant 2 has started", 1, participant2.getStartedCount()); assertEquals("Participant 2 has finished", 0, participant2.getFinishedCount()); assertEquals("Participant 3 has started", 1, participant3.getStartedCount()); assertEquals("Participant 3 has finished", 1, participant3.getFinishedCount()); } @Test public void testFutureWithWait() throws Exception { bundleContext.registerService(QuiesceParticipant.class.getName(), participant2, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant3, null); bundleList = new ArrayList<Bundle>(); bundleList.add(b1); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); Future<?> future = manager.quiesceWithFuture(2000, Arrays.asList(b1)); try { // causes us to wait, but too short future.get(500, TimeUnit.MILLISECONDS); fail("Too short wait, should have thrown TimeoutException"); } catch (TimeoutException te) { // expected } assertEquals("Participant 2 has started", 1, participant2.getStartedCount()); assertEquals("Participant 2 has finished", 0, participant2.getFinishedCount()); assertEquals("Participant 3 has started", 1, participant3.getStartedCount()); assertEquals("Participant 3 has finished", 0, participant3.getFinishedCount()); assertEquals("Bundle "+b1.getSymbolicName()+" should still be active, because we did not wait long enough", Bundle.ACTIVE, b1.getState()); } @Test public void testTwoBundles() throws Exception { //Register three participants. One returns immediately, one waits 5s then returns, one never returns bundleContext.registerService(QuiesceParticipant.class.getName(), participant1, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant2, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant3, null); //recreate the list as it may have been emptied bundleList = new ArrayList<Bundle>(); bundleList.add(b1); bundleList.add(b2); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); assertEquals("Bundle "+b2.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b2.getState()); manager.quiesceWithFuture(10000,bundleList).get(15000, TimeUnit.MILLISECONDS); assertEquals("Participant 1 should have started once", 1, participant1.getStartedCount()); assertEquals("Participant 1 should finished once", 1, participant1.getFinishedCount()); assertEquals("Participant 2 should have started once", 1, participant2.getStartedCount()); assertEquals("Participant 2 should not have finished", 0, participant2.getFinishedCount()); assertEquals("Participant 3 should have started once", 1, participant3.getStartedCount()); assertEquals("Participant 3 should finished once", 1, participant3.getFinishedCount()); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); assertTrue("Bundle "+b2.getSymbolicName()+" should not be in active state", b2.getState() != Bundle.ACTIVE); } @Test public void testOverlappedQuiesces() throws Exception { //Register three participants. One returns immediately, one waits 5s then returns, one never returns bundleContext.registerService(QuiesceParticipant.class.getName(), participant1, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant2, null); bundleContext.registerService(QuiesceParticipant.class.getName(), participant3, null); //recreate the list as it may have been emptied bundleList = new ArrayList<Bundle>(); bundleList.add(b1); bundleList.add(b2); assertEquals("Bundle "+b1.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b1.getState()); assertEquals("Bundle "+b2.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b2.getState()); assertEquals("Bundle "+b3.getSymbolicName()+" should be in active state", Bundle.ACTIVE, b3.getState()); manager.quiesce(2000,bundleList); bundleList = new ArrayList<Bundle>(); bundleList.add(b2); bundleList.add(b3); manager.quiesce(2000,bundleList); timeoutTime = System.currentTimeMillis()+10000; while (System.currentTimeMillis() < timeoutTime && (b1.getState() == Bundle.ACTIVE || b2.getState() == Bundle.ACTIVE || b3.getState() == Bundle.ACTIVE)) { Thread.sleep(500); } assertEquals("Participant 1 should have started twice as it has been asked to quiesce twice", 2, participant1.getStartedCount()); assertEquals("Participant 1 should finished twice as it should have returned from two quiesce requests immediately", 2, participant1.getFinishedCount()); assertEquals("Participant 2 should have started twice as it has been asked to quiesce twice", 2, participant2.getStartedCount()); assertEquals("Participant 2 should not have finished as it should never return from it's two quiesce requests", 0, participant2.getFinishedCount()); assertEquals("Participant 3 should have started twice as it has been asked to quiesce twice", 2, participant3.getStartedCount()); assertEquals("Participant 3 should finished twice as it should have waited a short time before returning from it's two quiesce requests", 2, participant3.getFinishedCount()); assertTrue("Bundle "+b1.getSymbolicName()+" should not be in active state", b1.getState() != Bundle.ACTIVE); assertTrue("Bundle "+b2.getSymbolicName()+" should not be in active state", b2.getState() != Bundle.ACTIVE); assertTrue("Bundle "+b3.getSymbolicName()+" should not be in active state", b3.getState() != Bundle.ACTIVE); } public Option baseOptions() { String localRepo = getLocalRepo(); return composite( junitBundles(), // this is how you set the default log level when using pax // logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)) ); } @Configuration public Option[] configuration() { return new Option[]{ baseOptions(), // Bundles mavenBundle("org.osgi", "org.osgi.compendium").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("commons-lang", "commons-lang").versionAsInProject(), mavenBundle("commons-collections", "commons-collections").versionAsInProject(), mavenBundle("commons-pool", "commons-pool").versionAsInProject(), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.serp").versionAsInProject(), mavenBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.api").versionAsInProject(), mavenBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.manager").versionAsInProject(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), //new VMOption( "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000" ), //new TimeoutOption( 0 ), }; } }
7,952
0
Create_ds/aries/quiesce/quiesce-manager/src/main/java/org/apache/aries/quiesce/manager
Create_ds/aries/quiesce/quiesce-manager/src/main/java/org/apache/aries/quiesce/manager/impl/QuiesceManagerImpl.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.quiesce.manager.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.aries.quiesce.manager.QuiesceCallback; import org.apache.aries.quiesce.manager.QuiesceManager; import org.apache.aries.quiesce.participant.QuiesceParticipant; import org.apache.aries.util.nls.MessageUtil; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class QuiesceManagerImpl implements QuiesceManager { /** Logger */ private static final Logger LOGGER = LoggerFactory.getLogger(QuiesceManagerImpl.class.getName()); /** MessageUtil */ private static final MessageUtil MESSAGES = MessageUtil.createMessageUtil(QuiesceManagerImpl.class, "org.apache.aries.quiesce.manager.nls.quiesceMessages"); /** The default timeout to use */ private static int defaultTimeout = 60000; /** The container's {@link BundleContext} */ private BundleContext bundleContext = null; /** The thread pool to execute timeout commands */ private ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(10, new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r, "Quiesce Manager Timeout Thread"); t.setDaemon(true); return t; } }); /** The thread pool to execute quiesce commands */ private ExecutorService executor = new ThreadPoolExecutor(0, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),new ThreadFactory() { public Thread newThread(Runnable arg0) { Thread t = new Thread(arg0, "Quiesce Manager Thread"); t.setDaemon(true); return t; } }); /** The map of bundles that are currently being quiesced */ private static ConcurrentHashMap<Bundle, Bundle> bundleMap = new ConcurrentHashMap<Bundle, Bundle>(); public QuiesceManagerImpl(BundleContext bc) { bundleContext = bc; } /** * Attempts to quiesce all bundles in the list. After the timeout has elapsed, * or if successfully quiesced before that, the bundles are stopped. This method * is non-blocking. Calling objects wishing to track the state of the bundles * need to listen for the resulting stop events. */ public void quiesce(long timeout, List<Bundle> bundles) { quiesceWithFuture(timeout, bundles); } public Future<?> quiesceWithFuture(List<Bundle> bundlesToQuiesce) { return quiesceWithFuture(defaultTimeout, bundlesToQuiesce); } public Future<?> quiesceWithFuture(long timeout, List<Bundle> bundles) { QuiesceFuture result = new QuiesceFuture(); if (bundles != null && !!!bundles.isEmpty()) { //check that bundle b is not already quiescing Iterator<Bundle> it = bundles.iterator(); Set<Bundle> bundlesToQuiesce = new HashSet<Bundle>(); while(it.hasNext()) { Bundle b = it.next(); Bundle priorBundle = bundleMap.putIfAbsent(b, b); if (priorBundle == null) { bundlesToQuiesce.add(b); }else{ LOGGER.warn(MESSAGES.getMessage("already.quiescing.bundle", b.getSymbolicName() + '/' + b.getVersion())); } } Runnable command = new BundleQuiescer(bundlesToQuiesce, timeout, result, bundleMap); executor.execute(command); return result; } else { result.registerDone(); } return result; } private static class QuiesceFuture implements Future<Object> { private CountDownLatch latch = new CountDownLatch(1); public boolean cancel(boolean mayInterruptIfRunning) { throw new UnsupportedOperationException(MESSAGES.getMessage("quiesce.cannot.be.canceled")); } public Object get() throws InterruptedException, ExecutionException { latch.await(); return null; } public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (!!!latch.await(timeout, unit)) throw new TimeoutException(); return null; } public boolean isCancelled() { return false; } public boolean isDone() { return latch.getCount() == 0; } public void registerDone() { if (!!!isDone()) { latch.countDown(); } } } /** * Attempts to quiesce all bundles in the list, using the default timeout. * After the timeout has elapsed, or if successfully quiesced before that, * the bundles are stopped. This method is non-blocking. Calling objects * wishing to track the state of the bundles need to listen for the * resulting stop events. */ public void quiesce(List<Bundle> bundlesToQuiesce) { quiesce(defaultTimeout, bundlesToQuiesce); } /** * Stop a bundle that was to be quiesced. This happens either when all the participants * are finished or when the timeout has occurred. * * The set of all bundles to quiesce is used to track stops, so that they do not occur twice. * @param bundleToStop * @param bundlesToStop * @return */ private static boolean stopBundle(Bundle bundleToStop, Set<Bundle> bundlesToStop) { try { synchronized (bundlesToStop) { if (bundlesToStop.remove(bundleToStop)) { bundleToStop.stop(); bundleMap.remove(bundleToStop); } } } catch (BundleException be) { return false; } return true; } private static boolean stillQuiescing(Bundle bundleToStop) { return bundleMap.containsKey(bundleToStop); } /** * BundleQuiescer is used for each bundle to quiesce. It creates a callback object for each * participant. Well-behaved participants will be non-blocking on their quiesce method. * When all callbacks for the participants have completed, this thread will get an * interrupt, so it sleeps until it hits the timeout. When complete it stops the bundle * and removes the bundles from the list of those that are being quiesced. */ private class BundleQuiescer implements Runnable { private final Set<Bundle> bundlesToQuiesce; private final long timeout; private final QuiesceFuture future; public BundleQuiescer(Set<Bundle> bundlesToQuiesce, long timeout, QuiesceFuture future, ConcurrentHashMap<Bundle, Bundle> bundleMap) { this.bundlesToQuiesce = new HashSet<Bundle>(bundlesToQuiesce); this.timeout = timeout; this.future = future; } public void run() { try { if (bundleContext != null) { ServiceReference[] serviceRefs = bundleContext.getServiceReferences(QuiesceParticipant.class.getName(), null); if (serviceRefs != null) { List<QuiesceParticipant> participants = new ArrayList<QuiesceParticipant>(); final List<QuiesceCallbackImpl> callbacks = new ArrayList<QuiesceCallbackImpl>(); List<Bundle> copyOfBundles = new ArrayList<Bundle>(bundlesToQuiesce); ScheduledFuture<?> timeoutFuture = timeoutExecutor.schedule(new Runnable() { public void run() { try { synchronized (bundlesToQuiesce) { for (Bundle b : new ArrayList<Bundle>(bundlesToQuiesce)) { LOGGER.warn(MESSAGES.getMessage("quiesce.failed", b.getSymbolicName() + '/' + b.getVersion())); stopBundle(b, bundlesToQuiesce); } } } finally { future.registerDone(); LOGGER.debug("Quiesce complete"); } } }, timeout, TimeUnit.MILLISECONDS); //Create callback objects for all participants for( ServiceReference sr : serviceRefs ) { QuiesceParticipant participant = (QuiesceParticipant) bundleContext.getService(sr); participants.add(participant); callbacks.add(new QuiesceCallbackImpl(bundlesToQuiesce, callbacks, future, timeoutFuture)); } //Quiesce each participant and wait for an interrupt from a callback //object when all are quiesced, or the timeout to be reached for( int i=0; i<participants.size(); i++ ) { QuiesceParticipant participant = participants.get(i); QuiesceCallbackImpl callback = callbacks.get(i); participant.quiesce(callback, copyOfBundles); } }else{ for (Bundle b : bundlesToQuiesce) { stopBundle(b, bundlesToQuiesce); } future.registerDone(); } } } catch (InvalidSyntaxException e) { LOGGER.warn(MESSAGES.getMessage("null.is.invalid.filter")); for (Bundle b : bundlesToQuiesce) { stopBundle(b, bundlesToQuiesce); } future.registerDone(); } } } /** * Callback object provided for each participant for each quiesce call * from the quiesce manager. */ private static class QuiesceCallbackImpl implements QuiesceCallback { //Must be a copy private final Set<Bundle> toQuiesce; // Must not be a copy private final Set<Bundle> toQuiesceShared; //Must not be a copy private final List<QuiesceCallbackImpl> allCallbacks; //Timer so we can cancel the alarm if all done private final QuiesceFuture future; //The cleanup action that runs at timeout private final ScheduledFuture<?> timeoutFuture; public QuiesceCallbackImpl(Set<Bundle> toQuiesce, List<QuiesceCallbackImpl> allCallbacks, QuiesceFuture future, ScheduledFuture<?> timeoutFuture) { this.toQuiesce = new HashSet<Bundle>(toQuiesce); this.toQuiesceShared = toQuiesce; this.allCallbacks = allCallbacks; this.future = future; this.timeoutFuture = timeoutFuture; } /** * Removes the bundles from the list of those to quiesce. * If the list is now empty, this callback object is finished (i.e. * the participant linked to this object has quiesced all the bundles * requested). * * If all other participants have also completed, then the * calling BundleQuieser thread is interrupted. */ public void bundleQuiesced(Bundle... bundlesQuiesced) { boolean timeoutOccurred = false; synchronized (allCallbacks) { for(Bundle b : bundlesQuiesced) { if(QuiesceManagerImpl.stillQuiescing(b)) { if(toQuiesce.remove(b)) { if(checkOthers(b)){ QuiesceManagerImpl.stopBundle(b, toQuiesceShared); if(allCallbacksComplete()){ future.registerDone(); timeoutFuture.cancel(false); LOGGER.debug("Quiesce complete"); } } } } else { timeoutOccurred = true; break; } } if (timeoutOccurred) { Iterator<QuiesceCallbackImpl> it = allCallbacks.iterator(); while (it.hasNext()) { it.next().toQuiesce.clear(); } } } } private boolean checkOthers(Bundle b) { boolean allDone = true; Iterator<QuiesceCallbackImpl> it = allCallbacks.iterator(); while (allDone && it.hasNext()) { allDone = !!!it.next().toQuiesce.contains(b); } return allDone; } private boolean allCallbacksComplete() { boolean allDone = true; Iterator<QuiesceCallbackImpl> it = allCallbacks.iterator(); while (allDone && it.hasNext()) { QuiesceCallbackImpl next = it.next(); if (!!!next.toQuiesce.isEmpty()) allDone = false; } return allDone; } } }
7,953
0
Create_ds/aries/quiesce/quiesce-manager/src/main/java/org/apache/aries/quiesce/manager
Create_ds/aries/quiesce/quiesce-manager/src/main/java/org/apache/aries/quiesce/manager/impl/Activator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.quiesce.manager.impl; import org.apache.aries.quiesce.manager.QuiesceManager; import org.apache.aries.util.AriesFrameworkUtil; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { private ServiceRegistration serviceReg; public void start(BundleContext bundleContext) throws Exception { QuiesceManager manager = new QuiesceManagerImpl(bundleContext); serviceReg = bundleContext.registerService(QuiesceManager.class.getName(), manager, null); } public void stop(BundleContext bundleContext) throws Exception { AriesFrameworkUtil.safeUnregisterService(serviceReg); } }
7,954
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/EsaMojoTest.java
package org.apache.aries.plugin.esa; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.codehaus.plexus.archiver.zip.ZipEntry; import org.codehaus.plexus.archiver.zip.ZipFile; import aQute.lib.osgi.Analyzer; /** * @author <a href="mailto:aramirez@apache.org">Allan Ramirez</a> */ public class EsaMojoTest extends AbstractMojoTestCase { public void testEsaTestEnvironment() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-test/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); } public void testBasicEsa() throws Exception { testBasicEsa( "target/test-classes/unit/basic-esa-test/plugin-config.xml", null ); } public void testBasicEsaPgkType() throws Exception { testBasicEsa( "target/test-classes/unit/basic-esa-test-with-pgk-type/plugin-config.xml", "maven-esa-test-1.0-SNAPSHOT.jar" ); } private void testBasicEsa(String path, String extraExpectedFiles) throws Exception { File testPom = new File( getBasedir(), path ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); if (extraExpectedFiles != null) { expectedFiles.add( extraExpectedFiles ); } ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } public void testBasicEsaWithDescriptor() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-with-descriptor/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } public void testBasicEsaWithManifest() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-with-manifest/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "META-INF/MANIFEST.MF" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } private Manifest getSubsystemManifest(ZipFile esa) throws Exception { ZipEntry entry = esa.getEntry("OSGI-INF/SUBSYSTEM.MF"); InputStream in = esa.getInputStream(entry); Manifest mf = new Manifest(in); return mf; } private Map<String, Map<String, String>> getHeader(Manifest mf, String header) { Attributes attributes = mf.getMainAttributes(); String value = attributes.getValue(header); assertNotNull("Header " + header + " not found", value); return Analyzer.parseHeader(value, null); } private void testForHeader(ZipFile esa, String header, String exactEntry) throws Exception { Enumeration entries = esa.getEntries(); // Test Use-Bundle & Subsytem-Type inclusion ZipEntry entry = esa.getEntry("OSGI-INF/SUBSYSTEM.MF"); BufferedReader br = new BufferedReader(new InputStreamReader(esa.getInputStream(entry))); Boolean foundHeader=false; String line; while ((line = br.readLine()) != null) { if (line.contains(header)) { assertEquals(exactEntry, line); foundHeader = true; } } assertTrue("Found " + header + ":", foundHeader); } public void testSubsystemManifestGeneration() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-without-manifest/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); // Test for the Use-Bundle header testForHeader(esa, "Use-Bundle", "Use-Bundle: org.apache.aries.test.Bundle;version=1.0.0-SNAPSHOT"); // Test for the Subsystem-Type header testForHeader(esa, "Subsystem-Type", "Subsystem-Type: feature"); } public void testSubsystemStartOrder() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-start-order/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); Manifest mf = getSubsystemManifest(esa); Map<String, Map<String, String>> header = getHeader(mf, "Subsystem-Content"); Map<String, String> attributes = null; attributes = header.get("maven-artifact01-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); // start-order is actually a directive, shows up here as the name+":" assertEquals("1", attributes.get("start-order:")); assertNull(attributes.get("type")); attributes = header.get("maven-artifact02-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); assertEquals("2", attributes.get("start-order:")); assertNull(attributes.get("type")); } public void testArchiveContentConfigurationNoBundles() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-no-bundles/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } public void testBasicEsaWithoutNonBundleJars() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-exclude-non-bundle-jars/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } public void testArchiveContentConfigurationSubsystemContentBundles() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-content-bundles-only/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } public void testArchiveContentConfigurationSubsystemContentAll() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-content-all-transitive/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.properties" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/pom.xml" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/maven-esa-test/" ); expectedFiles.add( "META-INF/maven/org.apache.maven.test/" ); expectedFiles.add( "META-INF/maven/" ); expectedFiles.add( "META-INF/" ); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact03-1.1-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); } public void testManifestSubsystemContentContainsOnlyDirectContent() throws Exception { File testPom = new File(getBasedir(), "target/test-classes/unit/basic-esa-content-type-bundles-only/plugin-config.xml"); EsaMojo mojo = (EsaMojo) lookupMojo("esa", testPom); assertNotNull(mojo); String finalName = (String) getVariableValueFromObject(mojo, "finalName"); String workDir = (String) getVariableValueFromObject(mojo, "workDirectory"); String outputDir = (String) getVariableValueFromObject(mojo, "outputDirectory"); mojo.execute(); // check the generated esa file File esaFile = new File(outputDir, finalName + ".esa"); assertTrue(esaFile.exists()); ZipFile esa = new ZipFile(esaFile); Manifest mf = getSubsystemManifest(esa); Map<String, Map<String, String>> header = getHeader(mf, "Subsystem-Content"); Map<String, String> attributes = null; attributes = header.get("maven-artifact01-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); assertNull(attributes.get("type")); attributes = header.get("maven-artifact02-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); assertNull(attributes.get("type")); assertEquals(2, header.size()); } public void testManifestSubsystemContentContainsAllTransitiveDependencies() throws Exception { File testPom = new File(getBasedir(), "target/test-classes/unit/basic-esa-content-type-all-transitive/plugin-config.xml"); EsaMojo mojo = (EsaMojo) lookupMojo("esa", testPom); assertNotNull(mojo); String finalName = (String) getVariableValueFromObject(mojo, "finalName"); String workDir = (String) getVariableValueFromObject(mojo, "workDirectory"); String outputDir = (String) getVariableValueFromObject(mojo, "outputDirectory"); mojo.execute(); // check the generated esa file File esaFile = new File(outputDir, finalName + ".esa"); assertTrue(esaFile.exists()); ZipFile esa = new ZipFile(esaFile); Manifest mf = getSubsystemManifest(esa); Map<String, Map<String, String>> header = getHeader(mf, "Subsystem-Content"); System.out.println(header); Map<String, String> attributes = null; attributes = header.get("maven-artifact01-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); assertNull(attributes.get("type")); attributes = header.get("maven-artifact02-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); assertNull(attributes.get("type")); attributes = header.get("maven-artifact03"); assertNotNull(attributes); assertEquals("[1.1.0.SNAPSHOT.NNN,1.1.0.SNAPSHOT.NNN]", attributes.get("version")); assertEquals("osgi.fragment", attributes.get("type")); assertEquals(3, header.size()); } public void testCustomInstructions() throws Exception { File testPom = new File( getBasedir(), "target/test-classes/unit/basic-esa-custom-instructions/plugin-config.xml" ); EsaMojo mojo = ( EsaMojo ) lookupMojo( "esa", testPom ); assertNotNull( mojo ); String finalName = ( String ) getVariableValueFromObject( mojo, "finalName" ); String workDir = ( String ) getVariableValueFromObject( mojo, "workDirectory" ); String outputDir = ( String ) getVariableValueFromObject( mojo, "outputDirectory" ); mojo.execute(); //check the generated esa file File esaFile = new File( outputDir, finalName + ".esa" ); assertTrue( esaFile.exists() ); //expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add( "OSGI-INF/SUBSYSTEM.MF" ); expectedFiles.add( "OSGI-INF/" ); expectedFiles.add( "maven-artifact01-1.0-SNAPSHOT.jar" ); expectedFiles.add( "maven-artifact02-1.0-SNAPSHOT.jar" ); ZipFile esa = new ZipFile( esaFile ); Enumeration entries = esa.getEntries(); assertTrue( entries.hasMoreElements() ); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); // Test for the Foo header testForHeader(esa, "Foo", "Foo: bar"); // Test for the MyHeader header testForHeader(esa, "MyHeader", "MyHeader: myValue"); // Test for the Subsystem-Name header testForHeader(esa, "Subsystem-Name", "Subsystem-Name: myName"); } public void testSubsystemContentType() throws Exception { File testPom = new File(getBasedir(), "target/test-classes/unit/basic-esa-content-type/plugin-config.xml"); EsaMojo mojo = (EsaMojo) lookupMojo("esa", testPom); assertNotNull(mojo); String finalName = (String) getVariableValueFromObject(mojo, "finalName"); String workDir = (String) getVariableValueFromObject(mojo, "workDirectory"); String outputDir = (String) getVariableValueFromObject(mojo, "outputDirectory"); mojo.execute(); // check the generated esa file File esaFile = new File(outputDir, finalName + ".esa"); assertTrue(esaFile.exists()); // expected files/directories inside the esa file List expectedFiles = new ArrayList(); expectedFiles.add("OSGI-INF/SUBSYSTEM.MF"); expectedFiles.add("OSGI-INF/"); expectedFiles.add("maven-artifact01-1.0-SNAPSHOT.jar"); expectedFiles.add("maven-artifact02-1.0-SNAPSHOT.jar"); expectedFiles.add("maven-artifact03-1.1-SNAPSHOT.jar"); ZipFile esa = new ZipFile(esaFile); Enumeration entries = esa.getEntries(); assertTrue(entries.hasMoreElements()); int missing = getSizeOfExpectedFiles(entries, expectedFiles); assertEquals("Missing files: " + expectedFiles, 0, missing); Manifest mf = getSubsystemManifest(esa); Map<String, Map<String, String>> header = getHeader(mf, "Subsystem-Content"); Map<String, String> attributes = null; attributes = header.get("maven-artifact01-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]", attributes.get("version")); assertNull(attributes.get("type")); attributes = header.get("maven-artifact02-1.0-SNAPSHOT"); assertNotNull(attributes); assertEquals("[1.3,2.5)", attributes.get("version")); assertNull(attributes.get("type")); attributes = header.get("maven-artifact03"); assertNotNull(attributes); assertEquals("[1.1.0.SNAPSHOT.NNN,1.1.0.SNAPSHOT.NNN]", attributes.get("version")); assertEquals("osgi.fragment", attributes.get("type")); attributes = header.get("maven-artifact04"); assertNotNull(attributes); assertEquals("[1.2.0.SNAPSHOT,1.2.0.SNAPSHOT]", attributes.get("version")); assertEquals("feature", attributes.get("type")); } private int getSizeOfExpectedFiles( Enumeration entries, List expectedFiles ) { while( entries.hasMoreElements() ) { ZipEntry entry = ( ZipEntry ) entries.nextElement(); if( expectedFiles.contains( entry.getName() ) ) { expectedFiles.remove( entry.getName() ); assertFalse( expectedFiles.contains( entry.getName() ) ); } else { fail( entry.getName() + " is not included in the expected files" ); } } return expectedFiles.size(); } }
7,955
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub9.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.util.HashSet; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; public class EsaMavenProjectStub9 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-content-type/plugin-config.xml" ); } public Set getArtifacts() { try { Set artifacts = new HashSet(); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact01", "1.0-SNAPSHOT", false ) ); Artifact artifact02 = createArtifact( "org.apache.maven.test", "maven-artifact02", "1.0-SNAPSHOT", false ); artifact02.setVersionRange(VersionRange.createFromVersionSpec("[1.3, 2.5)")); artifacts.add( artifact02 ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact03", "1.1-SNAPSHOT", false ) ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact04", "1.2-SNAPSHOT", "esa", true ) ); return artifacts; } catch (InvalidVersionSpecificationException e) { throw new RuntimeException(e); } } }
7,956
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub5.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class EsaMavenProjectStub5 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-no-bundles/plugin-config.xml" ); } }
7,957
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub4.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class EsaMavenProjectStub4 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-without-manifest/plugin-config.xml" ); } }
7,958
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub8.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class EsaMavenProjectStub8 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-custom-instructions/plugin-config.xml" ); } }
7,959
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub3.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class EsaMavenProjectStub3 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-with-manifest/plugin-config.xml" ); } }
7,960
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Model; import org.apache.maven.model.Organization; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.PlexusTestCase; /** * @author <a href="mailto:aramirez@apache.org">Allan Ramirez</a> */ public class EsaMavenProjectStub extends MavenProject { private List attachedArtifacts; public EsaMavenProjectStub() { super( new Model() ); super.setGroupId( getGroupId() ); super.setArtifactId( getArtifactId() ); super.setVersion( getVersion() ); super.setDescription( "Test description" ); Organization org = new Organization(); org.setName( "organization" ); org.setUrl( "http://www.some.org" ); super.setOrganization( org ); super.setFile( getFile() ); super.setPluginArtifacts( Collections.EMPTY_SET ); super.setReportArtifacts( Collections.EMPTY_SET ); super.setExtensionArtifacts( Collections.EMPTY_SET ); super.setArtifact( getArtifact() ); super.setRemoteArtifactRepositories( Collections.EMPTY_LIST ); super.setPluginArtifactRepositories( Collections.EMPTY_LIST ); super.setCollectedProjects( Collections.EMPTY_LIST ); super.setActiveProfiles( Collections.EMPTY_LIST ); super.addCompileSourceRoot( getBasedir() + "/src/test/resources/unit/basic-esa-test/src/main/java" ); super.addTestCompileSourceRoot( getBasedir() + "/src/test/resources/unit/basic-esa-test/src/test/java" ); super.setExecutionRoot( false ); } public String getGroupId() { return "org.apache.maven.test"; } public String getArtifactId() { return "maven-esa-test"; } public String getVersion() { return "1.0-SNAPSHOT"; } public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-test/plugin-config.xml" ); } public File getBasedir() { return new File( PlexusTestCase.getBasedir() ); } public Artifact getArtifact() { Artifact artifact = new EsaArtifactStub(); artifact.setGroupId( getGroupId() ); artifact.setArtifactId( getArtifactId() ); artifact.setVersion( getVersion() ); return artifact; } public Set getArtifacts() { Set artifacts = new LinkedHashSet(); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact01", "1.0-SNAPSHOT", false ) ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact02", "1.0-SNAPSHOT", false ) ); return artifacts; } @Override public Set getDependencyArtifacts() { return getArtifacts(); } public List getAttachedArtifacts() { if ( attachedArtifacts == null ) { attachedArtifacts = new ArrayList(); } return attachedArtifacts; } protected Artifact createArtifact( String groupId, String artifactId, String version, boolean optional ) { return createArtifact(groupId, artifactId, version, "jar", optional); } protected Artifact createArtifact( String groupId, String artifactId, String version, String type, boolean optional ) { Artifact artifact = new EsaArtifactStub(); artifact.setGroupId( groupId ); artifact.setArtifactId( artifactId ); artifact.setVersion( version ); artifact.setOptional( optional ); artifact.setFile( new File ( getBasedir() + "/src/test/remote-repo/" + artifact.getGroupId().replace( '.', '/' ) + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() + "/" + artifact.getArtifactId() + "-" + artifact.getVersion() + "." + type ) ) ; return artifact; } }
7,961
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub2.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class EsaMavenProjectStub2 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-with-descriptor/plugin-config.xml" ); } }
7,962
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub11.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.util.HashSet; import java.util.Set; public class EsaMavenProjectStub11 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-exclude-non-bundle-jars/plugin-config.xml" ); } public Set getArtifacts() { Set artifacts = new HashSet(); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact01", "1.0-SNAPSHOT", false ) ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact05-no-bundle-manifest", "1.1-SNAPSHOT", false )); return artifacts; } }
7,963
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub10.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.LinkedHashSet; import java.util.Set; public class EsaMavenProjectStub10 extends EsaMavenProjectStub { @Override public Set getArtifacts() { Set artifacts = new LinkedHashSet(); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact01", "1.0-SNAPSHOT", false ) ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact02", "1.0-SNAPSHOT", false ) ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact03", "1.1-SNAPSHOT", false ) ); return artifacts; } @Override public Set getDependencyArtifacts() { Set artifacts = new LinkedHashSet(); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact01", "1.0-SNAPSHOT", false ) ); artifacts.add( createArtifact( "org.apache.maven.test", "maven-artifact02", "1.0-SNAPSHOT", false ) ); return artifacts; } }
7,964
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaArtifactStub.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.testing.stubs.ArtifactStub; /** * @author <a href="mailto:aramirez@apache.org">Allan Ramirez</a> */ public class EsaArtifactStub extends ArtifactStub { private String groupId; private String artifactId; private String version; private String scope; private boolean optional; private File file; private VersionRange versionRange; public String getArtifactId() { return artifactId; } public void setArtifactId( String artifactId ) { this.artifactId = artifactId; } public File getFile() { return file; } public void setFile( File file ) { this.file = file; } public String getGroupId() { return groupId; } public void setGroupId( String groupId ) { this.groupId = groupId; } public boolean isOptional() { return optional; } public void setOptional( boolean optional ) { this.optional = optional; } public String getScope() { return scope; } public void setScope( String scope ) { this.scope = scope; } public String getVersion() { return version; } public void setVersion( String version ) { this.version = version; } public String getId() { return getGroupId() + ":" + getArtifactId() + ":" + getVersion(); } public String getBaseVersion() { return getVersion(); } @Override public VersionRange getVersionRange() { return versionRange; } @Override public void setVersionRange(VersionRange versionRange) { this.versionRange = versionRange; } }
7,965
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub7.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.testing.stubs.ArtifactStub; public class EsaMavenProjectStub7 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-test-with-pgk-type/plugin-config.xml" ); } @Override public Artifact getArtifact() { ArtifactStub artfct = (ArtifactStub) super.getArtifact(); artfct.setFile( new File( getBasedir(), "src/test/resources/unit/basic-esa-test-with-pgk-type/target/maven-esa-test-1.0-SNAPSHOT.jar" ) ); artfct.setType( "jar" ); return artfct; } }
7,966
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/BasicEsaStartOrder.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class BasicEsaStartOrder extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-start-order/plugin-config.xml" ); } }
7,967
0
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa
Create_ds/aries/esa-maven-plugin/src/test/java/org/apache/aries/plugin/esa/stubs/EsaMavenProjectStub6.java
package org.apache.aries.plugin.esa.stubs; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; public class EsaMavenProjectStub6 extends EsaMavenProjectStub { public File getFile() { return new File( getBasedir(), "src/test/resources/unit/basic-esa-content-bundles-only/plugin-config.xml" ); } }
7,968
0
Create_ds/aries/esa-maven-plugin/src/main/java/org/apache/aries/plugin
Create_ds/aries/esa-maven-plugin/src/main/java/org/apache/aries/plugin/esa/EsaMojo.java
package org.apache.aries.plugin.esa; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import static org.apache.aries.util.manifest.BundleManifest.fromBundle; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.apache.aries.util.manifest.BundleManifest; import org.apache.maven.archiver.PomPropertiesUtil; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.zip.ZipArchiver; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.FileUtils; /** * Builds OSGi Enterprise Subsystem Archive (esa) files. * * @version $Id: $ * @goal esa * @phase package * @requiresDependencyResolution test */ public class EsaMojo extends AbstractMojo { public enum EsaContent {none, all, content}; public enum EsaManifestContent {all, content}; public static final String SUBSYSTEM_MF_URI = "OSGI-INF/SUBSYSTEM.MF"; private static final String[] DEFAULT_INCLUDES = {"**/**"}; private static final Set<String> SKIP_INSTRUCTIONS = new HashSet<String>(); static { SKIP_INSTRUCTIONS.add(Constants.SUBSYSTEM_MANIFESTVERSION); SKIP_INSTRUCTIONS.add(Constants.SUBSYSTEM_SYMBOLICNAME); SKIP_INSTRUCTIONS.add(Constants.SUBSYSTEM_VERSION); SKIP_INSTRUCTIONS.add(Constants.SUBSYSTEM_NAME); SKIP_INSTRUCTIONS.add(Constants.SUBSYSTEM_DESCRIPTION); SKIP_INSTRUCTIONS.add(Constants.SUBSYSTEM_CONTENT); } /** * Single directory for extra files to include in the esa. * * @parameter expression="${basedir}/src/main/esa" * @required */ private File esaSourceDirectory; /** * The location of the SUBSYSTEM.MF file to be used within the esa file. * * @parameter expression="${basedir}/src/main/esa/OSGI-INF/SUBSYSTEM.MF" */ private File subsystemManifestFile; /** * The location of the manifest file to be used within the esa file. * * @parameter expression="${basedir}/src/main/esa/META-INF/MANIFEST.MF" */ private File manifestFile; /** * Directory that resources are copied to during the build. * * @parameter expression="${project.build.directory}/${project.build.finalName}" * @required */ private String workDirectory; /** * Directory that remote-resources puts legal files. * * @parameter expression="${project.build.directory}/maven-shared-archive-resources" * @required */ private String sharedResources; /** * The directory for the generated esa. * * @parameter expression="${project.build.directory}" * @required */ private String outputDirectory; /** * The name of the esa file to generate. * * @parameter alias="esaName" expression="${project.build.finalName}" * @required */ private String finalName; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * The Jar archiver. * * @component role="org.codehaus.plexus.archiver.Archiver" roleHint="zip" * @required */ private ZipArchiver zipArchiver; /** * Whether to generate a manifest based on maven configuration. * * @parameter expression="${generateManifest}" default-value="false" */ private boolean generateManifest; /** * Configuration for the plugin. * * @parameter */ private Map instructions = new LinkedHashMap(); /** * Adding pom.xml and pom.properties to the archive. * * @parameter expression="${addMavenDescriptor}" default-value="true" */ private boolean addMavenDescriptor; /** * Include or not empty directories * * @parameter expression="${includeEmptyDirs}" default-value="true" */ private boolean includeEmptyDirs; /** * Whether creating the archive should be forced. * * @parameter expression="${forceCreation}" default-value="false" */ private boolean forceCreation; /** * Define which bundles to include in the archive. * none - no bundles are included * content - direct dependencies go into the content * all - direct and transitive dependencies go into the content * * @parameter expression="${archiveContent}" default-value="content" */ private String archiveContent; /** * Define which bundles to include in the manifest Subsystem-Content header. * all - direct and transitive dependencies go into the Subsystem-Content header * content - direct dependencies go into the Subsystem-Content header * * @parameter expression="${manifestContent}" default-value="content" */ private String manifestContent; /** * Define the start order for content bundles. * none - no start orders are added * dependencies - start order based on pom dependency order * * @parameter expression="${startOrder}" default-value="none" */ private String startOrder; private File buildDir; /** * add the dependencies to the archive depending on the configuration of <archiveContent /> */ private void addDependenciesToArchive() throws MojoExecutionException { try { Set<Artifact> artifacts = null; switch (EsaContent.valueOf(archiveContent)) { case none: getLog().info("archiveContent=none: subsystem archive will not contain any bundles."); break; case content: // only include the direct dependencies in the archive artifacts = project.getDependencyArtifacts(); break; case all: // include direct and transitive dependencies in the archive artifacts = project.getArtifacts(); break; default: throw new MojoExecutionException("Invalid configuration for <archiveContent/>. Valid values are none, content and all." ); } if (artifacts != null) { // Explicitly add self to bundle set (used when pom packaging // type != "esa" AND a file is present (no point to add to // zip archive without file) final Artifact selfArtifact = project.getArtifact(); if (!"esa".equals(selfArtifact.getType()) && selfArtifact.getFile() != null) { getLog().info("Explicitly adding artifact[" + selfArtifact.getGroupId() + ", " + selfArtifact.getId() + ", " + selfArtifact.getScope() + "]"); artifacts.add(project.getArtifact()); } artifacts = selectArtifactsInCompileOrRuntimeScope(artifacts); artifacts = selectNonJarArtifactsAndBundles(artifacts); int cnt = 0; for (Artifact artifact : artifacts) { if (!artifact.isOptional() /*&& filter.include(artifact)*/) { getLog().info("Copying artifact[" + artifact.getGroupId() + ", " + artifact.getId() + ", " + artifact.getScope() + "]"); zipArchiver.addFile(artifact.getFile(), artifact.getArtifactId() + "-" + artifact.getVersion() + "." + (artifact.getType() == null ? "jar" : artifact.getType())); cnt++; } } getLog().info(String.format("Added %s artifacts to subsystem subsystem archive.", cnt)); } } catch ( ArchiverException e ) { throw new MojoExecutionException( "Error copying esa dependencies", e ); } } /** * * Copies source files to the esa * * @throws MojoExecutionException */ private void copyEsaSourceFiles() throws MojoExecutionException { try { File esaSourceDir = esaSourceDirectory; if ( esaSourceDir.exists() ) { getLog().info( "Copy esa resources to " + getBuildDir().getAbsolutePath() ); DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( esaSourceDir.getAbsolutePath() ); scanner.setIncludes( DEFAULT_INCLUDES ); scanner.addDefaultExcludes(); scanner.scan(); String[] dirs = scanner.getIncludedDirectories(); for ( int j = 0; j < dirs.length; j++ ) { new File( getBuildDir(), dirs[j] ).mkdirs(); } String[] files = scanner.getIncludedFiles(); for ( int j = 0; j < files.length; j++ ) { File targetFile = new File( getBuildDir(), files[j] ); targetFile.getParentFile().mkdirs(); File file = new File( esaSourceDir, files[j] ); FileUtils.copyFileToDirectory( file, targetFile.getParentFile() ); } } } catch ( Exception e ) { throw new MojoExecutionException( "Error copying esa resources", e ); } } private void includeCustomManifest() throws MojoExecutionException { try { if (!generateManifest) { includeCustomSubsystemManifestFile(); } } catch ( IOException e ) { throw new MojoExecutionException( "Error copying SUBSYSTEM.MF file", e ); } } private void generateSubsystemManifest() throws MojoExecutionException { if (generateManifest) { String fileName = new String(getBuildDir() + "/" + SUBSYSTEM_MF_URI); File appMfFile = new File(fileName); try { // Delete any old manifest if (appMfFile.exists()) { FileUtils.fileDelete(fileName); } appMfFile.getParentFile().mkdirs(); if (appMfFile.createNewFile()) { writeSubsystemManifest(fileName); } } catch (java.io.IOException e) { throw new MojoExecutionException( "Error generating SUBSYSTEM.MF file: " + fileName, e); } } // Check the manifest exists File ddFile = new File( getBuildDir(), SUBSYSTEM_MF_URI); if ( !ddFile.exists() ) { getLog().warn( "Subsystem manifest: " + ddFile.getAbsolutePath() + " does not exist." ); } } private void addMavenDescriptor() throws MojoExecutionException { try { if (addMavenDescriptor) { if (project.getArtifact().isSnapshot()) { project.setVersion(project.getArtifact().getVersion()); } String groupId = project.getGroupId(); String artifactId = project.getArtifactId(); zipArchiver.addFile(project.getFile(), "META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml"); PomPropertiesUtil pomPropertiesUtil = new PomPropertiesUtil(); File dir = new File(project.getBuild().getDirectory(), "maven-zip-plugin"); File pomPropertiesFile = new File(dir, "pom.properties"); pomPropertiesUtil.createPomProperties(project, zipArchiver, pomPropertiesFile, forceCreation); } } catch (Exception e) { throw new MojoExecutionException("Error assembling esa", e); } } private void init() { getLog().debug( " ======= esaMojo settings =======" ); getLog().debug( "esaSourceDirectory[" + esaSourceDirectory + "]" ); getLog().debug( "manifestFile[" + manifestFile + "]" ); getLog().debug( "subsystemManifestFile[" + subsystemManifestFile + "]" ); getLog().debug( "workDirectory[" + workDirectory + "]" ); getLog().debug( "outputDirectory[" + outputDirectory + "]" ); getLog().debug( "finalName[" + finalName + "]" ); getLog().debug( "generateManifest[" + generateManifest + "]" ); if (archiveContent == null) { archiveContent = new String("content"); } getLog().debug( "archiveContent[" + archiveContent + "]" ); getLog().info( "archiveContent[" + archiveContent + "]" ); if (manifestContent == null) { manifestContent = new String("content"); } getLog().debug( "manifestContent[" + archiveContent + "]" ); getLog().info( "manifestContent[" + archiveContent + "]" ); zipArchiver.setIncludeEmptyDirs( includeEmptyDirs ); zipArchiver.setCompress( true ); zipArchiver.setForced( forceCreation ); } private void writeSubsystemManifest(String fileName) throws MojoExecutionException { try { // TODO: add support for dependency version ranges. Need to pick // them up from the pom and convert them to OSGi version ranges. FileUtils.fileAppend(fileName, Constants.SUBSYSTEM_MANIFESTVERSION + ": " + "1" + "\n"); FileUtils.fileAppend(fileName, Constants.SUBSYSTEM_SYMBOLICNAME + ": " + getSubsystemSymbolicName(project.getArtifact()) + "\n"); FileUtils.fileAppend(fileName, Constants.SUBSYSTEM_VERSION + ": " + getSubsystemVersion() + "\n"); FileUtils.fileAppend(fileName, Constants.SUBSYSTEM_NAME + ": " + getSubsystemName() + "\n"); String description = getSubsystemDescription(); if (description != null) { FileUtils.fileAppend(fileName, Constants.SUBSYSTEM_DESCRIPTION + ": " + description + "\n"); } // Write the SUBSYSTEM-CONTENT Set<Artifact> artifacts = null; switch (EsaManifestContent.valueOf(manifestContent)) { case content: // only include the direct dependencies in the content artifacts = project.getDependencyArtifacts(); break; case all: // include direct and transitive dependencies in content artifacts = project.getArtifacts(); break; default: throw new MojoExecutionException("Invalid configuration for <manifestContent/>. Valid values are content and all." ); } artifacts = selectArtifactsInCompileOrRuntimeScope(artifacts); artifacts = selectNonJarArtifactsAndBundles(artifacts); Iterator<Artifact> iter = artifacts.iterator(); FileUtils.fileAppend(fileName, Constants.SUBSYSTEM_CONTENT + ": "); int order = 0; int nbInSubsystemContent = 0; while (iter.hasNext()) { Artifact artifact = iter.next(); order++; ContentInfo info = ContentInfo.create(artifact, getLog()); if (info == null) { continue; } String entry = info.getContentLine(); if ("dependencies".equals(startOrder)) { entry += ";start-order:=\"" + order + "\""; } if (iter.hasNext()) { entry += ",\n "; } nbInSubsystemContent++; FileUtils.fileAppend(fileName, entry); } getLog().info("Added '" + nbInSubsystemContent + "' artefacts to the Subsystem-Content header"); FileUtils.fileAppend(fileName, "\n"); Iterator<Map.Entry<?, ?>> instructionIter = instructions.entrySet().iterator(); while(instructionIter.hasNext()) { Map.Entry<?, ?> entry = instructionIter.next(); String header = entry.getKey().toString(); if (SKIP_INSTRUCTIONS.contains(header)) { continue; } getLog().debug("Adding header: " + header); FileUtils.fileAppend(fileName, header + ": " + entry.getValue() + "\n"); } } catch (Exception e) { throw new MojoExecutionException( "Error writing dependencies into SUBSYSTEM.MF", e); } } // The maven2OsgiConverter assumes the artifact is a jar so we need our own // This uses the same fallback scheme as the converter private String getSubsystemSymbolicName(Artifact artifact) { if (instructions.containsKey(Constants.SUBSYSTEM_SYMBOLICNAME)) { return instructions.get(Constants.SUBSYSTEM_SYMBOLICNAME).toString(); } return artifact.getGroupId() + "." + artifact.getArtifactId(); } private String getSubsystemVersion() { if (instructions.containsKey(Constants.SUBSYSTEM_VERSION)) { return instructions.get(Constants.SUBSYSTEM_VERSION).toString(); } return aQute.lib.osgi.Analyzer.cleanupVersion(project.getVersion()); } private String getSubsystemName() { if (instructions.containsKey(Constants.SUBSYSTEM_NAME)) { return instructions.get(Constants.SUBSYSTEM_NAME).toString(); } return project.getName(); } private String getSubsystemDescription() { if (instructions.containsKey(Constants.SUBSYSTEM_DESCRIPTION)) { return instructions.get(Constants.SUBSYSTEM_DESCRIPTION).toString(); } return project.getDescription(); } private File getBuildDir() { if (buildDir == null) { buildDir = new File(workDirectory); } return buildDir; } private void addBuildDir() throws MojoExecutionException { try { if (buildDir.isDirectory()) { zipArchiver.addDirectory(buildDir); } } catch (Exception e) { throw new MojoExecutionException( "Error writing dependencies into SUBSYSTEM.MF", e); } } private void includeCustomSubsystemManifestFile() throws IOException { if (subsystemManifestFile == null) { throw new NullPointerException("Subsystem manifest file location not set. Use <generateManifest>true</generateManifest> if you want it to be generated."); } File appMfFile = subsystemManifestFile; if (appMfFile.exists()) { getLog().info( "Using SUBSYSTEM.MF "+ subsystemManifestFile); File osgiInfDir = new File(getBuildDir(), "OSGI-INF"); FileUtils.copyFileToDirectory( appMfFile, osgiInfDir); } } /** * Return non-pom artifacts in 'compile' or 'runtime' scope only. */ private Set<Artifact> selectArtifactsInCompileOrRuntimeScope(Set<Artifact> artifacts) { Set<Artifact> selected = new LinkedHashSet<Artifact>(); for (Artifact artifact : artifacts) { String scope = artifact.getScope(); if (scope == null || Artifact.SCOPE_COMPILE.equals(scope) || Artifact.SCOPE_RUNTIME.equals(scope)) { if (artifact.getType() == null || !artifact.getType().equals("pom")) { selected.add(artifact); } } } return selected; } /** * Returns bundles and artifacts that aren't JARs */ private Set<Artifact> selectNonJarArtifactsAndBundles(Set<Artifact> artifacts) { Set<Artifact> selected = new LinkedHashSet<Artifact>(); for (Artifact artifact : artifacts) { if (isNonJarOrOSGiBundle(artifact)) { selected.add(artifact); } else { getLog().warn("Skipping dependency on non-bundle JAR! groupId: " + artifact.getGroupId() + " artifactId:" + artifact.getArtifactId()); } } return selected; } private boolean isNonJarOrOSGiBundle(Artifact artifact) { if(!artifact.getFile().getName().endsWith(".jar")){ return true; } else { BundleManifest manifest = fromBundle(artifact.getFile()); return manifest != null && manifest.getSymbolicName() != null; } } private void includeSharedResources() throws MojoExecutionException { try { //include legal files if any File sharedResourcesDir = new File(sharedResources); if (sharedResourcesDir.isDirectory()) { zipArchiver.addDirectory(sharedResourcesDir); } } catch ( Exception e ) { throw new MojoExecutionException( "Error assembling esa", e ); } } /** * Creates the final archive. * * @throws MojoExecutionException */ private void createEsaFile() throws MojoExecutionException { try { File esaFile = new File( outputDirectory, finalName + ".esa" ); zipArchiver.setDestFile(esaFile); zipArchiver.createArchive(); project.getArtifact().setFile( esaFile ); } catch ( Exception e ) { throw new MojoExecutionException( "Error assembling esa", e ); } } public void execute() throws MojoExecutionException { init(); addDependenciesToArchive(); copyEsaSourceFiles(); includeCustomManifest(); generateSubsystemManifest(); addMavenDescriptor(); addBuildDir(); includeSharedResources(); createEsaFile(); } }
7,969
0
Create_ds/aries/esa-maven-plugin/src/main/java/org/apache/aries/plugin
Create_ds/aries/esa-maven-plugin/src/main/java/org/apache/aries/plugin/esa/ContentInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.plugin.esa; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import aQute.lib.osgi.Analyzer; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.logging.Log; import org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter; import org.apache.maven.shared.osgi.Maven2OsgiConverter; public class ContentInfo { /** * Coverter for maven pom values to OSGi manifest values (pulled in from the maven-bundle-plugin) */ private static Maven2OsgiConverter maven2OsgiConverter = new DefaultMaven2OsgiConverter(); private String symbolicName; private String type; private String version; private VersionRange mavenVersionRange; public String getSymbolicName() { return symbolicName; } public String getType() { return type; } public String getVersion() { return version; } public String getContentLine() { String line = symbolicName; if (type != null) { line += ";type=\"" + type + "\""; } if (mavenVersionRange != null && mavenVersionRange.hasRestrictions()) { line += ";version=\"" + mavenVersionRange + '"'; } else { if (version != null) { line += ";version=\"[" + version + "," + version + "]\""; } } return line; } public static ContentInfo create(Artifact artifact, Log log) { ZipFile zip = null; try { zip = new ZipFile(artifact.getFile()); ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF"); if (entry != null) { Manifest mf = getManifest(zip, entry); return handleManifest(artifact, mf); } else { // no manifest.mf entry = zip.getEntry("OSGI-INF/SUBSYSTEM.MF"); if (entry != null) { Manifest mf = getManifest(zip, entry); return handleSubsystem(artifact, mf); } else { // and no subsystem.mf return handleUnknown(artifact); } } } catch (Exception e) { log.warn("Error creating content information for artifact '" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":v" + artifact.getVersion() + "'", e); return null; } finally { if (zip != null) { try { zip.close(); } catch (IOException ignore) {} } } } private static ContentInfo handleUnknown(Artifact artifact) { ContentInfo info = new ContentInfo(); info.symbolicName = maven2OsgiConverter.getBundleSymbolicName(artifact); info.version = Analyzer.cleanupVersion(artifact.getVersion()); info.mavenVersionRange = artifact.getVersionRange(); return info; } private static ContentInfo handleSubsystem(Artifact artifact, Manifest mf) { ContentInfo info = new ContentInfo(); Attributes mainAttributes = mf.getMainAttributes(); String subsystemSymbolicName = mainAttributes.getValue(Constants.SUBSYSTEM_SYMBOLICNAME); if (subsystemSymbolicName != null) { Map<String, ?> header = Analyzer.parseHeader(subsystemSymbolicName, null); info.symbolicName = header.keySet().iterator().next(); } String subsystemVersion = mainAttributes.getValue(Constants.SUBSYSTEM_VERSION); if (subsystemVersion != null) { info.version = subsystemVersion; } String subsystemType = mainAttributes.getValue(Constants.SUBSYSTEM_TYPE); if (subsystemType == null) { info.type = Constants.APPLICATION_TYPE; } else { Map<String, ?> header = Analyzer.parseHeader(subsystemType, null); info.type = header.keySet().iterator().next(); } info.mavenVersionRange = artifact.getVersionRange(); return info; } private static ContentInfo handleManifest(Artifact artifact, Manifest mf) { Attributes mainAttributes = mf.getMainAttributes(); String bundleSymbolicName = mainAttributes.getValue(Constants.BUNDLE_SYMBOLICNAME); if (bundleSymbolicName == null) { // not a bundle return handleUnknown(artifact); } else { ContentInfo info = new ContentInfo(); Map<String, ?> header = Analyzer.parseHeader(bundleSymbolicName, null); info.symbolicName = header.keySet().iterator().next(); String bundleVersion = mainAttributes.getValue(Constants.BUNDLE_VERSION); if (bundleVersion != null) { info.version = bundleVersion; } if (mainAttributes.getValue(Constants.FRAGMENT_HOST) != null) { info.type = Constants.FRAGMENT_TYPE; } info.mavenVersionRange = artifact.getVersionRange(); return info; } } private static Manifest getManifest(ZipFile zip, ZipEntry entry) throws IOException { InputStream in = null; try { in = zip.getInputStream(entry); Manifest mf = new Manifest(in); return mf; } finally { if (in != null) { try { in.close(); } catch (IOException ignore) {} } } } }
7,970
0
Create_ds/aries/esa-maven-plugin/src/main/java/org/apache/aries/plugin
Create_ds/aries/esa-maven-plugin/src/main/java/org/apache/aries/plugin/esa/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.plugin.esa; public class Constants { public static final String BUNDLE_VERSION = "Bundle-Version"; public static final String BUNDLE_SYMBOLICNAME = "Bundle-SymbolicName"; public static final String FRAGMENT_HOST = "Fragment-Host"; public static final String BUNDLE_TYPE = "osgi.bundle"; public static final String FRAGMENT_TYPE = "osgi.fragment"; public static final String APPLICATION_TYPE = "osgi.subsystem.application"; /* * Subsystem manifest headers */ public static final String SUBSYSTEM_MANIFESTVERSION = "Subsystem-ManifestVersion"; public static final String SUBSYSTEM_SYMBOLICNAME = "Subsystem-SymbolicName"; public static final String SUBSYSTEM_VERSION = "Subsystem-Version"; public static final String SUBSYSTEM_NAME = "Subsystem-Name"; public static final String SUBSYSTEM_DESCRIPTION = "Subsystem-Description"; public static final String SUBSYSTEM_CONTENT = "Subsystem-Content"; public static final String SUBSYSTEM_USEBUNDLE = "Use-Bundle"; public static final String SUBSYSTEM_TYPE = "Subsystem-Type"; }
7,971
0
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx/blueprint/BlueprintMetadataMBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.blueprint; import java.io.IOException; import javax.management.openmbean.ArrayType; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeType; import javax.management.openmbean.SimpleType; public interface BlueprintMetadataMBean { /** * The object name for this MBean. */ String OBJECTNAME = JmxConstants.ARIES_BLUEPRINT+":service=blueprintMetadata,version=1.0"; /////////////////////////////////////////////////////////////// // Define <value>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key STRING_VALUE, used in {@link #STRING_VALUE_ITEM}. */ String STRING_VALUE = "StringValue"; /** * The item containing the un-converted string representation of the value. * The key is {@link #STRING_VALUE}, and the type is {@link SimpleType#STRING}. */ Item STRING_VALUE_ITEM = new Item( STRING_VALUE, "The un-converted string representation of a value", SimpleType.STRING); /** * The key TYPE, used in {@link #TYPE_ITEM}. */ String TYPE = "Type"; /** * The item containing the name of the type to which the value should be converted. * The key is {@link #TYPE}, and the type is {@link SimpleType#STRING}. */ Item TYPE_ITEM = new Item( TYPE, "The type of a value", SimpleType.STRING); /** * The name of CompositeType for ValueMetadata objects, used in {@link #VALUE_METADATA_TYPE}. */ String VALUE_METADATA = "ValueMetadata"; /** * The CompositeType encapsulates ValueMetadata objects. It contains the following items: * <ul> * <li>{@link #STRING_VALUE}</li> * <li>{@link #TYPE}</li> * </ul> */ CompositeType VALUE_METADATA_TYPE = Item.compositeType( VALUE_METADATA, "This type encapsulates ValueMetadata objects", STRING_VALUE_ITEM, TYPE_ITEM); /////////////////////////////////////////////////////////////// // Define <null>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key PLACEHOLDER, used in {@link #PLACEHOLDER_ITEM}. */ String PLACEHOLDER = "Placeholder"; /** * The item is a placeholder in the null metadata type. * The key is {@link #PLACEHOLDER}, and the type is {@link SimpleType#STRING}. */ Item PLACEHOLDER_ITEM = new Item( PLACEHOLDER, "This is a placeholder", SimpleType.VOID); /** * The name of CompositeType for NullMetadata objects, used in {@link #NULL_METADATA_TYPE}. */ String NULL_METADATA = "NullMetadata"; /** * The CompositeType for NullMetadata objects. A composite type requires at least one item, so we add a placeholder item. */ CompositeType NULL_METADATA_TYPE = Item.compositeType( NULL_METADATA, "This type encapsulates NullMetadata objects", PLACEHOLDER_ITEM); /////////////////////////////////////////////////////////////// // Define <ref>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key COMPONENT_ID, used in {@link #COMPONENT_ID_ITEM}. */ String COMPONENT_ID = "ComponentId"; /** * The item containing the component id to which the "ref" associates. * The key is {@link #COMPONENT_ID}, and the type is {@link SimpleType#STRING}. */ Item COMPONENT_ID_ITEM = new Item( COMPONENT_ID, "The component id", SimpleType.STRING); /** * The name of CompositeType for RefMetadata objects, used in {@link #REF_METADATA_TYPE}. */ String REF_METADATA = "RefMetadata"; /** * The CompositeType for a RefMetadata object. It contains the following items: * <ul> * <li>{@link #COMPONENT_ID}</li> * </ul> */ CompositeType REF_METADATA_TYPE = Item.compositeType( REF_METADATA, "This type encapsulates RefMetadata objects", COMPONENT_ID_ITEM); /////////////////////////////////////////////////////////////// // Define <idref>'s CompositeType // COMPONENT_ID_ITEM defined in <ref>'s definition /////////////////////////////////////////////////////////////// /** * The name of CompositeType for IdRefMetadata objects, used in {@link #ID_REF_METADATA_TYPE}. */ String ID_REF_METADATA = "IdRefMetadata"; /** * The CompositeType for an IdRefMetadata object. It contains the following items: * <ul> * <li>{@link #COMPONENT_ID}</li> * </ul> */ CompositeType ID_REF_METADATA_TYPE = Item.compositeType( ID_REF_METADATA, "This type encapsulates IdRefMetadata objects", COMPONENT_ID_ITEM); /////////////////////////////////////////////////////////////// // Define <entry>'s CompositeType, // used by MapMetadata, PropsMetadata, and Service properties /////////////////////////////////////////////////////////////// /** * The key KEY, used in {@link #KEY_ITEM}. */ String KEY = "Key"; /** * The item containing the key of an entry. * The key is {@link #KEY}, and the type is {@link SimpleType#STRING}. */ Item KEY_ITEM = new Item( KEY, "The key of an entry", JmxConstants.BYTE_ARRAY_TYPE); /** * The key VALUE, used in {@link #VALUE_ITEM}. */ String VALUE = "Value"; /** * The item containing a value and this will be used by * BeanArgument, BeanProperty, MapEntry and CollectionMetadata. * The key is {@link #VALUE}, and the type is {@link JmxConstants#BYTE_ARRAY_TYPE}. */ Item VALUE_ITEM = new Item( VALUE, "A value", JmxConstants.BYTE_ARRAY_TYPE); /** * The name of CompositeType for MapEntry objects, used in {@link #MAP_ENTRY_TYPE}. */ String MAP_ENTRY = "MapEntry"; /** * The CompositeType for a MapEntry object. It contains the following items: * <ul> * <li>{@link #KEY}</li> * <li>{@link #VALUE}</li> * </ul> */ CompositeType MAP_ENTRY_TYPE = Item.compositeType( MAP_ENTRY, "This type encapsulates MapEntry objects", KEY_ITEM, VALUE_ITEM); /////////////////////////////////////////////////////////////// // Define <map>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key ENTRIES, used in {@link #ENTRIES_ITEM}. */ String ENTRIES = "Entries"; /** * The item containing an array of entries * The key is {@link #ENTRIES}, and the type is {@link ArrayType}. */ Item ENTRIES_ITEM = new Item( ENTRIES, "An array of entries", Item.arrayType(1, MAP_ENTRY_TYPE)); /** * The key KEY_TYPE, used in {@link #KEY_TYPE_ITEM}. */ String KEY_TYPE = "KeyType"; /** * The item containing the key type of the entries. * The key is {@link #KEY_TYPE}, and the type is {@link SimpleType#STRING}. */ Item KEY_TYPE_ITEM = new Item( KEY_TYPE, "The key type of the entries", SimpleType.STRING); /** * The key VALUE_TYPE, used in {@link #VALUE_TYPE_ITEM}. */ String VALUE_TYPE = "ValueType"; /** * The item containing the value type that the value should be * The key is {@link #VALUE_TYPE}, and the type is {@link SimpleType#STRING}. */ Item VALUE_TYPE_ITEM = new Item( VALUE_TYPE, "The value type", SimpleType.STRING); /** * The name of CompositeType for MapMetadata objects, used in {@link #MAP_METADATA_TYPE}. */ String MAP_METADATA = "MapMetadata"; /** * The CompositeType for a MapMetadata object. It contains the following items: * <ul> * <li>{@link #ENTRIES}</li> * <li>{@link #KEY_TYPE}</li> * <li>{@link #VALUE_TYPE}</li> * </ul> */ CompositeType MAP_METADATA_TYPE = Item.compositeType( MAP_METADATA, "This type encapsulates MapMetadata objects", ENTRIES_ITEM, KEY_TYPE_ITEM, VALUE_TYPE_ITEM); /////////////////////////////////////////////////////////////// // Define <props>'s CompositeType // ENTRIES_ITEM defined in <map>'s definition /////////////////////////////////////////////////////////////// /** * The name of CompositeType for PropsMetadata objects, used in {@link #PROPS_METADATA_TYPE}. */ String PROPS_METADATA = "PropsMetadata"; /** * The CompositeType for a PropsMetadata object. It contains the following items: * <ul> * <li>{@link #ENTRIES}</li> * </ul> */ CompositeType PROPS_METADATA_TYPE = Item.compositeType( PROPS_METADATA, "This type encapsulates PropsMetadata objects", ENTRIES_ITEM); /////////////////////////////////////////////////////////////// // Define <collection>'s CompositeType // VALUE_TYPE_ITEM defined in <map>'s definition /////////////////////////////////////////////////////////////// /** * The key COLLECTION_CLASS, used in {@link #KEY_TYPE_ITEM}. */ String COLLECTION_CLASS = "CollectionClass"; /** * The item containing the type of this collection * The key is {@link #COLLECTION_CLASS}, and the type is {@link SimpleType#STRING}. */ Item COLLECTION_CLASS_ITEM = new Item( COLLECTION_CLASS, "The type of this collection", SimpleType.STRING); /** * The key VALUES, used in {@link #VALUES_ITEM}. */ String VALUES = "Values"; /** * The item containing all the values * The key is {@link #VALUES}, and the type is {@link ArrayType}. */ Item VALUES_ITEM = new Item( VALUES, "All the values", Item.arrayType(2, SimpleType.BYTE)); /** * The name of CompositeType for CollectionMetadata objects, used in {@link #COLLECTION_METADATA_TYPE}. */ String COLLECTION_METADATA = "CollectionMetadata"; /** * The CompositeType for a CollectionMetadata object. It contains the following items: * <ul> * <li>{@link #COLLECTION_CLASS}</li> * <li>{@link #VALUES}</li> * <li>{@link #VALUE_TYPE}</li> * </ul> */ CompositeType COLLECTION_METADATA_TYPE= Item.compositeType( COLLECTION_METADATA, "This type encapsulates CollectionMetadata objects", COLLECTION_CLASS_ITEM, VALUES_ITEM, VALUE_TYPE_ITEM); /////////////////////////////////////////////////////////////// // Define <argument>'s CompositeType // VALUE_TYPE_ITEM defined in <map>'s definition /////////////////////////////////////////////////////////////// /** * The key INDEX, used in {@link #INDEX_ITEM}. */ String INDEX = "Index"; /** * The item containing the zero-based index into the parameter list of * the factory method or constructor to be invoked for this argument. * The key is {@link #INDEX}, and the type is {@link SimpleType#INTEGER}. */ Item INDEX_ITEM = new Item( INDEX, "The zero-based index", SimpleType.INTEGER); /** * The name of CompositeType for BeanArgument objects, used in {@link #BEAN_ARGUMENT_TYPE}. */ String BEAN_ARGUMENT = "BeanArgument"; /** * The CompositeType for a Argument object. It contains the following items: * <ul> * <li>{@link #INDEX}</li> * <li>{@link #VALUE_TYPE}</li> * <li>{@link #VALUE}</li> * </ul> */ CompositeType BEAN_ARGUMENT_TYPE = Item.compositeType( BEAN_ARGUMENT, "This type encapsulates BeanArgument objects", INDEX_ITEM, VALUE_TYPE_ITEM, VALUE_ITEM); /////////////////////////////////////////////////////////////// // Define <property>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key NAME, used in {@link #NAME_ITEM}. */ String NAME = "Name"; /** * The item containing the name of the property to be injected. * The key is {@link #NAME}, and the type is {@link SimpleType#STRING}. */ Item NAME_ITEM = new Item( NAME, "The name of the property", SimpleType.STRING); /** * The name of CompositeType for BeanProperty objects, used in {@link #BEAN_PROPERTY_TYPE}. */ String BEAN_PROPERTY = "BeanProperty"; /** * The CompositeType for property type. It contains the following items: * <ul> * <li>{@link #NAME}</li> * <li>{@link #VALUE}</li> * </ul> */ CompositeType BEAN_PROPERTY_TYPE = Item.compositeType( BEAN_PROPERTY, "This type encapsulates BeanProperty objects", NAME_ITEM, VALUE_ITEM); /////////////////////////////////////////////////////////////// // Define Component's CompositeType // <bean>, <service> & Service Reference's CompositeType will // extend this. /////////////////////////////////////////////////////////////// /** * The key ID, used in {@link #ID_ITEM}. */ String ID = "Id"; /** * The item containing the component id of a component. * The key is {@link #ID}, and the type is {@link SimpleType#STRING}. */ Item ID_ITEM = new Item( ID, "The id of the component", SimpleType.STRING); /** * The key ACTIVATION, used in {@link #ACTIVATION_ITEM}. */ String ACTIVATION = "Activation"; /** * The item containing the activation strategy for a component. * The key is {@link #ACTIVATION}, and the type is {@link SimpleType#INTEGER}. */ Item ACTIVATION_ITEM = new Item( ACTIVATION, "The activation strategy for a component", SimpleType.INTEGER); /** * The key DEPENDS_ON, used in {@link #DEPENDS_ON_ITEM}. */ String DEPENDS_ON = "DependsOn"; /** * The item containing the ids of any components listed in a <code>depends-on</code> attribute for the component. * The key is {@link #DEPENDS_ON}, and the type is {@link JmxConstants#STRING_ARRAY_TYPE}. */ Item DEPENDS_ON_ITEM = new Item( DEPENDS_ON, "The ids of any components listed in a depends-on attribute", JmxConstants.STRING_ARRAY_TYPE); /** * The name of CompositeType for ComponentMetadata objects, used in {@link #COMPONENT_METADATA_TYPE}. */ String COMPONENT_METADATA = "ComponentMetadata"; /** * The CompositeType for a ComponentMetadata object, it contains * the following items: * <ul> * <li>{@link #ID}</li> * <li>{@link #ACTIVATION}</li> * <li>{@link #DEPENDS_ON}</li> * </ul> */ CompositeType COMPONENT_METADATA_TYPE = Item.compositeType( COMPONENT_METADATA, "This type encapsulates ComponentMetadata objects", ID_ITEM, ACTIVATION_ITEM, DEPENDS_ON_ITEM); /////////////////////////////////////////////////////////////// // Define <bean>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key CLASS_NAME, used in {@link #CLASS_NAME_ITEM}. */ String CLASS_NAME = "ClassName"; /** * The item containing the name of the class specified for the bean. * The key is {@link #CLASS_NAME}, and the type is {@link SimpleType#STRING}. */ Item CLASS_NAME_ITEM = new Item( CLASS_NAME, "The name of the class specified for the bean", SimpleType.STRING ); /** * The key INIT_METHOD, used in {@link #INIT_METHOD_ITEM}. */ String INIT_METHOD = "InitMethod"; /** * The item containing the name of the init method specified for the bean. * The key is {@link #INIT_METHOD}, and the type is {@link SimpleType#STRING}. */ Item INIT_METHOD_ITEM = new Item( INIT_METHOD, "The name of the init method specified for the bean", SimpleType.STRING); /** * The key DESTROY_METHOD, used in {@link #DESTROY_METHOD_ITEM}. */ String DESTROY_METHOD = "DestroyMethod"; /** * The item containing the name of the destroy method specified for the bean. * The key is {@link #DESTROY_METHOD}, and the type is {@link SimpleType#STRING}. */ Item DESTROY_METHOD_ITEM = new Item( DESTROY_METHOD, "The name of the destroy method specified for the bean", SimpleType.STRING); /** * The key FACTORY_METHOD, used in {@link #FACTORY_METHOD_ITEM}. */ String FACTORY_METHOD = "FactoryMethod"; /** * The item containing the name of the factory method specified for the bean. * The key is {@link #FACTORY_METHOD}, and the type is {@link SimpleType#STRING}. */ Item FACTORY_METHOD_ITEM = new Item( FACTORY_METHOD, "The name of the factory method specified for the bean", SimpleType.STRING); /** * The key FACTORY_COMPONENT, used in {@link #FACTORY_COMPONENT_ITEM}. */ String FACTORY_COMPONENT = "FactoryComponent"; /** * The item containing the id of the factory component on which to invoke the factory method for the bean. * The key is {@link #FACTORY_COMPONENT}, and the type is {@link JmxConstants#BYTE_ARRAY_TYPE}. */ Item FACTORY_COMPONENT_ITEM = new Item( FACTORY_COMPONENT, "The factory component on which to invoke the factory method for the bean", JmxConstants.BYTE_ARRAY_TYPE); /** * The key SCOPE, used in {@link #SCOPE_ITEM}. */ String SCOPE = "Scope"; /** * The item containing the scope for the bean. * The key is {@link #SCOPE}, and the type is {@link SimpleType#STRING}. */ Item SCOPE_ITEM = new Item( SCOPE, "The scope for the bean", SimpleType.STRING); /** * The key ARGUMENT, used in {@link #ARGUMENTS_ITEM}. */ String ARGUMENTS = "Arguments"; /** * The item containing the bean argument for the bean's compositeType. * The key is {@link #ARGUMENTS}, and the type is {@link #BEAN_ARGUMENT_TYPE}. */ Item ARGUMENTS_ITEM = new Item( ARGUMENTS, "The bean argument", Item.arrayType(1, BEAN_ARGUMENT_TYPE)); /** * The key PROPERTY, used in {@link #PROPERTIES_ITEM}. */ String PROPERTIES = "Properties"; /** * The item containing the bean property for the bean's compositeType. * The key is {@link #PROPERTIES}, and the type is {@link #BEAN_PROPERTY_TYPE}. */ Item PROPERTIES_ITEM = new Item( PROPERTIES, "The bean property", Item.arrayType(1, BEAN_PROPERTY_TYPE)); /** * The name of CompositeType for BeanMetadata objects, used in {@link #BEAN_METADATA_TYPE}. */ String BEAN_METADATA = "BeanMetadata"; /** * The CompositeType for a BeanMetadata object, it extends {@link #COMPONENT_METADATA_TYPE} * and adds the following items: * <ul> * <li>{@link #CLASS_NAME}</li> * <li>{@link #INIT_METHOD}</li> * <li>{@link #DESTROY_METHOD}</li> * <li>{@link #FACTORY_METHOD}</li> * <li>{@link #FACTORY_COMPONENT}</li> * <li>{@link #SCOPE}</li> * <li>{@link #ARGUMENTS}</li> * <li>{@link #PROPERTIES}</li> * </ul> */ CompositeType BEAN_METADATA_TYPE = Item.extend( COMPONENT_METADATA_TYPE, BEAN_METADATA, "This type encapsulates BeanMetadata objects", CLASS_NAME_ITEM, INIT_METHOD_ITEM, DESTROY_METHOD_ITEM, FACTORY_METHOD_ITEM, FACTORY_COMPONENT_ITEM, SCOPE_ITEM, ARGUMENTS_ITEM, PROPERTIES_ITEM); /////////////////////////////////////////////////////////////// // Define <registration-listener>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key LISTENER_COMPONENT, used in {@link #LISTENER_COMPONENT_ITEM}. */ String LISTENER_COMPONENT = "ListenerComponent"; /** * The item containing the listener component. * The key is {@link #LISTENER_COMPONENT}, and the type is {@link JmxConstants#BYTE_ARRAY_TYPE}. */ Item LISTENER_COMPONENT_ITEM = new Item( LISTENER_COMPONENT, "The listener component", JmxConstants.BYTE_ARRAY_TYPE); /** * The key REGISTRATION_METHOD, used in {@link #REGISTRATION_METHOD_ITEM}. */ String REGISTRATION_METHOD = "RegistrationMethod"; /** * The item containing the name of the registration method. * The key is {@link #REGISTRATION_METHOD}, and the type is {@link SimpleType#STRING}. */ Item REGISTRATION_METHOD_ITEM = new Item( REGISTRATION_METHOD, "The name of the registration method", SimpleType.STRING); /** * The key UNREGISTRATION_METHOD, used in {@link #UNREGISTRATION_METHOD_ITEM}. */ String UNREGISTRATION_METHOD = "UnregistrationMethod"; /** * The item containing the name of the unregistration method. * The key is {@link #UNREGISTRATION_METHOD}, and the type is {@link SimpleType#STRING}. */ Item UNREGISTRATION_METHOD_ITEM = new Item( UNREGISTRATION_METHOD, "The name of the unregistration method", SimpleType.STRING); /** * The name of CompositeType for RegistrationListener objects, used in {@link #REGISTRATION_LISTENER_TYPE}. */ String REGISTRATION_LISTENER = "RegistrationListener"; /** * The CompositeType for a registration listener, and it contains the following items: * <ul> * <li>{@link #LISTENER_COMPONENT}</li> * <li>{@link #REGISTRATION_METHOD}</li> * <li>{@link #UNREGISTRATION_METHOD}</li> * </ul> */ CompositeType REGISTRATION_LISTENER_TYPE = Item.compositeType( REGISTRATION_LISTENER, "This type encapsulates RegistrationListener objects", LISTENER_COMPONENT_ITEM, REGISTRATION_METHOD_ITEM, UNREGISTRATION_METHOD_ITEM); /////////////////////////////////////////////////////////////// // Define <service>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key INTERFACES, used in {@link #INTERFACES_ITEM}. */ String INTERFACES = "Interfaces"; /** * The item containing the type names of the interfaces that the service should be advertised as supporting. * The key is {@link #INTERFACES}, and the type is {@link JmxConstants#STRING_ARRAY_TYPE}. */ Item INTERFACES_ITEM = new Item( INTERFACES, "The type names of the interfaces", JmxConstants.STRING_ARRAY_TYPE); /** * The key AUTO_EXPORT, used in {@link #AUTO_EXPORT_ITEM}. */ String AUTO_EXPORT = "AutoExport"; /** * The item containing the auto-export mode for the service. * The key is {@link #AUTO_EXPORT}, and the type is {@link SimpleType#INTEGER}. */ //TODO describe integer Item AUTO_EXPORT_ITEM = new Item( AUTO_EXPORT, "The auto-export mode for the service", SimpleType.INTEGER); /** * The key RANKING, used in {@link #RANKING_ITEM}. */ String RANKING = "Ranking"; /** * The item containing the ranking value to use when advertising the service. * The key is {@link #RANKING}, and the type is {@link SimpleType#INTEGER}. */ Item RANKING_ITEM = new Item( RANKING, "The ranking value when advertising the service", SimpleType.INTEGER); /** * The key SERVICE_COMPONENT, used in {@link #SERVICE_COMPONENT_ITEM}. */ String SERVICE_COMPONENT = "ServiceComponent"; /** * The item containing the id of the component to be exported as a service. * The key is {@link #SERVICE_COMPONENT}, and the type is {@link JmxConstants#BYTE_ARRAY_TYPE}. */ Item SERVICE_COMPONENT_ITEM = new Item( SERVICE_COMPONENT, "The component to be exported as a service", JmxConstants.BYTE_ARRAY_TYPE); /** * The key SERVICE_PROPERTIES, used in {@link #SERVICE_PROPERTIES_ITEM}. */ String SERVICE_PROPERTIES = "ServiceProperties"; /** * The item containing the user declared properties to be advertised with the service. * The key is {@link #SERVICE_COMPONENT}, and the type is {@link SimpleType#STRING}. */ Item SERVICE_PROPERTIES_ITEM = new Item( SERVICE_PROPERTIES, "The user declared properties to be advertised with the service", Item.arrayType(1, MAP_ENTRY_TYPE)); /** * The key REGISTRATION_LISTENERS, used in {@link #REGISTRATION_LISTENERS_ITEM}. */ String REGISTRATION_LISTENERS = "RegistrationListeners"; /** * The item containing all the registration listeners. * The key is {@link #REGISTRATION_LISTENERS}, and the type is {@link ArrayType}. */ Item REGISTRATION_LISTENERS_ITEM = new Item( REGISTRATION_LISTENERS, "All the registration listeners", Item.arrayType(1, REGISTRATION_LISTENER_TYPE)); /** * The name of CompositeType for ServiceMetadata objects, used in {@link #SERVICE_METADATA_TYPE}. */ String SERVICE_METADATA = "ServiceMetadata"; /** * The CompositeType for a ServiceMetadata object, it extends {@link #COMPONENT_METADATA_TYPE} * and adds the following items: * <ul> * <li>{@link #INTERFACES}</li> * <li>{@link #AUTO_EXPORT}</li> * <li>{@link #RANKING}</li> * <li>{@link #SERVICE_COMPONENT}</li> * <li>{@link #SERVICE_PROPERTIES}</li> * <li>{@link #REGISTRATION_LISTENERS}</li> * </ul> */ CompositeType SERVICE_METADATA_TYPE = Item.extend( COMPONENT_METADATA_TYPE, SERVICE_METADATA, "This type encapsulates ServiceMetadata objects", INTERFACES_ITEM, AUTO_EXPORT_ITEM, RANKING_ITEM, SERVICE_COMPONENT_ITEM, SERVICE_PROPERTIES_ITEM, REGISTRATION_LISTENERS_ITEM); /////////////////////////////////////////////////////////////// // Define <reference-listener>'s CompositeType // LISTENER_COMPONENT_ITEM defined in the <registration-listener> /////////////////////////////////////////////////////////////// /** * The key BIND_METHOD, used in {@link #BIND_METHOD_ITEM}. */ String BIND_METHOD = "BindMethod"; /** * The item containing the name of the bind method. * The key is {@link #BIND_METHOD}, and the type is {@link SimpleType#STRING}. */ Item BIND_METHOD_ITEM = new Item( BIND_METHOD, "The name of the bind method", SimpleType.STRING); /** * The key UNBIND_METHOD, used in {@link #UNBIND_METHOD_ITEM}. */ String UNBIND_METHOD = "UnbindMethod"; /** * The item containing the name of the unbind method. * The key is {@link #UNBIND_METHOD}, and the type is {@link SimpleType#STRING}. */ Item UNBIND_METHOD_ITEM = new Item( UNBIND_METHOD, "The name of the unbind method", SimpleType.STRING); /** * The name of CompositeType for ReferenceListener objects, used in {@link #REFERENCE_LISTENER_TYPE}. */ String REFERENCE_LISTENER = "ReferenceListener"; /** * The CompositeType for a reference listener, and it contains the following items: * <ul> * <li>{@link #LISTENER_COMPONENT}</li> * <li>{@link #BIND_METHOD}</li> * <li>{@link #UNBIND_METHOD}</li> * </ul> */ CompositeType REFERENCE_LISTENER_TYPE = Item.compositeType( REFERENCE_LISTENER, "This type encapsulates ReferenceListener objects", LISTENER_COMPONENT_ITEM, BIND_METHOD_ITEM, UNBIND_METHOD_ITEM); /////////////////////////////////////////////////////////////// // Define Service Reference's CompositeType, // <reference> & <reference-list> will extend this /////////////////////////////////////////////////////////////// /** * The key AVAILABILITY, used in {@link #AVAILABILITY_ITEM}. */ String AVAILABILITY = "Availability"; /** * The item specify whether or not a matching service is required at all times. * The key is {@link #AVAILABILITY}, and the type is {@link SimpleType#INTEGER}. * */ //TODO add description for each int Item AVAILABILITY_ITEM = new Item( AVAILABILITY, "To specify whether or not a matching service is required at all times", SimpleType.INTEGER); /** * The key INTERFACE, used in {@link #INTERFACE_ITEM}. */ String INTERFACE = "Interface"; /** * The item containing the name of the interface type that a matching service must support. * The key is {@link #INTERFACE}, and the type is {@link SimpleType#STRING}. */ Item INTERFACE_ITEM = new Item( INTERFACE, "the name of the interface type", SimpleType.STRING); /** * The key COMPONENT_NAME, used in {@link #COMPONENT_NAME_ITEM}. */ String COMPONENT_NAME = "ComponentName"; /** * The item containing the value of the <code>component-name</code> attribute of the service reference. * The key is {@link #INTERFACE}, and the type is {@link SimpleType#STRING}. */ Item COMPONENT_NAME_ITEM = new Item( COMPONENT_NAME, "The value of the component-name attribute of the service reference", SimpleType.STRING); /** * The key FILTER, used in {@link #FILTER_ITEM}. */ String FILTER = "Filter"; /** * The item containing the filter expression that a matching service must match. * The key is {@link #FILTER}, and the type is {@link SimpleType#STRING}. */ Item FILTER_ITEM = new Item( FILTER, "The filter expression that a matching service must match", SimpleType.STRING); /** * The key REFERENCE_LISTENERS, used in {@link #REFERENCE_LISTENERS_ITEM}. */ String REFERENCE_LISTENERS = "ReferenceListeners"; /** * The item containing all the reference listeners. * The key is {@link #REFERENCE_LISTENERS}, and the type is {@link ArrayType}. */ Item REFERENCE_LISTENERS_ITEM= new Item( REFERENCE_LISTENERS, "All the reference listeners", Item.arrayType(1, REFERENCE_LISTENER_TYPE)); /** * The name of CompositeType for ServiceReferenceMetadata objects, used in {@link #SERVICE_REFERENCE_METADATA_TYPE}. */ String SERVICE_REFERENCE_METADATA = "ServiceReferenceMetadata"; /** * The CompositeType for a ServiceReferenceMetadata object, it extends * {@link #COMPONENT_METADATA_TYPE} and adds the following items: * <ul> * <li>{@link #AVAILABILITY}</li> * <li>{@link #INTERFACE}</li> * <li>{@link #COMPONENT_NAME}</li> * <li>{@link #FILTER}</li> * <li>{@link #REFERENCE_LISTENERS}</li> * </ul> */ CompositeType SERVICE_REFERENCE_METADATA_TYPE = Item.extend( COMPONENT_METADATA_TYPE, SERVICE_REFERENCE_METADATA, "This type encapsulates ServiceReferenceMetadata objects", AVAILABILITY_ITEM, INTERFACE_ITEM, COMPONENT_NAME_ITEM, FILTER_ITEM, REFERENCE_LISTENERS_ITEM); /////////////////////////////////////////////////////////////// // Define <reference>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key TIME_OUT, used in {@link #TIMEOUT_ITEM}. */ String TIMEOUT = "TimeOut"; /** * The item containing the timeout for service invocations when a backing service is is unavailable. * The key is {@link #TIMEOUT}, and the type is {@link SimpleType#LONG}. */ Item TIMEOUT_ITEM = new Item( TIMEOUT, "The timeout for service invocations when a backing service is is unavailable", SimpleType.LONG); /** * The name of CompositeType for ReferenceMetadata objects, used in {@link #REFERENCE_METADATA_TYPE}. */ String REFERENCE_METADATA = "ReferenceMetadata"; /** * The CompositeType for a ReferenceMetadata object, it extends * {@link #SERVICE_REFERENCE_METADATA_TYPE} and adds the following items: * <ul> * <li>{@link #TIMEOUT}</li> * </ul> */ CompositeType REFERENCE_METADATA_TYPE = Item.extend( SERVICE_REFERENCE_METADATA_TYPE, REFERENCE_METADATA, "This type encapsulates ReferenceMetadata objects", TIMEOUT_ITEM); /////////////////////////////////////////////////////////////// // Define <reference-list>'s CompositeType /////////////////////////////////////////////////////////////// /** * The key MEMBER_TYPE, used in {@link #MEMBER_TYPE_ITEM}. */ String MEMBER_TYPE = "MemberType"; /** * The item specify whether the List will contain service object proxies or ServiceReference objects. * The key is {@link #MEMBER_TYPE}, and the type is {@link SimpleType#INTEGER}. */ Item MEMBER_TYPE_ITEM = new Item( MEMBER_TYPE, "To specify whether the List will contain service object proxies or ServiceReference objects", SimpleType.INTEGER); /** * The name of CompositeType for ReferenceListMetadata objects, used in {@link #REFERENCE_LIST_METADATA_TYPE}. */ String REFERENCE_LIST_METADATA = "ReferenceListMetadata"; /** * The CompositeType for a ReferenceListMetadata object, it extends * {@link #SERVICE_REFERENCE_METADATA_TYPE} and adds the following items: * <ul> * <li>{@link #MEMBER_TYPE}</li> * </ul> */ CompositeType REFERENCE_LIST_METADATA_TYPE = Item.extend( SERVICE_REFERENCE_METADATA_TYPE, REFERENCE_LIST_METADATA, "This type encapsulates ReferenceListMetadata objects", MEMBER_TYPE_ITEM); /** * Returns the list of component id. * * @param containerServiceId The blueprint container service id * @return the array of component id * @throws IOException if the operation fails */ String[] getComponentIds(long containerServiceId) throws IOException; /** * Returns all component ids of the specified component type * * @param containerServiceId The blueprint container service id * @param type The string used to specify the type of component * @return the array of component id * @throws IOException if the operation fails */ String[] getComponentIdsByType(long containerServiceId, String type) throws IOException; /** * Returns the ComponentMetadata according to the its component id. * The returned Composite Data's type is actually one of {@link #BEAN_METADATA_TYPE}, * {@link #SERVICE_METADATA_TYPE}, {@link #REFERENCE_METADATA_TYPE}, REFERENCE_LIST_METADATA_TYPE. * * @param containerServiceId The blueprint container service id * @param componentId The component id * @return the ComponentMetadata * @throws IOException if the operation fails */ CompositeData getComponentMetadata(long containerServiceId, String componentId) throws IOException; /** * Returns all the blueprint containers' service IDs, which successfully * created from blueprint bundles. * * @return the list of all the service IDs of the blueprint containers created by current extender * @throws IOException if the operation fails */ long[] getBlueprintContainerServiceIds() throws IOException; /** * Returns the blueprint container's service id if the bundle specified * by the bundle id is a blueprint bundle. * * @param bundleId The bundle id of a blueprint bundle * @return the blueprint container's service id, or null if the blueprint bundle initialed failed. * @throws IOException if the operation fails * @throws IllegalArgumentException if the bundle is not a blueprint bundle */ long getBlueprintContainerServiceId(long bundleId) throws IOException; }
7,972
0
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx/blueprint/JmxConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.blueprint; import javax.management.openmbean.ArrayType; import javax.management.openmbean.SimpleType; /** * Constants. * * Additionally, this class contains a number of utility types that are used in * different places in the specification. These are {@link #BYTE_ARRAY_TYPE}, * and {@link #STRING_ARRAY_TYPE}. * * Immutable */ public class JmxConstants { /* * Empty constructor to make sure this is not used as an object. */ private JmxConstants() { // empty } public static final ArrayType<Byte> BYTE_ARRAY_TYPE = Item .arrayType( 1, SimpleType.BYTE); /** * The MBean Open type for an array of strings */ public static final ArrayType<String> STRING_ARRAY_TYPE = Item .arrayType( 1, SimpleType.STRING); /** * The domain name of the Blueprint MBeans */ public static final String ARIES_BLUEPRINT = "org.apache.aries.blueprint"; }
7,973
0
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx/blueprint/BlueprintStateMBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.blueprint; import java.io.IOException; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularType; /** * This MBean provides the management interface to the OSGi Blueprint Service. * * This MBean also emits events that clients can use to get notified of the * changes in the blueprint containers state in the framework. * * @version $Revision$ */ public interface BlueprintStateMBean { /** * The object name for this MBean. */ String OBJECTNAME = JmxConstants.ARIES_BLUEPRINT+":service=blueprintState,version=1.0"; /////////////////////////////////////////////////////////////// // Define Event's CompositeType /////////////////////////////////////////////////////////////// /** * The key BUNDLE_ID, used in {@link #BUNDLE_ID_ITEM}. */ String BUNDLE_ID = "BundleId"; /** * The item containing the Blueprint bundle id associated with this event. * The key is {@link #BUNDLE_ID}, and the type is {@link SimpleType#LONG}. */ Item BUNDLE_ID_ITEM = new Item( BUNDLE_ID, "the Blueprint bundle id associated with this event.", SimpleType.LONG); /** * The key EXTENDER_BUNDLE_ID, used in {@link #EXTENDER_BUNDLE_ID_ITEM}. */ String EXTENDER_BUNDLE_ID = "ExtenderBundleId"; /** * The item containing the Blueprint extender bundle id that is generating this event. * The key is {@link #EXTENDER_BUNDLE_ID}, and the type is {@link SimpleType#LONG}. */ Item EXTENDER_BUNDLE_ID_ITEM = new Item( EXTENDER_BUNDLE_ID, "the Blueprint extender bundle id that is generating this event.", SimpleType.LONG); /** * The key REPLAY, used in {@link #REPLAY_ITEM}. */ String REPLAY = "Replay"; /** * The item containing the flag that represents whether this event is a replay event. * The key is {@link #REPLAY}, and the type is {@link SimpleType#BOOLEAN}. */ Item REPLAY_ITEM = new Item( REPLAY, "the flag that represents whether this event is a replay event.", SimpleType.BOOLEAN); /** * The key EVENT_TYPE, used in {@link #EVENT_TYPE_ITEM}. */ String EVENT_TYPE = "EventType"; /** * The item containing the type of this event. * The key is {@link #EVENT_TYPE}, and the type is {@link SimpleType#STRING}. */ Item EVENT_TYPE_ITEM = new Item( EVENT_TYPE, "The type of the event: {CREATING=1, CREATED=2, DESTROYING=3, DESTROYED=4, FAILURE=5, GRACE_PERIOD=6, WAITING=7}", SimpleType.INTEGER); /** * The key TIMESTAMP, used in {@link #TIMESTAMP_ITEM}. */ String TIMESTAMP = "Timestamp"; /** * The item containing the time at which this event was created. * The key is {@link #TIMESTAMP}, and the type is {@link SimpleType#LONG}. */ Item TIMESTAMP_ITEM = new Item( TIMESTAMP, "the time at which this event was created.", SimpleType.LONG); /** * The key DEPENDENCIES, used in {@link #DEPENDENCIES_ITEM}. */ String DEPENDENCIES = "Dependencies"; /** * The item containing the filters identifying the missing dependencies that caused the WAITING, GRACE_PERIOD or FAILURE event. * The key is {@link #DEPENDENCIES}, and the type is {@link JmxConstants#STRING_ARRAY_TYPE}. */ Item DEPENDENCIES_ITEM = new Item( DEPENDENCIES, "the filters identifying the missing dependencies that caused the WAITING, GRACE_PERIOD or FAILURE event.", JmxConstants.STRING_ARRAY_TYPE); /** * The key EXCEPTION_MESSAGE, used in {@link #EXCEPTION_MESSAGE_ITEM}. */ String EXCEPTION_MESSAGE = "ExceptionMessage"; /** * The item containing the exception message that cause this FAILURE event. * The key is {@link #EXCEPTION_MESSAGE}, and the type is {@link SimpleType#STRING}. */ Item EXCEPTION_MESSAGE_ITEM = new Item( EXCEPTION_MESSAGE, "the exception message that cause this FAILURE event.", SimpleType.STRING); /** * The CompositeType for a blueprint event. It contains the following items: * <ul> * <li>{@link #BUNDLE_ID}</li> * <li>{@link #EXTENDER_BUNDLE_ID}</li> * <li>{@link #EVENT_TYPE}</li> * <li>{@link #REPLAY}</li> * <li>{@link #TIMESTAMP}</li> * <li>{@link #DEPENDENCIES}</li> * <li>{@link #EXCEPTION_MESSAGE}</li> * </ul> */ CompositeType OSGI_BLUEPRINT_EVENT_TYPE = Item.compositeType( "OSGI_BLUEPRINT_EVENT", "Blueprint event", BUNDLE_ID_ITEM, EXTENDER_BUNDLE_ID_ITEM, EVENT_TYPE_ITEM, REPLAY_ITEM, TIMESTAMP_ITEM, DEPENDENCIES_ITEM, EXCEPTION_MESSAGE_ITEM); /** * The Tabular Type for A list of blueprint events. The row type is * {@link #OSGI_BLUEPRINT_EVENT_TYPE}. */ TabularType OSGI_BLUEPRINT_EVENTS_TYPE = Item.tabularType( "BUNDLES", "A list of blueprint events", OSGI_BLUEPRINT_EVENT_TYPE, new String[] { BUNDLE_ID }); /** * Returns the BlueprintEvent associated with this blueprint container. * The returned Composite Data is typed by {@link #OSGI_BLUEPRINT_EVENT_TYPE}. * * @param bundleId The bundle id of a blueprint bundle * @return the last event associated with the blueprint bundle, see {@link #OSGI_BLUEPRINT_EVENT_TYPE} * @throws IOException if the operation fails * @throws IllegalArgumentException if the bundle is not a blueprint bundle */ public CompositeData getLastEvent(long bundleId) throws IOException; /** * Returns all the last events associated with the blueprint bundles. * * @return the tabular representation of all the last events associated with the blueprint bundles see {@link #OSGI_BLUEPRINT_EVENTS_TYPE} * @throws IOException if the operation fails */ public TabularData getLastEvents() throws IOException; /** * Returns all the blueprint bundles' IDs, which are either * successfully created or not by current extender. * * @return the list of all the blueprint bundles's IDs (either successfully created or not by current extender) * @throws IOException if the operation fails */ public long[] getBlueprintBundleIds() throws IOException; }
7,974
0
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-blueprint-api/src/main/java/org/apache/aries/jmx/blueprint/Item.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.blueprint; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import javax.management.openmbean.ArrayType; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenType; import javax.management.openmbean.TabularType; /** * The item class enables the definition of open types in the appropriate interfaces. * * This class contains a number of methods that make it possible to create open types for {@link CompositeType}, * {@link TabularType}, and {@link ArrayType}. The normal creation throws a checked exception, making it impossible to * use them in a static initializer. They constructors are also not very suitable for static construction. * * * An Item instance describes an item in a Composite Type. It groups the triplet of name, description, and Open Type. * These Item instances allows the definitions of an item to stay together. * * Immutable */ public class Item { /** * The name of this item. */ private final String name; /** * The description of this item. */ private final String description; /** * The type of this item. */ private final OpenType/*<?>*/ type; /** * Create a triple of name, description, and type. This triplet is used in the creation of a Composite Type. * * @param name * The name of the item. * @param description * The description of the item. * @param type * The Open Type of this item. * @param restrictions * Ignored, contains list of restrictions */ public Item(String name, String description, OpenType/*<?>*/ type, String... restrictions) { this.name = name; this.description = description; this.type = type; } /** * Create a Tabular Type. * * @param name * The name of the Tabular Type. * @param description * The description of the Tabular Type. * @param rowType * The Open Type for a row * @param index * The names of the items that form the index . * @return A new Tabular Type composed from the parameters. * @throws RuntimeException * when the Tabular Type throws an OpenDataException */ static public TabularType tabularType(String name, String description, CompositeType rowType, String... index) { try { return new TabularType(name, description, rowType, index); } catch (OpenDataException e) { throw new RuntimeException(e); } } /** * Create a Composite Type * * @param name * The name of the Tabular Type. * @param description * The description of the Tabular Type. * @param items * The items that describe the composite type. * @return a new Composite Type * @throws RuntimeException * when the Tabular Type throws an OpenDataException */ static public CompositeType compositeType(String name, String description, Item... items) { return extend(null, name, description, items); } /** * Extend a Composite Type by adding new items. Items can override items in the parent type. * * @param parent * The parent type, can be <code>null</code> * @param name * The name of the type * @param description * The description of the type * @param items * The items that should be added/override to the parent type * @return A new Composite Type that extends the parent type * @throws RuntimeException * when an OpenDataException is thrown */ public static CompositeType extend(CompositeType parent, String name, String description, Item... items) { Set<Item> all = new LinkedHashSet<Item>(); if (parent != null) { for (Object nm : parent.keySet()) { String key = (String) nm; all.add(new Item((String) nm, parent.getDescription(key), parent.getType(key))); } } all.addAll(Arrays.asList(items)); String names[] = new String[all.size()]; String descriptions[] = new String[all.size()]; OpenType types[] = new OpenType[all.size()]; int n = 0; for (Item item : all) { names[n] = item.name; descriptions[n] = item.description; types[n] = item.type; n++; } try { return new CompositeType(name, description, names, descriptions, types); } catch (OpenDataException e) { throw new RuntimeException(e); } } /** * Return a new Array Type. * * @param dim * The dimension * @param elementType * The element type * @return A new Array Type */ public static <T> ArrayType<T> arrayType(int dim, OpenType<T> elementType) { try { return new ArrayType<T>(dim, elementType); } catch (OpenDataException e) { throw new RuntimeException(e); } } /** * Return a new primaArray Type. * * @param elementType * The element type * @return A new Array Type */ /* * For the compatibility with java 5, we have to cancel this method temporarily. * * public static ArrayType<?> primitiveArrayType(SimpleType<?> elementType) { try { return new ArrayType(elementType, true); } catch (OpenDataException e) { throw new RuntimeException(e); } } */ }
7,975
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/MBeanHolderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard; import java.lang.reflect.Field; import java.util.Map; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class MBeanHolderTest { @Test public void testPlainRegistration() throws Exception { MBeanHolder mbh = new MBeanHolder(new Object(), new ObjectName("foo:bar=123")); Map<?,?> registrations = (Map<?,?>) getPrivateField(mbh, "registrations"); Logger ml = Mockito.mock(Logger.class); setPrivateField(mbh, "log", ml); MBeanServer ms = mockMBeanServer(); assertEquals(0, registrations.size()); mbh.register(ms, new String [] {}); assertEquals(1, registrations.size()); assertEquals(new ObjectName("foo:bar=123"), registrations.get(ms)); Mockito.verify(ml, Mockito.never()).error(Mockito.anyString(), Mockito.isA(Throwable.class)); } @Test public void testRegistrationException() throws Exception { MBeanHolder mbh = new MBeanHolder(new Object(), new ObjectName("foo:bar=123")); Map<?,?> registrations = (Map<?,?>) getPrivateField(mbh, "registrations"); Logger ml = Mockito.mock(Logger.class); setPrivateField(mbh, "log", ml); MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.eq(new ObjectName("foo:bar=123")))). thenThrow(new InstanceAlreadyExistsException()); assertEquals(0, registrations.size()); mbh.register(ms, new String [] {}); assertEquals(0, registrations.size()); Mockito.verify(ml, Mockito.times(1)).error(Mockito.anyString(), Mockito.isA(InstanceAlreadyExistsException.class)); } @Test public void testExceptionsAsWarnings() throws Exception { MBeanHolder mbh = new MBeanHolder(new Object(), new ObjectName("foo:bar=123")); Map<?,?> registrations = (Map<?,?>) getPrivateField(mbh, "registrations"); Logger ml = Mockito.mock(Logger.class); setPrivateField(mbh, "log", ml); MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.eq(new ObjectName("foo:bar=123")))). thenThrow(new InstanceAlreadyExistsException()); assertEquals(0, registrations.size()); mbh.register(ms, new String [] {InstanceAlreadyExistsException.class.getName()}); assertEquals(0, registrations.size()); Mockito.verify(ml, Mockito.times(1)).warn(Mockito.anyString(), Mockito.isA(InstanceAlreadyExistsException.class)); } @Test public void testExceptionsAsWarnings2() throws Exception { MBeanHolder mbh = new MBeanHolder(new Object(), new ObjectName("foo:bar=123")); Map<?,?> registrations = (Map<?,?>) getPrivateField(mbh, "registrations"); Logger ml = Mockito.mock(Logger.class); setPrivateField(mbh, "log", ml); MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.eq(new ObjectName("foo:bar=123")))). thenThrow(new NullPointerException()); assertEquals(0, registrations.size()); mbh.register(ms, new String [] {InstanceAlreadyExistsException.class.getName(), NullPointerException.class.getName()}); assertEquals(0, registrations.size()); Mockito.verify(ml, Mockito.times(1)).warn(Mockito.anyString(), Mockito.isA(NullPointerException.class)); } @Test public void testThrowRuntimeException() throws Exception { MBeanHolder mbh = new MBeanHolder(new Object(), new ObjectName("foo:bar=123")); Map<?,?> registrations = (Map<?,?>) getPrivateField(mbh, "registrations"); Logger ml = Mockito.mock(Logger.class); setPrivateField(mbh, "log", ml); MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.eq(new ObjectName("foo:bar=123")))). thenThrow(new NullPointerException()); assertEquals(0, registrations.size()); try { mbh.register(ms, new String [] {}); fail("Should have thrown a NullPointerException"); } catch (NullPointerException npe) { // good! } } private MBeanServer mockMBeanServer() throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.isA(ObjectName.class))).then( new Answer<ObjectInstance>() { @Override public ObjectInstance answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return new ObjectInstance(((ObjectName) args[1]).toString(), args[0].getClass().getName()); } }); return ms; } private Object getPrivateField(Object obj, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); return field.get(obj); } private void setPrivateField(Object obj, String name, Object val) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); field.set(obj, val); } }
7,976
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/JmxWhiteboardSupportTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard; import java.lang.reflect.Field; import java.util.Dictionary; import java.util.Hashtable; import javax.management.DynamicMBean; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.junit.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; public class JmxWhiteboardSupportTest { @Test public void testRegisterMBean() throws Exception { final Logger ml = Mockito.mock(Logger.class); JmxWhiteboardSupport s = new JmxWhiteboardSupport() { @Override MBeanHolder createMBeanHolder(Object mbean, ObjectName objectName) { MBeanHolder mbh = super.createMBeanHolder(mbean, objectName); setPrivateField(mbh, "log", ml); return mbh; } }; final Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("jmx.objectname", "test:key=val"); ServiceReference<?> sref = Mockito.mock(ServiceReference.class); Mockito.when(sref.getProperty(Mockito.anyString())).then(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return props.get(invocation.getArguments()[0].toString()); } }); MBeanServer ms = mockMBeanServer(); s.addMBeanServer(ms); Mockito.verify(ml, Mockito.never()).error(Mockito.anyString(), Mockito.isA(Throwable.class)); Mockito.verify(ml, Mockito.never()).warn(Mockito.anyString(), Mockito.isA(Throwable.class)); s.registerMBean(Mockito.mock(DynamicMBean.class), sref); Mockito.verify(ml, Mockito.never()).error(Mockito.anyString(), Mockito.isA(Throwable.class)); Mockito.verify(ml, Mockito.never()).warn(Mockito.anyString(), Mockito.isA(Throwable.class)); } @Test public void testRegisterMBeanError() throws Exception { final Logger ml = Mockito.mock(Logger.class); JmxWhiteboardSupport s = new JmxWhiteboardSupport() { @Override MBeanHolder createMBeanHolder(Object mbean, ObjectName objectName) { MBeanHolder mbh = super.createMBeanHolder(mbean, objectName); setPrivateField(mbh, "log", ml); return mbh; } }; final Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("jmx.objectname", "test:key=val"); ServiceReference<?> sref = Mockito.mock(ServiceReference.class); Mockito.when(sref.getProperty(Mockito.anyString())).then(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return props.get(invocation.getArguments()[0].toString()); } }); MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.eq(new ObjectName("test:key=val")))). thenThrow(new InstanceAlreadyExistsException()); s.addMBeanServer(ms); Mockito.verify(ml, Mockito.never()).error(Mockito.anyString(), Mockito.isA(Throwable.class)); Mockito.verify(ml, Mockito.never()).warn(Mockito.anyString(), Mockito.isA(Throwable.class)); s.registerMBean(Mockito.mock(DynamicMBean.class), sref); Mockito.verify(ml, Mockito.times(1)).error(Mockito.anyString(), Mockito.isA(Throwable.class)); Mockito.verify(ml, Mockito.never()).warn(Mockito.anyString(), Mockito.isA(Throwable.class)); } @Test public void testRegisterMBeanWarning() throws Exception { final Logger ml = Mockito.mock(Logger.class); JmxWhiteboardSupport s = new JmxWhiteboardSupport() { @Override MBeanHolder createMBeanHolder(Object mbean, ObjectName objectName) { MBeanHolder mbh = super.createMBeanHolder(mbean, objectName); setPrivateField(mbh, "log", ml); return mbh; } }; final Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("jmx.objectname", "test:key=val"); props.put("warning.exceptions", new String [] {InstanceAlreadyExistsException.class.getName(), MBeanRegistrationException.class.getName()}); ServiceReference<?> sref = Mockito.mock(ServiceReference.class); Mockito.when(sref.getProperty(Mockito.anyString())).then(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return props.get(invocation.getArguments()[0].toString()); } }); MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.eq(new ObjectName("test:key=val")))). thenThrow(new InstanceAlreadyExistsException()); s.addMBeanServer(ms); Mockito.verify(ml, Mockito.never()).error(Mockito.anyString(), Mockito.isA(Throwable.class)); Mockito.verify(ml, Mockito.never()).warn(Mockito.anyString(), Mockito.isA(Throwable.class)); s.registerMBean(Mockito.mock(DynamicMBean.class), sref); Mockito.verify(ml, Mockito.never()).error(Mockito.anyString(), Mockito.isA(Throwable.class)); Mockito.verify(ml, Mockito.times(1)).warn(Mockito.anyString(), Mockito.isA(Throwable.class)); } private MBeanServer mockMBeanServer() throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { MBeanServer ms = Mockito.mock(MBeanServer.class); Mockito.when(ms.registerMBean(Mockito.any(), Mockito.isA(ObjectName.class))).then( new Answer<ObjectInstance>() { @Override public ObjectInstance answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return new ObjectInstance(((ObjectName) args[1]).toString(), args[0].getClass().getName()); } }); return ms; } private void setPrivateField(Object obj, String name, Object val) { try { Field field = obj.getClass().getDeclaredField(name); field.setAccessible(true); field.set(obj, val); } catch (Exception e) { throw new RuntimeException(e); } } }
7,977
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/MBeanServerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration; import javax.management.MBeanServer; import javax.management.ObjectName; import junit.framework.TestCase; import org.apache.aries.jmx.whiteboard.integration.helper.IntegrationTestBase; import org.apache.aries.jmx.whiteboard.integration.helper.TestClass; import org.apache.aries.jmx.whiteboard.integration.helper.TestClassMBean; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.ServiceRegistration; /** * The <code>MBeanTest</code> tests MBean registration with MBean Servers */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class MBeanServerTest extends IntegrationTestBase { @Test public void test_MServerBean() throws Exception { final String instanceName = "simple.test.instance"; final String objectNameString = "domain:instance=" + instanceName; final ObjectName objectName = new ObjectName(objectNameString); final TestClass testInstance = new TestClass(instanceName); // get or create the dynamic MBean Server final MBeanServer server = getOrCreateMBeanServer(); // MBean server not registered as service, unknown object assertNotRegistered(server, objectName); // expect the MBean to be registered with the static server final ServiceRegistration mBeanReg = registerService( TestClassMBean.class.getName(), testInstance, objectNameString); // MBean server not registered, expect object to not be known assertNotRegistered(server, objectName); // register MBean server, expect MBean registered ServiceRegistration mBeanServerReg = registerMBeanServer(server); assertRegistered(server, objectName); // expect MBean to return expected value TestCase.assertEquals(instanceName, server.getAttribute(objectName, "InstanceName")); // unregister MBean server, expect MBean to be unregistered mBeanServerReg.unregister(); assertNotRegistered(server, objectName); // unregister MBean, expect to not be registered any more mBeanReg.unregister(); assertNotRegistered(server, objectName); } }
7,978
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/MBeanTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration; import javax.management.DynamicMBean; import javax.management.MBeanServer; import javax.management.ObjectName; import junit.framework.TestCase; import org.apache.aries.jmx.whiteboard.integration.helper.IntegrationTestBase; import org.apache.aries.jmx.whiteboard.integration.helper.TestClass; import org.apache.aries.jmx.whiteboard.integration.helper.TestClassMBean; import org.apache.aries.jmx.whiteboard.integration.helper.TestStandardMBean; import org.apache.aries.jmx.whiteboard.integration.helper2.TestClass2; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.ServiceRegistration; /** * The <code>MBeanTest</code> tests MBean registration with MBean Servers */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class MBeanTest extends IntegrationTestBase { @Test public void test_simple_MBean() throws Exception { final String instanceName = "simple.test.instance"; final String objectNameString = "domain:instance=" + instanceName; final ObjectName objectName = new ObjectName(objectNameString); final TestClass testInstance = new TestClass(instanceName); final MBeanServer server = getStaticMBeanServer(); // expect MBean to not be registered yet assertNotRegistered(server, objectName); // expect the MBean to be registered with the static server final ServiceRegistration reg = registerService( TestClassMBean.class.getName(), testInstance, objectNameString); assertRegistered(server, objectName); // expect MBean to return expected value TestCase.assertEquals(instanceName, server.getAttribute(objectName, "InstanceName")); // unregister MBean, expect to not be registered any more reg.unregister(); assertNotRegistered(server, objectName); } @Test public void test_simple_MBean_different_package() throws Exception { final String instanceName = "simple.test.instance.2"; final String objectNameString = "domain:instance=" + instanceName; final ObjectName objectName = new ObjectName(objectNameString); final TestClass testInstance = new TestClass2(instanceName); final MBeanServer server = getStaticMBeanServer(); // expect MBean to not be registered yet assertNotRegistered(server, objectName); // expect the MBean to be registered with the static server final ServiceRegistration reg = registerService( TestClassMBean.class.getName(), testInstance, objectNameString); assertRegistered(server, objectName); // expect MBean to return expected value TestCase.assertEquals(instanceName, server.getAttribute(objectName, "InstanceName")); // unregister MBean, expect to not be registered any more reg.unregister(); assertNotRegistered(server, objectName); } @Test public void test_StandardMBean() throws Exception { final String instanceName = "standard.test.instance"; final String objectNameString = "domain:instance=" + instanceName; final ObjectName objectName = new ObjectName(objectNameString); final TestStandardMBean testInstance = new TestStandardMBean( instanceName); final MBeanServer server = getStaticMBeanServer(); // expect MBean to not be registered yet assertNotRegistered(server, objectName); // expect the MBean to be registered with the static server final ServiceRegistration reg = registerService( DynamicMBean.class.getName(), testInstance, objectNameString); assertRegistered(server, objectName); // expect MBean to return expected value TestCase.assertEquals(instanceName, server.getAttribute(objectName, "InstanceName")); // unregister MBean, expect to not be registered any more reg.unregister(); assertNotRegistered(server, objectName); } }
7,979
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/helper2/TestClass2.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration.helper2; import org.apache.aries.jmx.whiteboard.integration.helper.TestClass; /** * The <code>TestClass2</code> is a simple class which will be registered as a * Simple MBean implementing the {@link TestClassMBean} interface. */ public class TestClass2 extends TestClass { public TestClass2() { this(null); } public TestClass2(final String name) { super(name); } }
7,980
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/helper/TestStandardMBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration.helper; import javax.management.NotCompliantMBeanException; import javax.management.StandardMBean; public class TestStandardMBean extends StandardMBean implements TestClassMBean { private final String instanceName; protected TestStandardMBean() throws NotCompliantMBeanException { this(null); } public TestStandardMBean(final String name) throws NotCompliantMBeanException { super(TestClassMBean.class); this.instanceName = (name == null) ? getClass().getName() : name; } public String getInstanceName() { return instanceName; } }
7,981
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/helper/TestClass.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration.helper; /** * The <code>TestClass</code> is a simple class which will be registered as a * Simple MBean implementing the {@link TestClassMBean} interface. */ public class TestClass implements TestClassMBean { private final String instanceName; public TestClass() { this(null); } public TestClass(final String name) { this.instanceName = (name == null) ? getClass().getName() : name; } public String getInstanceName() { return instanceName; } }
7,982
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/helper/TestClassMBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration.helper; /** * The <code>TestClassMBean</code> is the simple MBean interface for the * {@link TestClass} class. */ public interface TestClassMBean { String getInstanceName(); }
7,983
0
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration
Create_ds/aries/jmx/jmx-whiteboard/src/test/java/org/apache/aries/jmx/whiteboard/integration/helper/IntegrationTestBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard.integration.helper; import static org.ops4j.pax.exam.CoreOptions.*; import static org.ops4j.pax.exam.OptionUtils.combine; import java.io.File; import java.util.Dictionary; import java.util.Hashtable; import javax.inject.Inject; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectInstance; import javax.management.ObjectName; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class IntegrationTestBase { // the name of the system property providing the bundle file to be installed // and tested protected static final String BUNDLE_JAR_SYS_PROP = "project.bundle.file"; // the default bundle jar file name protected static final String BUNDLE_JAR_DEFAULT = "target/jmx-whiteboard.jar"; // the JVM option to set to enable remote debugging protected static final String DEBUG_VM_OPTION = "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=30303"; private static MBeanServer staticServer; private MBeanServer server; @Inject protected BundleContext bundleContext; private ServiceRegistration staticServerRegistration; protected static final String PROP_NAME = "theValue"; protected static final Dictionary<String, String> theConfig; static { theConfig = new Hashtable<String, String>(); theConfig.put(PROP_NAME, PROP_NAME); } @Configuration public static Option[] configuration() { final String bundleFileName = System.getProperty(BUNDLE_JAR_SYS_PROP, BUNDLE_JAR_DEFAULT); final File bundleFile = new File(bundleFileName); if (!bundleFile.canRead()) { throw new IllegalArgumentException("Cannot read from bundle file " + bundleFileName + " specified in the " + BUNDLE_JAR_SYS_PROP + " system property"); } final Option[] options = options( systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), junitBundles(), bundle(bundleFile.toURI().toString()), mavenBundle("org.ops4j.pax.tinybundles", "tinybundles", "2.0.0"), mavenBundle("org.apache.felix", "org.apache.felix.configadmin", "1.2.8"), mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.7.2"), mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.7.2")); return options; } @Before public void setUp() { staticServerRegistration = registerMBeanServer(getStaticMBeanServer()); } @After public void tearDown() { staticServerRegistration.unregister(); } protected MBeanServer getStaticMBeanServer() { if (staticServer == null) { staticServer = MBeanServerFactory.createMBeanServer("StaticServerDomain"); } return staticServer; } protected MBeanServer getMBeanServer() { return server; } protected MBeanServer getOrCreateMBeanServer() { if (server == null) { server = MBeanServerFactory.createMBeanServer("DynamicServerDomain"); } return server; } protected void dropMBeanServer() { if (server != null) { MBeanServerFactory.releaseMBeanServer(server); server = null; } } protected ServiceRegistration registerMBeanServer(final MBeanServer server) { return registerService(MBeanServer.class.getName(), server, null); } protected ServiceRegistration registerService(final String clazz, final Object service, final String objectName) { Hashtable<String, String> properties; if (objectName != null) { properties = new Hashtable<String, String>(); properties.put("jmx.objectname", objectName); } else { properties = null; } return bundleContext.registerService(clazz, service, properties); } protected void assertRegistered(final MBeanServer server, final ObjectName objectName) { try { ObjectInstance instance = server.getObjectInstance(objectName); TestCase.assertNotNull(instance); TestCase.assertEquals(objectName, instance.getObjectName()); } catch (InstanceNotFoundException nfe) { TestCase.fail("Expected instance of " + objectName + " registered with MBeanServer"); } } protected void assertNotRegistered(final MBeanServer server, final ObjectName objectName) { try { server.getObjectInstance(objectName); TestCase.fail("Unexpected instance of " + objectName + " registered with MBeanServer"); } catch (InstanceNotFoundException nfe) { // expected, ignore } } }
7,984
0
Create_ds/aries/jmx/jmx-whiteboard/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-whiteboard/src/main/java/org/apache/aries/jmx/whiteboard/MBeanHolder.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard; import java.util.IdentityHashMap; import java.util.Map; import java.util.Map.Entry; import javax.management.DynamicMBean; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.StandardMBean; import org.apache.aries.jmx.util.shared.RegistrableStandardEmitterMBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; final class MBeanHolder { /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); private final Object mbean; private final ObjectName requestedObjectName; private final Map<MBeanServer, ObjectName> registrations; static <T> MBeanHolder create(final T mbean, final ObjectName requestedObjectName) { if (mbean instanceof DynamicMBean) { return new MBeanHolder(mbean, requestedObjectName); } else if (mbean == null) { return null; } Class<?> mbeanClass = mbean.getClass(); @SuppressWarnings("unchecked") // This is all in aid of getting new StandardMBean to work. Class<T> mbeanInterface = (Class<T>) getMBeanInterface(mbeanClass); if (mbeanInterface == null) { return null; } if (mbeanInterface.getName().equals( mbeanClass.getName().concat("MBean")) || mbeanInterface.getName().equals(mbeanClass.getName().concat("MXBean")) ) { return new MBeanHolder(mbean, requestedObjectName); } try { StandardMBean stdMbean = new RegistrableStandardEmitterMBean(mbean, mbeanInterface); return new MBeanHolder(stdMbean, requestedObjectName); } catch (NotCompliantMBeanException e) { LoggerFactory.getLogger(MBeanHolder.class).error( "create: Cannot create StandardMBean for " + mbean + " of type " + mbeanClass + " for interface " + mbeanInterface, e); return null; } } private static Class<?> getMBeanInterface(final Class<?> mbeanClass) { if (mbeanClass == null) { return null; } for (Class<?> i : mbeanClass.getInterfaces()) { if (i.getName().endsWith("MBean") || i.getName().endsWith("MXBean")) { return i; } Class<?> mbeanInterface = getMBeanInterface(i); if (mbeanInterface != null) { return mbeanInterface; } } if (mbeanClass.getSuperclass() != null) { return getMBeanInterface(mbeanClass.getSuperclass()); } return null; } MBeanHolder(final Object mbean, final ObjectName requestedObjectName) { this.mbean = mbean; this.requestedObjectName = requestedObjectName; this.registrations = new IdentityHashMap<MBeanServer, ObjectName>(); } void register(final MBeanServer server, String[] warnExceptions) { ObjectInstance instance; try { instance = server.registerMBean(mbean, requestedObjectName); registrations.put(server, instance.getObjectName()); } catch (Exception e) { String exClass = e.getClass().getName(); if (warnExceptions == null) warnExceptions = new String[] {}; for (String exCls : warnExceptions) { if (exClass.equals(exCls)) { log.warn("register: problem registering MBean " + mbean, e); return; } } if (e instanceof InstanceAlreadyExistsException || e instanceof MBeanRegistrationException || e instanceof NotCompliantMBeanException) { log.error("register: Failure registering MBean " + mbean, e); } else if (e instanceof RuntimeException) { throw ((RuntimeException) e); } } } void unregister(final MBeanServer server) { final ObjectName registeredName = registrations.remove(server); if (registeredName != null) { unregister(server, registeredName); } } void unregister() { for (Entry<MBeanServer, ObjectName> entry : registrations.entrySet()) { unregister(entry.getKey(), entry.getValue()); } registrations.clear(); } private void unregister(final MBeanServer server, final ObjectName name) { try { server.unregisterMBean(name); } catch (MBeanRegistrationException e) { log.error("unregister: preDeregister of " + name + " threw an exception", e); } catch (InstanceNotFoundException e) { // not really expected ! log.error("unregister: Unexpected unregistration problem of MBean " + name, e); } } }
7,985
0
Create_ds/aries/jmx/jmx-whiteboard/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-whiteboard/src/main/java/org/apache/aries/jmx/whiteboard/Activator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard; import javax.management.MBeanServer; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; public class Activator implements BundleActivator { private JmxWhiteboardSupport jmxWhiteBoard; private ServiceTracker mbeanServerTracker; private ServiceTracker mbeanTracker; public void start(BundleContext context) throws Exception { jmxWhiteBoard = new JmxWhiteboardSupport(); mbeanServerTracker = new MBeanServerTracker(context); mbeanServerTracker.open(); mbeanTracker = new MBeanTracker(context); mbeanTracker.open(true); } public void stop(BundleContext context) throws Exception { if (mbeanTracker != null) { mbeanTracker.close(); mbeanTracker = null; } if (mbeanServerTracker != null) { mbeanServerTracker.close(); mbeanServerTracker = null; } jmxWhiteBoard = null; } private class MBeanServerTracker extends ServiceTracker { public MBeanServerTracker(BundleContext context) { super(context, MBeanServer.class.getName(), null); } @Override public Object addingService(ServiceReference reference) { MBeanServer mbeanServer = (MBeanServer) super.addingService(reference); jmxWhiteBoard.addMBeanServer(mbeanServer); return mbeanServer; } @Override public void removedService(ServiceReference reference, Object service) { if (service instanceof MBeanServer) { jmxWhiteBoard.removeMBeanServer((MBeanServer) service); } super.removedService(reference, service); } } private class MBeanTracker extends ServiceTracker { /** * Listens for any services registered with a "jmx.objectname" service * property. If the property is not a non-empty String object the service * is expected to implement the MBeanRegistration interface to create * the name dynamically. */ private static final String SIMPLE_MBEAN_FILTER = "(" + JmxWhiteboardSupport.PROP_OBJECT_NAME+ "=*)"; public MBeanTracker(BundleContext context) throws InvalidSyntaxException { super(context, context.createFilter(SIMPLE_MBEAN_FILTER), null); } @Override public Object addingService(ServiceReference reference) { Object mbean = super.addingService(reference); jmxWhiteBoard.registerMBean(mbean, reference); return mbean; } @Override public void removedService(ServiceReference reference, Object service) { jmxWhiteBoard.unregisterMBean(service); super.removedService(reference, service); } } }
7,986
0
Create_ds/aries/jmx/jmx-whiteboard/src/main/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-whiteboard/src/main/java/org/apache/aries/jmx/whiteboard/JmxWhiteboardSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.whiteboard; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.IdentityHashMap; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class JmxWhiteboardSupport { static final String PROP_OBJECT_NAME = "jmx.objectname"; /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); private MBeanServer[] mbeanServers = new MBeanServer[0]; // mapping registered MBean services to their MBeanHolder objects private final IdentityHashMap<Object, MBeanHolder> mbeans = new IdentityHashMap<Object, MBeanHolder>(); protected synchronized void addMBeanServer(final MBeanServer mbeanServer) { log.debug("addMBeanServer: Adding MBeanServer {}", mbeanServer); ArrayList<MBeanServer> serverList = new ArrayList<MBeanServer>( Arrays.asList(mbeanServers)); serverList.add(mbeanServer); mbeanServers = serverList.toArray(new MBeanServer[serverList.size()]); // register all mbeans with the new server for (MBeanHolder mbean : mbeans.values()) { mbean.register(mbeanServer, null); } } protected synchronized void removeMBeanServer(final MBeanServer mbeanServer) { log.debug("removeMBeanServer: Removing MBeanServer {}", mbeanServer); // remove all dynamically registered mbeans from the server for (MBeanHolder mbean : mbeans.values()) { mbean.unregister(mbeanServer); } ArrayList<MBeanServer> serverList = new ArrayList<MBeanServer>( Arrays.asList(mbeanServers)); serverList.remove(mbeanServer); mbeanServers = serverList.toArray(new MBeanServer[serverList.size()]); } protected synchronized void registerMBean(Object mbean, final ServiceReference props) { log.debug("registerMBean: Adding MBean {}", mbean); ObjectName objectName = getObjectName(props); if (objectName != null || mbean instanceof MBeanRegistration) { MBeanHolder holder = createMBeanHolder(mbean, objectName); if (holder != null) { MBeanServer[] mbeanServers = this.mbeanServers; String[] warnExceptions = getStringPlusProperty(props, "warning.exceptions"); for (MBeanServer mbeanServer : mbeanServers) { holder.register(mbeanServer, warnExceptions); } mbeans.put(mbean, holder); } else { log.error( "registerMBean: Cannot register MBean service {} with MBean servers: Not an instanceof DynamicMBean or not MBean spec compliant standard MBean", mbean); } } else { log.error( "registerMBean: MBean service {} not registered with valid jmx.objectname propety and not implementing MBeanRegistration interface; not registering with MBean servers", mbean); } } MBeanHolder createMBeanHolder(Object mbean, ObjectName objectName) { return MBeanHolder.create(mbean, objectName); } protected synchronized void unregisterMBean(Object mbean) { log.debug("unregisterMBean: Removing MBean {}", mbean); final MBeanHolder holder = mbeans.remove(mbean); if (holder != null) { holder.unregister(); } } private ObjectName getObjectName(final ServiceReference props) { Object oName = props.getProperty(PROP_OBJECT_NAME); if (oName instanceof ObjectName) { return (ObjectName) oName; } else if (oName instanceof String) { try { return new ObjectName((String) oName); } catch (MalformedObjectNameException e) { log.error("getObjectName: Provided ObjectName property " + oName + " cannot be used as an ObjectName", e); } } else { log.info( "getObjectName: Missing {} service property (or wrong type); registering if MBean is MBeanRegistration implementation", PROP_OBJECT_NAME); } return null; } private static String[] getStringPlusProperty(ServiceReference<?> ref, String propertyName) { final String[] res; Object prop = ref.getProperty(propertyName); if (prop == null) { res = null; } else if (prop instanceof String) { res = new String[] { (String) prop }; } else if ( prop instanceof Collection ) { final Object[] col = ((Collection<?>) prop).toArray(); res = new String[col.length]; for (int i = 0; i < res.length; i++) { res[i] = String.valueOf(col[i]); } } else if (prop.getClass().isArray() && String.class.equals(prop.getClass().getComponentType())) { res = (String[]) prop; } else { // unsupported type of property res = null; } return res; } }
7,987
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/AbstractIntegrationTest.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jmx; import static org.junit.Assert.assertNotNull; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.provision; import static org.ops4j.pax.exam.CoreOptions.streamBundle; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; import static org.ops4j.pax.tinybundles.core.TinyBundles.bundle; import static org.ops4j.pax.tinybundles.core.TinyBundles.withBnd; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; import javax.inject.Inject; import javax.management.MBeanServer; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import org.apache.aries.jmx.test.MbeanServerActivator; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; /** * @version $Rev$ $Date$ */ @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public abstract class AbstractIntegrationTest extends org.apache.aries.itest.AbstractIntegrationTest { protected ServiceReference reference; @Inject protected MBeanServer mbeanServer; public Option baseOptions() { String localRepo = System.getProperty("maven.repo.local"); if (localRepo == null) { localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository"); } return composite( junitBundles(), // this is how you set the default log level when using pax // logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)) ); } protected Option jmxRuntime() { return composite( baseOptions(), mavenBundle("org.osgi", "org.osgi.compendium").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.configadmin").versionAsInProject(), mavenBundle("org.apache.aries.jmx", "org.apache.aries.jmx").versionAsInProject(), mavenBundle("org.apache.aries.jmx", "org.apache.aries.jmx.core.whiteboard").versionAsInProject(), mavenBundle("org.apache.aries.jmx", "org.apache.aries.jmx.api").versionAsInProject(), mavenBundle("org.apache.aries.jmx", "org.apache.aries.jmx.whiteboard").versionAsInProject(), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), mbeanServerBundle() ); } protected Option mbeanServerBundle() { return provision(bundle() .add(MbeanServerActivator.class) .set(Constants.BUNDLE_ACTIVATOR, MbeanServerActivator.class.getName()) .build(withBnd())); } protected Option bundlea() { return provision(bundle() .add(org.apache.aries.jmx.test.bundlea.Activator.class) .add(org.apache.aries.jmx.test.bundlea.api.InterfaceA.class) .add(org.apache.aries.jmx.test.bundlea.impl.A.class) .set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundlea") .set(Constants.BUNDLE_VERSION, "2.0.0") .set(Constants.EXPORT_PACKAGE, "org.apache.aries.jmx.test.bundlea.api;version=2.0.0") .set(Constants.IMPORT_PACKAGE, "org.osgi.framework;version=1.5.0,org.osgi.util.tracker,org.apache.aries.jmx.test.bundleb.api;version=1.1.0;resolution:=optional" + ",org.osgi.service.cm") .set(Constants.BUNDLE_ACTIVATOR, org.apache.aries.jmx.test.bundlea.Activator.class.getName()) .build(withBnd())); } protected Option bundleb() { return provision(bundle() .add(org.apache.aries.jmx.test.bundleb.Activator.class) .add(org.apache.aries.jmx.test.bundleb.api.InterfaceB.class) .add(org.apache.aries.jmx.test.bundleb.api.MSF.class) .add(org.apache.aries.jmx.test.bundleb.impl.B.class) .set(Constants.BUNDLE_SYMBOLICNAME,"org.apache.aries.jmx.test.bundleb") .set(Constants.BUNDLE_VERSION, "1.0.0") .set(Constants.EXPORT_PACKAGE,"org.apache.aries.jmx.test.bundleb.api;version=1.1.0") .set(Constants.IMPORT_PACKAGE,"org.osgi.framework;version=1.5.0,org.osgi.util.tracker," + "org.osgi.service.cm,org.apache.aries.jmx.test.fragmentc") .set(Constants.BUNDLE_ACTIVATOR, org.apache.aries.jmx.test.bundleb.Activator.class.getName()) .build(withBnd())); } protected Option fragmentc() { return streamBundle(bundle() .add(org.apache.aries.jmx.test.fragmentc.C.class) .set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.fragc") .set(Constants.FRAGMENT_HOST, "org.apache.aries.jmx.test.bundlea") .set(Constants.EXPORT_PACKAGE, "org.apache.aries.jmx.test.fragmentc") .build(withBnd())).noStart(); } protected Option bundled() { return provision(bundle() .set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundled") .set(Constants.BUNDLE_VERSION, "3.0.0") .set(Constants.REQUIRE_BUNDLE, "org.apache.aries.jmx.test.bundlea;bundle-version=2.0.0") .build(withBnd())); } protected Option bundlee() { return provision(bundle() .set(Constants.BUNDLE_SYMBOLICNAME, "org.apache.aries.jmx.test.bundlee") .set(Constants.BUNDLE_DESCRIPTION, "%desc") .add("OSGI-INF/l10n/bundle.properties", getBundleProps("desc", "Description")) .add("OSGI-INF/l10n/bundle_nl.properties", getBundleProps("desc", "Omschrijving")) .build(withBnd())); } private InputStream getBundleProps(String key, String value) { try { Properties p = new Properties(); p.put(key, value); ByteArrayOutputStream baos = new ByteArrayOutputStream(); p.store(baos, ""); return new ByteArrayInputStream(baos.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } } protected ObjectName waitForMBean(String name) { return waitForMBean(name, 20); } protected ObjectName waitForMBean(String name, int timeoutInSeconds) { int i=0; while (true) { ObjectName queryName; try { queryName = new ObjectName(name.toString() + ",*"); } catch (Exception e) { throw new IllegalArgumentException("Invalid name " + name, e); } Set<ObjectName> result = mbeanServer.queryNames(queryName, null); if (result.size() > 0) return result.iterator().next(); if (i == timeoutInSeconds * 10) throw new RuntimeException(name + " mbean is not available after waiting " + timeoutInSeconds + " seconds"); i++; try { Thread.sleep(100); } catch (InterruptedException e) { } } } protected <T> T getMBean(String name, Class<T> type) { ObjectName objectName = waitForMBean(name); return getMBean(objectName, type); } protected <T> T getMBean(ObjectName objectName, Class<T> type) { return MBeanServerInvocationHandler.newProxyInstance(mbeanServer, objectName, type, false); } protected Bundle getBundleByName(String symName) { Bundle b = context().getBundleByName(symName); assertNotNull("Bundle " + symName + "should be installed", b); return b; } }
7,988
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/MbeanServerActivator.java
package org.apache.aries.jmx.test; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; public class MbeanServerActivator implements BundleActivator { public void start(BundleContext context) throws Exception { MBeanServer mBeanServer = MBeanServerFactory.createMBeanServer(); context.registerService(MBeanServer.class, mBeanServer, null); } public void stop(BundleContext context) throws Exception { } }
7,989
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb/Activator.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jmx.test.bundleb; import java.util.Dictionary; import java.util.Hashtable; import org.apache.aries.jmx.test.bundleb.api.InterfaceB; import org.apache.aries.jmx.test.bundleb.api.MSF; import org.apache.aries.jmx.test.bundleb.impl.B; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.service.cm.ManagedServiceFactory; /** * * * @version $Rev$ $Date$ */ public class Activator implements BundleActivator { /* (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(Constants.SERVICE_PID, "org.apache.aries.jmx.test.ServiceB"); context.registerService(InterfaceB.class.getName(), new B(), props); Dictionary<String, Object> fprops = new Hashtable<String, Object>(); fprops.put(Constants.SERVICE_PID, "jmx.test.B.factory"); context.registerService(ManagedServiceFactory.class.getName(), new MSF(), fprops); } /* (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { } }
7,990
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb/impl/B.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jmx.test.bundleb.impl; import java.util.Dictionary; import org.apache.aries.jmx.test.bundleb.api.InterfaceB; /** * * * @version $Rev$ $Date$ */ @SuppressWarnings("rawtypes") public class B implements InterfaceB { private Dictionary<String, Object> conf; public boolean invoke() { return (conf == null); } public void configure(Dictionary<String, Object> props) { this.conf = props; } // test cback public Dictionary getConfig() { return this.conf; } }
7,991
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb/api/MSF.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jmx.test.bundleb.api; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import org.apache.aries.jmx.test.bundleb.impl.B; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedServiceFactory; /** * * * @version $Rev$ $Date$ */ @SuppressWarnings({"unchecked", "rawtypes"}) public class MSF implements ManagedServiceFactory { Map<String, InterfaceB> configured = new HashMap<String, InterfaceB>(); public void deleted(String pid) { configured.remove(pid); } public String getName() { return "jmx.test.B.factory"; } public void updated(String pid, Dictionary dictionary) throws ConfigurationException { if (configured.containsKey(pid)) { configured.get(pid).configure(dictionary); } else { InterfaceB ser = new B(); ser.configure(dictionary); configured.put(pid, ser); } } // test cback public InterfaceB getConfigured(String pid) { return configured.get(pid); } }
7,992
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/bundleb/api/InterfaceB.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jmx.test.bundleb.api; import java.util.Dictionary; /** * * * @version $Rev$ $Date$ */ @SuppressWarnings("rawtypes") public interface InterfaceB { boolean invoke(); void configure(Dictionary<String, Object> props); Dictionary getConfig(); }
7,993
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/fragmentc/C.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.aries.jmx.test.fragmentc; /** * * * @version $Rev$ $Date$ */ public class C { boolean invoke() { return true; } }
7,994
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/BlueprintMBeanTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.test.blueprint; import static org.junit.Assert.assertEquals; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import java.util.Arrays; import javax.inject.Inject; import javax.management.MBeanServerInvocationHandler; import javax.management.ObjectName; import javax.management.openmbean.TabularData; import org.apache.aries.jmx.AbstractIntegrationTest; import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean; import org.apache.aries.jmx.blueprint.BlueprintStateMBean; import org.apache.aries.jmx.test.blueprint.framework.BeanPropertyValidator; import org.apache.aries.jmx.test.blueprint.framework.BeanValidator; import org.apache.aries.jmx.test.blueprint.framework.BlueprintEventValidator; import org.apache.aries.jmx.test.blueprint.framework.CollectionValidator; import org.apache.aries.jmx.test.blueprint.framework.MapEntryValidator; import org.apache.aries.jmx.test.blueprint.framework.RefValidator; import org.apache.aries.jmx.test.blueprint.framework.ReferenceListValidator; import org.apache.aries.jmx.test.blueprint.framework.ReferenceListenerValidator; import org.apache.aries.jmx.test.blueprint.framework.ReferenceValidator; import org.apache.aries.jmx.test.blueprint.framework.RegistrationListenerValidator; import org.apache.aries.jmx.test.blueprint.framework.ServiceValidator; import org.apache.aries.jmx.test.blueprint.framework.ValueValidator; import org.junit.Before; import org.junit.Test; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.util.Filter; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.blueprint.container.BlueprintContainer; public class BlueprintMBeanTest extends AbstractIntegrationTest { @Inject @Filter("(osgi.blueprint.container.symbolicname=org.apache.aries.blueprint)") BlueprintContainer blueprintExtender; @Inject @Filter("(osgi.blueprint.container.symbolicname=org.apache.aries.blueprint.sample)") BlueprintContainer blueprintSample; private Bundle extender; private Bundle sample; @Configuration public Option[] configuration() { return CoreOptions.options( jmxRuntime(), blueprint(), mavenBundle("org.apache.aries.jmx", "org.apache.aries.jmx.blueprint").versionAsInProject(), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.sample").versionAsInProject() ); } protected Option blueprint() { return composite( mavenBundle("org.ow2.asm", "asm-debug-all").versionAsInProject(), mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject(), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint").versionAsInProject(), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.jexl.evaluator").versionAsInProject(), mavenBundle("org.apache.commons", "commons-jexl").versionAsInProject() ); } @Before public void setup() { extender = getBundleByName("org.apache.aries.blueprint"); sample = getBundleByName("org.apache.aries.blueprint.sample"); } @Test public void testBlueprintStateMBean() throws Exception { BlueprintStateMBean stateProxy = getMBean(BlueprintStateMBean.OBJECTNAME, BlueprintStateMBean.class); // test getBlueprintBundleIds long[] bpBundleIds = stateProxy.getBlueprintBundleIds(); assertEquals("The blueprint bundle ids are: " + Arrays.toString(bpBundleIds), 3, bpBundleIds.length); // test getLastEvent BlueprintEventValidator sampleValidator = new BlueprintEventValidator(sample.getBundleId(), extender.getBundleId(), 2); sampleValidator.validate(stateProxy.getLastEvent(sample.getBundleId())); // test getLastEvents TabularData lastEvents = stateProxy.getLastEvents(); assertEquals(BlueprintStateMBean.OSGI_BLUEPRINT_EVENTS_TYPE,lastEvents.getTabularType()); sampleValidator.validate(lastEvents.get(new Long[]{sample.getBundleId()})); } @Test public void testBlueprintMetaDataMBean() throws Exception { //find the Blueprint Sample bundle's container service id String filter = "(&(osgi.blueprint.container.symbolicname=" // no similar one in interfaces + sample.getSymbolicName() + ")(osgi.blueprint.container.version=" + sample.getVersion() + "))"; ServiceReference[] serviceReferences = null; try { serviceReferences = bundleContext.getServiceReferences(BlueprintContainer.class.getName(), filter); } catch (InvalidSyntaxException e) { throw new RuntimeException(e); } long sampleBlueprintContainerServiceId = (Long) serviceReferences[0].getProperty(Constants.SERVICE_ID); //retrieve the proxy object BlueprintMetadataMBean metadataProxy = MBeanServerInvocationHandler.newProxyInstance(mbeanServer, new ObjectName(BlueprintMetadataMBean.OBJECTNAME), BlueprintMetadataMBean.class, false); // test getBlueprintContainerServiceIds long[] bpContainerServiceIds = metadataProxy.getBlueprintContainerServiceIds(); assertEquals(3, bpContainerServiceIds.length); // test getBlueprintContainerServiceId assertEquals(sampleBlueprintContainerServiceId, metadataProxy.getBlueprintContainerServiceId(sample.getBundleId())); // test getComponentMetadata // bean: foo BeanValidator bv_foo = new BeanValidator("org.apache.aries.blueprint.sample.Foo", "init", "destroy"); BeanPropertyValidator bpv_a = property("a", "5"); BeanPropertyValidator bpv_b = property("b", "-1"); BeanPropertyValidator bpv_bar = new BeanPropertyValidator("bar"); bpv_bar.setObjectValueValidator(new RefValidator("bar")); BeanPropertyValidator bpv_currency = property("currency", "PLN"); BeanPropertyValidator bpv_date = property("date", "2009.04.17"); bv_foo.addPropertyValidators(bpv_a, bpv_b, bpv_bar, bpv_currency, bpv_date); bv_foo.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "foo")); // bean: bar BeanPropertyValidator bpv_value = property("value", "Hello FooBar"); BeanPropertyValidator bpv_context = new BeanPropertyValidator("context"); bpv_context.setObjectValueValidator(new RefValidator("blueprintBundleContext")); CollectionValidator cv = new CollectionValidator("java.util.List"); cv.addCollectionValueValidators( new ValueValidator("a list element"), new ValueValidator("5", "java.lang.Integer")); BeanPropertyValidator bpv_list = new BeanPropertyValidator("list"); bpv_list.setObjectValueValidator(cv); BeanValidator bv_bar = new BeanValidator("org.apache.aries.blueprint.sample.Bar"); bv_bar.addPropertyValidators(bpv_value, bpv_context, bpv_list); bv_bar.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "bar")); // service: ref=foo, no componentId set. So using it to test getComponentIdsByType. String[] serviceComponentIds = metadataProxy.getComponentIdsByType(sampleBlueprintContainerServiceId, BlueprintMetadataMBean.SERVICE_METADATA); assertEquals("There should be two service components in this sample", 2, serviceComponentIds.length); MapEntryValidator mev = new MapEntryValidator(); mev.setKeyValueValidator(new ValueValidator("key"), new ValueValidator("value")); RegistrationListenerValidator rglrv = new RegistrationListenerValidator("serviceRegistered", "serviceUnregistered"); rglrv.setListenerComponentValidator(new RefValidator("fooRegistrationListener")); ServiceValidator sv = new ServiceValidator(4); sv.setServiceComponentValidator(new RefValidator("foo")); sv.addMapEntryValidator(mev); sv.addRegistrationListenerValidator(rglrv); sv.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, serviceComponentIds[0])); // bean: fooRegistrationListener BeanValidator bv_fooRegistrationListener = new BeanValidator("org.apache.aries.blueprint.sample.FooRegistrationListener"); bv_fooRegistrationListener.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "fooRegistrationListener")); // reference: ref2 ReferenceListenerValidator rlrv_1 = new ReferenceListenerValidator("bind", "unbind"); rlrv_1.setListenerComponentValidator(new RefValidator("bindingListener")); ReferenceValidator rv = new ReferenceValidator("org.apache.aries.blueprint.sample.InterfaceA", 100); rv.addReferenceListenerValidator(rlrv_1); rv.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "ref2")); // bean: bindingListener BeanValidator bv_bindingListener = new BeanValidator("org.apache.aries.blueprint.sample.BindingListener"); bv_bindingListener.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "bindingListener")); // reference-list: ref-list ReferenceListenerValidator rlrv_2 = new ReferenceListenerValidator("bind", "unbind"); rlrv_2.setListenerComponentValidator(new RefValidator("listBindingListener")); ReferenceListValidator rlv_ref_list = new ReferenceListValidator("org.apache.aries.blueprint.sample.InterfaceA"); rlv_ref_list.addReferenceListenerValidator(rlrv_2); rlv_ref_list.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "ref-list")); // bean: listBindingListener BeanValidator bv_listBindingListener = new BeanValidator("org.apache.aries.blueprint.sample.BindingListener"); bv_listBindingListener.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "listBindingListener")); // bean: circularReference ReferenceListenerValidator rlrv_3 = new ReferenceListenerValidator("bind", "unbind"); rlrv_3.setListenerComponentValidator(new RefValidator("circularReference")); ReferenceListValidator rlv_2 = new ReferenceListValidator("org.apache.aries.blueprint.sample.InterfaceA", 2); rlv_2.addReferenceListenerValidator(rlrv_3); BeanPropertyValidator bpv_list_2 = new BeanPropertyValidator("list"); bpv_list_2.setObjectValueValidator(rlv_2); BeanValidator bv_circularReference = new BeanValidator("org.apache.aries.blueprint.sample.BindingListener", "init"); bv_circularReference.addPropertyValidators(bpv_list_2); bv_circularReference.validate(metadataProxy.getComponentMetadata(sampleBlueprintContainerServiceId, "circularReference")); } private BeanPropertyValidator property(String name, String expectedValue) { BeanPropertyValidator val = new BeanPropertyValidator(name); val.setObjectValueValidator(new ValueValidator(expectedValue)); return val; } }
7,995
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/ReferenceValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.test.blueprint.framework; import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean; public class ReferenceValidator extends AbstractServiceReferenceValidator implements TargetValidator{ public ReferenceValidator(String interfaceName, long timeout){ super(BlueprintMetadataMBean.REFERENCE_METADATA_TYPE); this.setExpectValue(BlueprintMetadataMBean.INTERFACE, interfaceName); this.setExpectValue(BlueprintMetadataMBean.TIMEOUT, timeout); } }
7,996
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/ReferenceListenerValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.test.blueprint.framework; import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean; public class ReferenceListenerValidator extends AbstractListenerComponentValidator { public ReferenceListenerValidator(String bindMethod,String unbindMethod){ super(BlueprintMetadataMBean.REFERENCE_LISTENER_TYPE); this.setExpectValue(BlueprintMetadataMBean.BIND_METHOD, bindMethod); this.setExpectValue(BlueprintMetadataMBean.UNBIND_METHOD, unbindMethod); } }
7,997
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/Util.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.test.blueprint.framework; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import javax.management.openmbean.CompositeData; public class Util { public static CompositeData decode(Byte[] wrap){ if (null == wrap) return null; byte[] prim = new byte[wrap.length]; for (int i = 0; i < wrap.length; i++) { prim[i] = wrap[i]; } ByteArrayInputStream inBytes = new ByteArrayInputStream(prim); ObjectInputStream inObject; CompositeData data; try { inObject = new ObjectInputStream(inBytes); data = (CompositeData) inObject.readObject(); inObject.close(); return data; } catch (Exception e) { throw new RuntimeException(e); } } }
7,998
0
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint
Create_ds/aries/jmx/jmx-itests/src/test/java/org/apache/aries/jmx/test/blueprint/framework/BeanValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.aries.jmx.test.blueprint.framework; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; import javax.management.openmbean.CompositeData; import org.apache.aries.jmx.blueprint.BlueprintMetadataMBean; public class BeanValidator extends AbstractCompositeDataValidator implements NonNullObjectValueValidator, TargetValidator{ private boolean validateArgumentsFlag = true; private List<BeanArgumentValidator> beanArgumentValidators = new ArrayList<BeanArgumentValidator>(); private boolean validatePropertiesFlag = true; private List<BeanPropertyValidator> beanPropertyValidators = new ArrayList<BeanPropertyValidator>(); public BeanValidator(String className){ super(BlueprintMetadataMBean.BEAN_METADATA_TYPE); setExpectValue(BlueprintMetadataMBean.CLASS_NAME, className); } public BeanValidator(String className, String initMethod){ super(BlueprintMetadataMBean.BEAN_METADATA_TYPE); setExpectValue(BlueprintMetadataMBean.CLASS_NAME, className); setExpectValue(BlueprintMetadataMBean.INIT_METHOD, initMethod); } public BeanValidator(String className, String initMethod, String destroyMethod){ super(BlueprintMetadataMBean.BEAN_METADATA_TYPE); setExpectValue(BlueprintMetadataMBean.CLASS_NAME, className); setExpectValue(BlueprintMetadataMBean.INIT_METHOD, initMethod); setExpectValue(BlueprintMetadataMBean.DESTROY_METHOD, destroyMethod); } public void setValidateArgumentsFlag(boolean flag){ validateArgumentsFlag = flag; } public void addArgumentValidators(BeanArgumentValidator... validators){ for (BeanArgumentValidator beanArgumentValidator : validators) beanArgumentValidators.add(beanArgumentValidator); } public void setValidatePropertiesFlag(boolean flag){ validatePropertiesFlag = flag; } public void addPropertyValidators(BeanPropertyValidator... validators){ for (BeanPropertyValidator beanPropertyValidator : validators) beanPropertyValidators.add(beanPropertyValidator); } public void validate(CompositeData target){ super.validate(target); //Validate args if (validateArgumentsFlag){ CompositeData[] args = (CompositeData[])target.get(BlueprintMetadataMBean.ARGUMENTS); assertNotNull(args); // at least CompositeData[0] assertEquals("The size of arguments is not equals, expect " + beanArgumentValidators.size() + " but got " + args.length, beanArgumentValidators.size(), args.length); for (int i=0; i<beanArgumentValidators.size(); i++) // the order of the arg validators should be the same with the args beanArgumentValidators.get(i).validate(args[i]); } //Validate props if (validatePropertiesFlag){ CompositeData[] props = (CompositeData[])target.get(BlueprintMetadataMBean.PROPERTIES); assertNotNull(props); assertEquals("The size of properties is not equals, expect " + beanPropertyValidators.size() + " but got " + props.length, beanPropertyValidators.size(), props.length); for (int i=0; i<beanPropertyValidators.size(); i++) beanPropertyValidators.get(i).validate(props[i]); } } }
7,999