Search in sources :

Example 6 with ServiceException

use of org.osgi.framework.ServiceException in project ecf by eclipse.

the class RemoteServiceAdmin method createProxy.

private Object createProxy(Bundle requestingBundle, ServiceReference serviceReference, IRemoteService remoteService, Map<String, Version> interfaceVersions) {
    // Get symbolicName once for possible use below
    String bundleSymbolicName = requestingBundle.getSymbolicName();
    // Get String[] via OBJECTCLASS constant property
    String[] serviceClassnames = (String[]) serviceReference.getProperty(org.osgi.framework.Constants.OBJECTCLASS);
    // Load as many of the serviceInterface classes as possible
    Collection<Class> serviceInterfaceClasses = loadServiceInterfacesViaBundle(requestingBundle, serviceClassnames);
    // load...otherwise the service can't be accessed
    if (serviceInterfaceClasses.size() < 1)
        throw new RuntimeException(// $NON-NLS-1$
        "ProxyServiceFactory cannot load any serviceInterfaces=" + serviceInterfaceClasses + " for serviceReference=" + // $NON-NLS-1$
        serviceReference + " via clientBundle=" + // $NON-NLS-1$
        bundleSymbolicName);
    // Now verify that the classes are of valid versions
    if (!verifyServiceInterfaceVersionsForProxy(requestingBundle, serviceInterfaceClasses, interfaceVersions))
        return null;
    // Now create/get class loader for proxy. This will typically
    // be an instance of ProxyClassLoader
    ClassLoader cl = getProxyClassLoader(requestingBundle);
    try {
        return remoteService.getProxy(cl, (Class[]) serviceInterfaceClasses.toArray(new Class[serviceInterfaceClasses.size()]));
    } catch (ECFException e) {
        throw new ServiceException(// $NON-NLS-1$
        "ProxyServiceFactory cannot create proxy for clientBundle=" + bundleSymbolicName + // $NON-NLS-1$
        " from serviceReference=" + serviceReference, e);
    }
}
Also used : ECFException(org.eclipse.ecf.core.util.ECFException) ServiceException(org.osgi.framework.ServiceException)

Example 7 with ServiceException

use of org.osgi.framework.ServiceException in project aries by apache.

the class AriesApplicationManagerImpl method createApplication.

/**
 * Create an AriesApplication from a .eba file: a zip file with a '.eba' extension
 */
public AriesApplication createApplication(IDirectory ebaFile) throws ManagementException {
    ApplicationMetadata applicationMetadata = null;
    DeploymentMetadata deploymentMetadata = null;
    Map<String, BundleConversion> modifiedBundles = new HashMap<String, BundleConversion>();
    AriesApplicationImpl application = null;
    String appPath = ebaFile.toString();
    try {
        // try to read the app name out of the application.mf
        Manifest applicationManifest = parseApplicationManifest(ebaFile);
        String appName = applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_NAME);
        // If the application name is null, we will try to get the file name.
        if (appName == null || appName.isEmpty()) {
            String fullPath = appPath;
            if (fullPath.endsWith("/")) {
                fullPath = fullPath.substring(0, fullPath.length() - 1);
            }
            int last_slash = fullPath.lastIndexOf("/");
            appName = fullPath.substring(last_slash + 1, fullPath.length());
        }
        IFile deploymentManifest = ebaFile.getFile(AppConstants.DEPLOYMENT_MF);
        /* We require that all other .jar and .war files included by-value be valid bundles
       * because a DEPLOYMENT.MF has been provided. If no DEPLOYMENT.MF, migrate 
       * wars to wabs, plain jars to bundles
       */
        Set<BundleInfo> extraBundlesInfo = new HashSet<BundleInfo>();
        for (IFile f : ebaFile) {
            if (f.isDirectory()) {
                continue;
            }
            BundleManifest bm = getBundleManifest(f);
            if (bm != null) {
                if (bm.isValid()) {
                    _logger.debug("File {} is a valid bundle. Adding it to bundle list.", f.getName());
                    extraBundlesInfo.add(new SimpleBundleInfo(bm, f.toURL().toExternalForm()));
                } else if (deploymentManifest == null) {
                    _logger.debug("File {} is not a valid bundle. Attempting to convert it.", f.getName());
                    // We have a jar that needs converting to a bundle, or a war to migrate to a WAB
                    // We only do this if a DEPLOYMENT.MF does not exist.
                    BundleConversion convertedBinary = null;
                    Iterator<BundleConverter> converters = _bundleConverters.iterator();
                    List<ConversionException> conversionExceptions = Collections.emptyList();
                    while (converters.hasNext() && convertedBinary == null) {
                        try {
                            BundleConverter converter = converters.next();
                            _logger.debug("Converting file using {} converter", converter);
                            convertedBinary = converter.convert(ebaFile, f);
                        } catch (ServiceException sx) {
                        // We'll get this if our optional BundleConverter has not been injected.
                        } catch (ConversionException cx) {
                            conversionExceptions.add(cx);
                        }
                    }
                    if (conversionExceptions.size() > 0) {
                        for (ConversionException cx : conversionExceptions) {
                            _logger.error("APPMANAGEMENT0004E", new Object[] { f.getName(), appName, cx });
                        }
                        throw new ManagementException(MessageUtil.getMessage("APPMANAGEMENT0005E", appName));
                    }
                    if (convertedBinary != null) {
                        _logger.debug("File {} was successfully converted. Adding it to bundle list.", f.getName());
                        modifiedBundles.put(f.getName(), convertedBinary);
                        extraBundlesInfo.add(convertedBinary.getBundleInfo());
                    } else {
                        _logger.debug("File {} was not converted.", f.getName());
                    }
                } else {
                    _logger.debug("File {} was ignored. It is not a valid bundle and DEPLOYMENT.MF is present", f.getName());
                }
            } else {
                _logger.debug("File {} was ignored. It has no manifest file.", f.getName());
            }
        }
        // if Application-Content header was not specified build it based on the bundles included by value
        if (applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_CONTENT) == null) {
            String appContent = buildAppContent(extraBundlesInfo);
            applicationManifest.getMainAttributes().putValue(AppConstants.APPLICATION_CONTENT, appContent);
        }
        ManifestDefaultsInjector.updateManifest(applicationManifest, appName, ebaFile);
        applicationMetadata = _applicationMetadataFactory.createApplicationMetadata(applicationManifest);
        if (deploymentManifest != null) {
            deploymentMetadata = _deploymentMetadataFactory.parseDeploymentMetadata(deploymentManifest);
            // Validate: symbolic names must match
            String appSymbolicName = applicationMetadata.getApplicationSymbolicName();
            String depSymbolicName = deploymentMetadata.getApplicationSymbolicName();
            if (!appSymbolicName.equals(depSymbolicName)) {
                throw new ManagementException(MessageUtil.getMessage("APPMANAGEMENT0002E", appName, appSymbolicName, depSymbolicName));
            }
        }
        application = new AriesApplicationImpl(applicationMetadata, extraBundlesInfo, _localPlatform);
        application.setDeploymentMetadata(deploymentMetadata);
        // Store a reference to any modified bundles
        application.setModifiedBundles(modifiedBundles);
    } catch (IOException iox) {
        _logger.error("APPMANAGEMENT0006E", new Object[] { appPath, iox });
        throw new ManagementException(iox);
    }
    return application;
}
Also used : ConversionException(org.apache.aries.application.management.spi.convert.ConversionException) DeploymentMetadata(org.apache.aries.application.DeploymentMetadata) IFile(org.apache.aries.util.filesystem.IFile) HashMap(java.util.HashMap) BundleManifest(org.apache.aries.util.manifest.BundleManifest) IOException(java.io.IOException) Manifest(java.util.jar.Manifest) BundleManifest(org.apache.aries.util.manifest.BundleManifest) ResolveConstraint(org.apache.aries.application.management.ResolveConstraint) BundleConverter(org.apache.aries.application.management.spi.convert.BundleConverter) ApplicationMetadata(org.apache.aries.application.ApplicationMetadata) ManagementException(org.apache.aries.application.management.ManagementException) BundleInfo(org.apache.aries.application.management.BundleInfo) SimpleBundleInfo(org.apache.aries.application.utils.management.SimpleBundleInfo) ServiceException(org.osgi.framework.ServiceException) Iterator(java.util.Iterator) SimpleBundleInfo(org.apache.aries.application.utils.management.SimpleBundleInfo) List(java.util.List) BundleConversion(org.apache.aries.application.management.spi.convert.BundleConversion) HashSet(java.util.HashSet)

Example 8 with ServiceException

use of org.osgi.framework.ServiceException in project aries by apache.

the class ServiceRegistryContextTest method testLookupWithPause.

@Test
public void testLookupWithPause() throws NamingException {
    BundleMock mock = new BundleMock("scooby.doo", new Properties());
    Thread.currentThread().setContextClassLoader(mock.getClassLoader());
    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(JNDIConstants.REBIND_TIMEOUT, 1000);
    InitialContext ctx = new InitialContext(env);
    Context ctx2 = (Context) ctx.lookup("osgi:service");
    Runnable r1 = (Runnable) ctx2.lookup("java.lang.Runnable");
    reg.unregister();
    long startTime = System.currentTimeMillis();
    try {
        r1.run();
        fail("Should have received an exception");
    } catch (ServiceException e) {
        long endTime = System.currentTimeMillis();
        long diff = endTime - startTime;
        assertTrue("The run method did not fail in the expected time (1s): " + diff, diff >= 1000);
    }
}
Also used : Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) BundleContext(org.osgi.framework.BundleContext) ServiceException(org.osgi.framework.ServiceException) Hashtable(java.util.Hashtable) BundleMock(org.apache.aries.mocks.BundleMock) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Example 9 with ServiceException

use of org.osgi.framework.ServiceException in project polymap4-core by Polymap4.

the class SimpleWmsServer method parseBBox.

public static ReferencedEnvelope parseBBox(String value) throws NoSuchAuthorityCodeException, FactoryException {
    String[] unparsed = StringUtils.split(value, INNER_DELIMETER);
    // check to make sure that the bounding box has 4 coordinates
    if (unparsed.length < 4) {
        throw new IllegalArgumentException("Requested bounding box contains wrong" + "number of coordinates (should have " + "4): " + unparsed.length);
    }
    // if it does, store them in an array of doubles
    double[] bbox = new double[4];
    for (int i = 0; i < 4; i++) {
        try {
            bbox[i] = Double.parseDouble(unparsed[i]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Bounding box coordinate " + i + " is not parsable:" + unparsed[i]);
        }
    }
    // ensure the values are sane
    double minx = bbox[0];
    double miny = bbox[1];
    double maxx = bbox[2];
    double maxy = bbox[3];
    if (minx > maxx) {
        throw new ServiceException("Illegal bbox, minX: " + minx + " is " + "greater than maxX: " + maxx);
    }
    if (miny > maxy) {
        throw new ServiceException("Illegal bbox, minY: " + miny + " is " + "greater than maxY: " + maxy);
    }
    // check for crs
    CoordinateReferenceSystem crs = null;
    if (unparsed.length > 4) {
        crs = CRS.decode(unparsed[4]);
    } else {
    // TODO: use the default crs of the system
    }
    return new ReferencedEnvelope(minx, maxx, miny, maxy, crs);
}
Also used : ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) ServiceException(org.osgi.framework.ServiceException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 10 with ServiceException

use of org.osgi.framework.ServiceException in project opencast by opencast.

the class EventCommentDatabaseServiceImpl method repopulate.

@Override
public void repopulate(final String indexName) throws Exception {
    final String destinationId = CommentItem.COMMENT_QUEUE_PREFIX + WordUtils.capitalize(indexName);
    try {
        final int total = countComments();
        final int[] current = new int[1];
        current[0] = 0;
        logger.info("Re-populating index '{}' with comments for events. There are {} events with comments to add", indexName, total);
        final int responseInterval = (total < 100) ? 1 : (total / 100);
        final Map<String, List<String>> eventsWithComments = getEventsWithComments();
        for (String orgId : eventsWithComments.keySet()) {
            Organization organization = organizationDirectoryService.getOrganization(orgId);
            SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(cc, organization), new Effect0() {

                @Override
                protected void run() {
                    for (String eventId : eventsWithComments.get(orgId)) {
                        try {
                            List<EventComment> comments = getComments(eventId);
                            boolean hasOpenComments = !Stream.$(comments).filter(filterOpenComments).toList().isEmpty();
                            boolean needsCutting = !Stream.$(comments).filter(filterNeedsCuttingComment).toList().isEmpty();
                            messageSender.sendObjectMessage(destinationId, MessageSender.DestinationType.Queue, CommentItem.update(eventId, !comments.isEmpty(), hasOpenComments, needsCutting));
                            current[0] += comments.size();
                            if (responseInterval == 1 || comments.size() > responseInterval || current[0] == total || current[0] % responseInterval < comments.size()) {
                                messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.update(indexName, IndexRecreateObject.Service.Comments, total, current[0]));
                            }
                        } catch (EventCommentDatabaseException e) {
                            logger.error("Unable to retrieve event comments for organization {}", orgId, e);
                        } catch (Throwable t) {
                            logger.error("Unable to update comment on event {} for organization {}", eventId, orgId, t);
                        }
                    }
                }
            });
        }
    } catch (Exception e) {
        logger.warn("Unable to index event comments", e);
        throw new ServiceException(e.getMessage());
    }
    Organization organization = new DefaultOrganization();
    SecurityUtil.runAs(securityService, organization, SecurityUtil.createSystemUser(cc, organization), new Effect0() {

        @Override
        protected void run() {
            messageSender.sendObjectMessage(IndexProducer.RESPONSE_QUEUE, MessageSender.DestinationType.Queue, IndexRecreateObject.end(indexName, IndexRecreateObject.Service.Comments));
        }
    });
}
Also used : Organization(org.opencastproject.security.api.Organization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) ServiceException(org.osgi.framework.ServiceException) NoResultException(javax.persistence.NoResultException) NotFoundException(org.opencastproject.util.NotFoundException) ServiceException(org.osgi.framework.ServiceException) Effect0(org.opencastproject.util.data.Effect0) ArrayList(java.util.ArrayList) List(java.util.List) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization)

Aggregations

ServiceException (org.osgi.framework.ServiceException)16 Organization (org.opencastproject.security.api.Organization)6 IOException (java.io.IOException)5 NotFoundException (org.opencastproject.util.NotFoundException)5 DefaultOrganization (org.opencastproject.security.api.DefaultOrganization)4 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)4 SeriesException (org.opencastproject.series.api.SeriesException)3 Effect0 (org.opencastproject.util.data.Effect0)3 File (java.io.File)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Properties (java.util.Properties)2 Context (javax.naming.Context)2 InitialContext (javax.naming.InitialContext)2 BundleMock (org.apache.aries.mocks.BundleMock)2 SolrServerException (org.apache.solr.client.solrj.SolrServerException)2 Test (org.junit.Test)2 AccessControlList (org.opencastproject.security.api.AccessControlList)2