示例#1
0
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();
    DatabaseHelper.DATABASE.setUp();

    deployBundle("org.nuxeo.ecm.core.schema");
    deployBundle("org.nuxeo.ecm.core");
    deployBundle("org.nuxeo.ecm.core.event");
    deployBundle("org.nuxeo.ecm.core.api");
    deployBundle("org.nuxeo.ecm.directory.api");
    deployBundle("org.nuxeo.ecm.directory");
    deployBundle("org.nuxeo.ecm.directory.sql");
    deployBundle("org.nuxeo.ecm.directory.types.contrib");
    deployContrib("org.nuxeo.ecm.platform.query.api", "OSGI-INF/pageprovider-framework.xml");
    deployBundle("org.nuxeo.ecm.platform.usermanager.api");
    deployBundle("org.nuxeo.ecm.platform.usermanager");

    deployContrib(
        "org.nuxeo.ecm.platform.usermanager.tests", "test-usermanagerimpl/directory-config.xml");
    deployContrib("org.nuxeo.ecm.platform.usermanager.tests", "computedgroups-contrib.xml");

    ppService = Framework.getService(PageProviderService.class);
    assertNotNull(ppService);

    userManager = Framework.getService(UserManager.class);
    assertNotNull(userManager);

    initGroups();
  }
 protected void loadComponents(Bundle bundle, RuntimeContext ctx) throws Exception {
   String list = getComponentsList(bundle);
   String name = bundle.getSymbolicName();
   log.debug("Bundle: " + name + " components: " + list);
   if (list == null) {
     return;
   }
   StringTokenizer tok = new StringTokenizer(list, ", \t\n\r\f");
   while (tok.hasMoreTokens()) {
     String path = tok.nextToken();
     URL url = bundle.getEntry(path);
     log.debug("Loading component for: " + name + " path: " + path + " url: " + url);
     if (url != null) {
       try {
         ctx.deploy(url);
       } catch (Exception e) {
         // just log error to know where is the cause of the
         // exception
         log.error("Error deploying resource: " + url);
         Framework.handleDevError(e);
         throw e;
       }
     } else {
       String message = "Unknown component '" + path + "' referenced by bundle '" + name + "'";
       log.error(message + ". Check the MANIFEST.MF");
       Framework.handleDevError(null);
       warnings.add(message);
     }
   }
 }
示例#3
0
 @Override
 public void unregisterContribution(
     Object contribution, String extensionPoint, ComponentInstance contributor) {
   if (contribution instanceof FlavorDescriptor) {
     FlavorDescriptor flavor = (FlavorDescriptor) contribution;
     flavorReg.removeContribution(flavor);
   } else if (contribution instanceof Resource) {
     Resource resource = (Resource) contribution;
     unregisterResource(resource);
   } else if (contribution instanceof SimpleStyle) {
     SimpleStyle style = (SimpleStyle) contribution;
     unregisterResource(getResourceFromStyle(style));
   } else if (contribution instanceof PageDescriptor) {
     PageDescriptor page = (PageDescriptor) contribution;
     if (page.hasResources() && !Framework.getRuntime().isShuttingDown()) {
       WebResourceManager wrm = Framework.getService(WebResourceManager.class);
       wrm.unregisterResourceBundle(page.getComputedResourceBundle());
     }
     pageReg.removeContribution(page);
   } else if (contribution instanceof NegotiationDescriptor) {
     NegotiationDescriptor neg = (NegotiationDescriptor) contribution;
     negReg.removeContribution(neg);
   } else {
     log.error(
         String.format(
             "Unknown contribution to the theme " + "styling service, extension point '%s': '%s",
             extensionPoint, contribution));
   }
 }
示例#4
0
 /** Creates a {@code Dialect} by connecting to the datasource to check what database is used. */
 public static Dialect createDialect(
     Connection connection, RepositoryDescriptor repositoryDescriptor) {
   DatabaseMetaData metadata;
   String databaseName;
   try {
     metadata = connection.getMetaData();
     databaseName = metadata.getDatabaseProductName();
   } catch (SQLException e) {
     throw new NuxeoException(e);
   }
   if (databaseName.contains("/")) {
     // DB2/LINUX, DB2/DARWIN, etc.
     databaseName = databaseName.substring(0, databaseName.indexOf('/'));
   }
   String dialectClassName = Framework.getProperty(DIALECT_CLASS);
   if (dialectClassName == null) {
     dialectClassName = Framework.getProperty(DIALECT_CLASS + '.' + databaseName.replace(" ", ""));
   }
   Class<? extends Dialect> dialectClass;
   if (dialectClassName == null) {
     dialectClass = DIALECTS.get(databaseName);
     if (dialectClass == null) {
       throw new NuxeoException("Unsupported database: " + databaseName);
     }
   } else {
     Class<?> klass;
     try {
       ClassLoader cl = Thread.currentThread().getContextClassLoader();
       klass = cl.loadClass(dialectClassName);
     } catch (ClassNotFoundException e) {
       throw new NuxeoException(e);
     }
     if (!Dialect.class.isAssignableFrom(klass)) {
       throw new NuxeoException("Not a Dialect: " + dialectClassName);
     }
     dialectClass = (Class<? extends Dialect>) klass;
   }
   Constructor<? extends Dialect> ctor;
   try {
     ctor = dialectClass.getConstructor(DatabaseMetaData.class, RepositoryDescriptor.class);
   } catch (ReflectiveOperationException e) {
     throw new NuxeoException("Bad constructor signature for: " + dialectClassName, e);
   }
   Dialect dialect;
   try {
     dialect = ctor.newInstance(metadata, repositoryDescriptor);
   } catch (InvocationTargetException e) {
     Throwable t = e.getTargetException();
     if (t instanceof NuxeoException) {
       throw (NuxeoException) t;
     } else {
       throw new NuxeoException(t);
     }
   } catch (ReflectiveOperationException e) {
     throw new NuxeoException("Cannot construct dialect: " + dialectClassName, e);
   }
   return dialect;
 }
示例#5
0
 /**
  * Makes sure there is no previous runtime hanging around.
  *
  * <p>This happens for instance if a previous test had errors in its <code>setUp()</code>, because
  * <code>tearDown()</code> has not been called.
  */
 protected void wipeRuntime() throws Exception {
   // Make sure there is no active runtime (this might happen if an
   // exception is raised during a previous setUp -> tearDown is not called
   // afterwards).
   runtime = null;
   if (Framework.getRuntime() != null) {
     Framework.shutdown();
   }
 }
示例#6
0
 public SQLSession(
     org.nuxeo.ecm.core.storage.sql.Session session, Repository repository, String sessionId) {
   this.session = session;
   this.repository = repository;
   Node rootNode = session.getRootNode();
   this.sessionId = sessionId;
   root = newDocument(rootNode);
   negativeAclAllowed = Framework.isBooleanPropertyTrue(ALLOW_NEGATIVE_ACL_PROPERTY);
   copyFindFreeNameDisabled = Framework.isBooleanPropertyTrue(COPY_FINDFREENAME_DISABLED_PROP);
 }
 protected DocumentRoute instantiateAndRun(
     CoreSession session, List<String> docIds, Map<String, Serializable> map) {
   DocumentRoutingService routing = Framework.getLocalService(DocumentRoutingService.class);
   DocumentRoute route = validate(routeDoc, session);
   // create instance and start
   String id =
       Framework.getLocalService(DocumentRoutingService.class)
           .createNewInstance(route.getDocument().getName(), docIds, map, session, true);
   return session.getDocument(new IdRef(id)).getAdapter(DocumentRoute.class);
 }
 public MultiDirectorySession(MultiDirectory directory) {
   directoryService = Framework.getService(DirectoryService.class);
   schemaManager = Framework.getLocalService(SchemaManager.class);
   this.directory = directory;
   descriptor = directory.getDescriptor();
   schemaName = descriptor.schemaName;
   schemaIdField = descriptor.idField;
   schemaPasswordField = descriptor.passwordField;
   permissions = descriptor.permissions;
 }
  @Test
  public void testPipeConnection() throws Exception {
    Framework.getProperties()
        .load(new FileInputStream(tc.getResource("jodPipe.properties").getFile()));
    ods = Framework.getLocalService(OOoManagerService.class);
    assertNotNull(ods);

    ods.startOOoManager();
    OfficeDocumentConverter converter = ods.getDocumentConverter();
    assertNotNull(converter);
  }
  @Override
  public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters)
      throws ConversionException {
    try {
      // Make sure the toThumbnail command is available
      CommandLineExecutorService cles = Framework.getLocalService(CommandLineExecutorService.class);
      CommandAvailability commandAvailability = cles.getCommandAvailability(THUMBNAIL_COMMAND);
      if (!commandAvailability.isAvailable()) {
        return null;
      }
      // get the input and output of the command
      Blob blob = blobHolder.getBlob();
      File inputFile = null;
      if (blob instanceof FileBlob) {
        inputFile = ((FileBlob) blob).getFile();
      } else if (blob instanceof SQLBlob) {
        StreamSource source = ((SQLBlob) blob).getBinary().getStreamSource();
        inputFile = ((FileSource) source).getFile();
      } else if (blob instanceof StreamingBlob) {
        StreamingBlob streamingBlob = ((StreamingBlob) blob);
        if (!streamingBlob.isPersistent()) {
          streamingBlob.persist();
        }
        StreamSource source = streamingBlob.getStreamSource();
        inputFile = ((FileSource) source).getFile();
      }
      if (inputFile == null) {
        return null;
      }
      CmdParameters params = new CmdParameters();
      File outputFile = File.createTempFile("nuxeoImageTarget", "." + "png");
      String size = THUMBNAIL_DEFAULT_SIZE;
      if (parameters != null) {
        if (parameters.containsKey(THUMBNAIL_SIZE_PARAMETER_NAME)) {
          size = (String) parameters.get(THUMBNAIL_SIZE_PARAMETER_NAME);
        }
      }
      params.addNamedParameter(THUMBNAIL_SIZE_PARAMETER_NAME, size);
      params.addNamedParameter("inputFilePath", inputFile);
      params.addNamedParameter("outputFilePath", outputFile);

      ExecResult res = cles.execCommand(THUMBNAIL_COMMAND, params);
      if (!res.isSuccessful()) {
        throw res.getError();
      }
      Blob targetBlob = new FileBlob(outputFile);
      Framework.trackFile(outputFile, targetBlob);
      return new SimpleCachableBlobHolder(targetBlob);
    } catch (CommandNotAvailable | IOException | ClientException | CommandException e) {
      throw new ConversionException("Thumbnail conversion failed", e);
    }
  }
 @Override
 @Before
 public void setUp() throws Exception {
   super.setUp();
   mailService = Framework.getService(MailService.class);
   assertNotNull(mailService);
   correspDocumentTypeService = Framework.getService(CaseManagementDocumentTypeService.class);
   assertNotNull(correspDocumentTypeService);
   String postType = correspDocumentTypeService.getCaseLinkType();
   assertNotNull(postType);
   incomingDocumentType = CorrespondenceConstants.IN_CORRESPONDENCE_DOCUMENT;
   openSession();
 }
示例#12
0
 /**
  * Creates a serializable blob from a stream, with filename and mimetype detection.
  *
  * <p>Creates an in-memory blob if data is under 64K, otherwise constructs a serializable FileBlob
  * which stores data in a temporary file on the hard disk.
  *
  * @param file the input stream holding data
  * @param filename the file name. Will be set on the blob and will used for mimetype detection.
  * @param mimeType the detected mimetype at upload. Can be null. Will be verified by the mimetype
  *     service.
  */
 public static Blob createSerializableBlob(InputStream file, String filename, String mimeType) {
   Blob blob = null;
   try {
     // persisting the blob makes it possible to read the binary content
     // of the request stream several times (mimetype sniffing, digest
     // computation, core binary storage)
     blob = StreamingBlob.createFromStream(file, mimeType).persist();
     // filename
     if (filename != null) {
       filename = getCleanFileName(filename);
     }
     blob.setFilename(filename);
     // mimetype detection
     MimetypeRegistry mimeService = Framework.getService(MimetypeRegistry.class);
     String detectedMimeType =
         mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob, null);
     if (detectedMimeType == null) {
       if (mimeType != null) {
         detectedMimeType = mimeType;
       } else {
         // default
         detectedMimeType = "application/octet-stream";
       }
     }
     blob.setMimeType(detectedMimeType);
   } catch (MimetypeDetectionException e) {
     log.error(String.format("could not fetch mimetype for file %s", filename), e);
   } catch (IOException e) {
     log.error(e);
   } catch (Exception e) {
     log.error(e);
   }
   return blob;
 }
示例#13
0
  protected void check(String layoutName, String lang) throws Exception {
    LayoutConversionContext ctx = new LayoutConversionContext(lang, null);
    LayoutDefinition layoutDef =
        service.getLayoutDefinition(WebLayoutManager.JSF_CATEGORY, layoutName);
    Layout layout =
        jsfService.getLayout(
            null, ctx, TEST_CATEGORY, layoutDef, BuiltinModes.VIEW, "currentDocument", null, false);
    String langFilePath = lang;
    if (langFilePath == null) {
      langFilePath = "nolang";
    }
    File file = Framework.createTempFile("layout-instance-export-" + langFilePath, ".json");
    FileOutputStream out = new FileOutputStream(file);
    JSONObject res = JSONLayoutExporter.exportToJson(layout);
    out.write(res.toString(2).getBytes(JSONLayoutExporter.ENCODED_VALUES_ENCODING));
    out.close();

    InputStream written = new FileInputStream(file);
    InputStream expected =
        new FileInputStream(
            FileUtils.getResourcePathFromContext(
                "layout-instance-export-" + langFilePath + ".json"));

    String expectedString = IOUtils.toString(expected, Charsets.UTF_8);
    String writtenString = IOUtils.toString(written, Charsets.UTF_8);
    // order of select options may depend on directory database => do not
    // check order of element by using the NON_EXTENSIBLE mode
    JSONAssert.assertEquals(expectedString, writtenString, JSONCompareMode.NON_EXTENSIBLE);
  }
  @Override
  protected void doIndexingWork(ElasticSearchIndexing esi, List<IndexingCommand> cmds) {
    if (cmds.isEmpty()) {
      return;
    }
    IndexingCommand cmd = cmds.get(0);
    DocumentModel doc = getDocument(cmd);
    if (doc == null) {
      return;
    }
    DocumentModelIterator iter = session.getChildrenIterator(doc.getRef());
    while (iter.hasNext()) {
      // Add a session save to process cache invalidation
      session.save();
      DocumentModel child = iter.next();

      IndexingCommand childCommand = cmd.clone(child);

      if (!esi.isAlreadyScheduled(childCommand)) {
        esi.indexNonRecursive(childCommand);
      }
      if (child.isFolder()) {
        ChildrenIndexingWorker subWorker = new ChildrenIndexingWorker(monitor, childCommand);
        WorkManager wm = Framework.getLocalService(WorkManager.class);
        wm.schedule(subWorker);
      }
    }
  }
 private UserWorkspaceService getUserWorkspaceService() {
   if (userWorkspaceService != null) {
     return userWorkspaceService;
   }
   userWorkspaceService = Framework.getLocalService(UserWorkspaceService.class);
   return userWorkspaceService;
 }
  protected boolean useTiling(Blob blob, DocumentModel dm) {
    Long width = Long.valueOf(0);
    Long height = Long.valueOf(0);

    if ("Picture".equals(dm.getType())) {
      try {
        PictureResourceAdapter adapter = dm.getAdapter(PictureResourceAdapter.class);
        String xpath = adapter.getViewXPath(ORIGINAL_JPEG_VIEW_NAME);
        if (xpath == null) {
          xpath = adapter.getViewXPath(ORIGINAL_VIEW_NAME);
          if (xpath == null) {
            xpath = adapter.getFirstViewXPath();
          }
        }

        width = (Long) dm.getPropertyValue(xpath + "width");
        height = (Long) dm.getPropertyValue(xpath + "height");
      } catch (ClientException e) {
        log.error("Failed to get picture dimensions", e);
      }
    } else {
      ImagingService imagingService = Framework.getLocalService(ImagingService.class);
      if (imagingService != null) {
        Map<String, Object> imageMetadata = imagingService.getImageMetadata(blob);
        width = ((Integer) imageMetadata.get(MetadataConstants.META_WIDTH)).longValue();
        height = ((Integer) imageMetadata.get(MetadataConstants.META_HEIGHT)).longValue();
      }
    }

    Integer widthThreshold =
        Integer.valueOf(PictureTilingComponent.getEnvValue("WidthThreshold", "1200"));
    Integer heightThreshold =
        Integer.valueOf(PictureTilingComponent.getEnvValue("HeightThreshold", "1200"));
    return width > widthThreshold || height > heightThreshold;
  }
示例#17
0
 @GET
 @Produces("application/json")
 @Path(value = "startDownloads")
 public String startDownloads(@QueryParam("pkgList") String pkgList) {
   if (RequestHelper.isInternalLink(getContext())) {
     if (pkgList != null) {
       String[] pkgs = pkgList.split("/");
       PackageManager pm = Framework.getLocalService(PackageManager.class);
       try {
         log.info("Starting download for packages " + Arrays.toString(pkgs));
         pm.download(Arrays.asList(pkgs));
       } catch (ConnectServerError e) {
         log.error(e, e);
       }
       // here we generate a fake progress report so that if some
       // download are very fast, they will still be visible on the
       // client side
       StringBuffer sb = new StringBuffer();
       sb.append("[");
       for (int i = 0; i < pkgs.length; i++) {
         if (i > 0) {
           sb.append(",");
         }
         sb.append("{ \"pkgid\" : ");
         sb.append("\"" + pkgs[i] + "\",");
         sb.append(" \"progress\" : 0}");
       }
       sb.append("]");
       return sb.toString();
     }
   }
   return "[]";
 }
 /** @throws Exception */
 private static LabsThemeManager getThemeService() {
   try {
     return Framework.getService(LabsThemeManager.class);
   } catch (Exception e) {
     return null;
   }
 }
示例#19
0
  /**
   * Called by the theme negotiation module.
   *
   * @return the local theme associated to the current space (workspace, section, ...) as a
   *     'theme/page' string. Return null otherwise.
   */
  public String getOutcome(Object context) {
    Boolean useOldThemeConf =
        Boolean.valueOf(Framework.getProperty(LocalThemeConfig.OLD_THEME_CONFIGURATION_PROPERTY));
    if (Boolean.FALSE.equals(useOldThemeConf)) {
      return null;
    }

    DocumentModel currentSuperSpace = (DocumentModel) Component.getInstance("currentSuperSpace");
    if (currentSuperSpace == null) {
      return null;
    }

    // Get the placeful local theme configuration for the current
    // workspace.
    LocalThemeConfig localThemeConfig = LocalThemeHelper.getLocalThemeConfig(currentSuperSpace);
    if (localThemeConfig == null) {
      return null;
    }

    // Extract the page path
    String path = localThemeConfig.computePagePath();
    if (path == null) {
      return null;
    }

    // Look up the page
    PageElement page = Manager.getThemeManager().getPageByPath(path);
    if (page != null) {
      return path;
    }
    return null;
  }
 public static final List<LabsSite> getTemplateSites() throws ClientException {
   SiteManager sm;
   List<LabsSite> adaptersList = new ArrayList<LabsSite>();
   try {
     sm = Framework.getService(SiteManager.class);
   } catch (Exception e) {
     return adaptersList;
   }
   StringBuilder query = new StringBuilder();
   CoreSession session = getCoreSession();
   query
       .append("SELECT * FROM ")
       .append(Docs.SITE.type())
       .append(" WHERE ")
       .append(NXQL.ECM_LIFECYCLESTATE)
       .append(" = '")
       .append(State.PUBLISH.getState())
       .append("'")
       .append(" AND ")
       .append(NXQL.ECM_PATH)
       .append(" STARTSWITH '")
       .append(sm.getSiteRoot(session).getPathAsString().replace("'", "\\'"))
       .append("'")
       .append(" AND ")
       .append(NXQL.ECM_MIXINTYPE)
       .append("='")
       .append(LabsSiteConstants.FacetNames.LABS_ELEMENT_TEMPLATE)
       .append("'");
   DocumentModelList list = session.query(query.toString());
   for (DocumentModel site : list) {
     adaptersList.add(Tools.getAdapter(LabsSite.class, site, session));
   }
   return adaptersList;
 }
 public static final SiteManager getSiteManager() {
   try {
     return Framework.getService(SiteManager.class);
   } catch (Exception e) {
     return null;
   }
 }
示例#22
0
  @Override
  public File getBundleFile(Bundle bundle) {
    File file;
    String location = bundle.getLocation();
    String vendor = Framework.getProperty(Constants.FRAMEWORK_VENDOR);
    String name = bundle.getSymbolicName();

    if ("Eclipse".equals(vendor)) { // equinox framework
      log.debug("getBundleFile (Eclipse): " + name + "->" + location);
      return getEclipseBundleFileUsingReflection(bundle);
    } else if (location.startsWith("file:")) { // nuxeo osgi adapter
      try {
        file = FileUtils.urlToFile(location);
      } catch (MalformedURLException e) {
        log.error(
            "getBundleFile: Unable to create " + " for bundle: " + name + " as URI: " + location);
        return null;
      }
    } else { // may be a file path - this happens when using
      // JarFileBundle (for ex. in nxshell)
      file = new File(location);
    }
    if (file != null && file.exists()) {
      log.debug("getBundleFile: " + name + " bound to file: " + file);
      return file;
    } else {
      log.debug("getBundleFile: " + name + " cannot bind to nonexistent file: " + file);
      return null;
    }
  }
示例#23
0
 @Test
 public void testService() {
   PreviewAdapterManager pam = Framework.getLocalService(PreviewAdapterManager.class);
   assertNotNull(pam);
   MimeTypePreviewer previewer = pam.getPreviewer("text/html");
   assertNotNull(previewer);
 }
示例#24
0
  // "readonly" meaningful for proxies and versions, used for import
  private Document newDocument(Node node, boolean readonly) {
    if (node == null) {
      // root's parent
      return null;
    }

    Node targetNode = null;
    String typeName = node.getPrimaryType();
    if (node.isProxy()) {
      Serializable targetId = node.getSimpleProperty(Model.PROXY_TARGET_PROP).getValue();
      if (targetId == null) {
        throw new NoSuchDocumentException("Proxy has null target");
      }
      targetNode = session.getNodeById(targetId);
      typeName = targetNode.getPrimaryType();
    }
    SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class);
    DocumentType type = schemaManager.getDocumentType(typeName);
    if (type == null) {
      throw new NoSuchDocumentException("Unknown document type: " + typeName);
    }

    if (node.isProxy()) {
      // proxy seen as a normal document
      Document proxy = new SQLDocumentLive(node, type, this, false);
      Document target = newDocument(targetNode, readonly);
      return new SQLDocumentProxy(proxy, target);
    } else if (node.isVersion()) {
      return new SQLDocumentVersion(node, type, this, readonly);
    } else {
      return new SQLDocumentLive(node, type, this, false);
    }
  }
示例#25
0
  protected void check(LayoutDefinition layoutDef, String lang) throws Exception {
    LayoutConversionContext ctx = new LayoutConversionContext(lang, null);
    List<LayoutDefinitionConverter> layoutConverters = service.getLayoutConverters(TEST_CATEGORY);
    for (LayoutDefinitionConverter conv : layoutConverters) {
      layoutDef = conv.getLayoutDefinition(layoutDef, ctx);
    }
    List<WidgetDefinitionConverter> widgetConverters = service.getWidgetConverters(TEST_CATEGORY);

    String langFilePath = lang;
    if (langFilePath == null) {
      langFilePath = "nolang";
    }
    File file = Framework.createTempFile("layout-export-" + langFilePath, ".json");
    FileOutputStream out = new FileOutputStream(file);
    JSONLayoutExporter.export(WebLayoutManager.JSF_CATEGORY, layoutDef, ctx, widgetConverters, out);
    out.close();

    InputStream written = new FileInputStream(file);
    InputStream expected =
        new FileInputStream(
            FileUtils.getResourcePathFromContext("layout-export-" + langFilePath + ".json"));

    String expectedString = IOUtils.toString(expected, Charsets.UTF_8);
    String writtenString = IOUtils.toString(written, Charsets.UTF_8);
    // order of select options may depend on directory database => do not
    // check order of element by using the NON_EXTENSIBLE mode
    JSONAssert.assertEquals(expectedString, writtenString, JSONCompareMode.NON_EXTENSIBLE);
  }
 protected String getJSWrapper(boolean refresh) throws OperationException {
   if (jsWrapper == null || refresh) {
     StringBuffer sb = new StringBuffer();
     AutomationService as = Framework.getService(AutomationService.class);
     Map<String, List<String>> opMap = new HashMap<>();
     List<String> flatOps = new ArrayList<>();
     List<String> ids = new ArrayList<>();
     for (OperationType op : as.getOperations()) {
       ids.add(op.getId());
       if (op.getAliases() != null) {
         Collections.addAll(ids, op.getAliases());
       }
     }
     // Create js object related to operation categories
     for (String id : ids) {
       parseAutomationIDSForScripting(opMap, flatOps, id);
     }
     for (String obName : opMap.keySet()) {
       List<String> ops = opMap.get(obName);
       sb.append("\nvar ").append(obName).append("={};");
       for (String opId : ops) {
         generateFunction(sb, opId);
       }
     }
     for (String opId : flatOps) {
       generateFlatFunction(sb, opId);
     }
     jsWrapper = sb.toString();
   }
   return jsWrapper;
 }
 public NuxeoPrincipal getNuxeoPrincipal(String username) {
   UserManager userManager = Framework.getLocalService(UserManager.class);
   if (userManager == null) {
     return null;
   }
   return userManager.getPrincipal(username);
 }
示例#28
0
文件: Site.java 项目: nuxeo/lm-labs
 private SiteManager getSiteManager() {
   try {
     return Framework.getService(SiteManager.class);
   } catch (Exception e) {
     return null;
   }
 }
  @Test
  public void testAnyToPDFConverter() throws Exception {
    ConversionService cs = Framework.getLocalService(ConversionService.class);
    ConverterCheckResult check = cs.isConverterAvailable("any2pdf");
    assertNotNull(check);
    if (!check.isAvailable()) {
      log.warn("Skipping JOD based converter tests since OOo is not installed");
      log.warn("  converter check output : " + check.getInstallationMessage());
      log.warn("  converter check output : " + check.getErrorMessage());
      return;
    }

    doTestPDFConverter("text/html", "hello.html");
    //        doTestPDFConverter("text/xml", "hello.xml");
    doTestPDFConverter("application/vnd.ms-excel", "hello.xls");
    doTestPDFConverter("application/vnd.sun.xml.writer", "hello.sxw");
    doTestPDFConverter("application/vnd.oasis.opendocument.text", "hello.odt");
    doTestPDFConverter("application/vnd.sun.xml.calc", "hello.sxc");
    doTestPDFConverter("application/vnd.oasis.opendocument.spreadsheet", "hello.ods");
    doTestPDFConverter("application/vnd.sun.xml.impress", "hello.sxi");
    doTestPDFConverter("application/vnd.oasis.opendocument.presentation", "hello.odp");

    doTestPDFConverter(
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "hello.docx");
    doTestPDFConverter(
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "hello.xlsx");
    doTestPDFConverter(
        "application/vnd.openxmlformats-officedocument.presentationml.presentation", "hello.pptx");
  }
  @Override
  public List<ActivityMessage> getCurrentPage() {
    if (pageMiniMessages == null) {
      pageMiniMessages = new ArrayList<ActivityMessage>();
      long pageSize = getMinMaxPageSize();

      MiniMessageService miniMessageService = Framework.getLocalService(MiniMessageService.class);
      String streamType = getStreamType();
      if (FOR_ACTOR_STREAM_TYPE.equals(streamType)) {
        pageMiniMessages.addAll(
            miniMessageService
                .getMiniMessageActivitiesFor(
                    getActor(), getRelationshipKind(), getCurrentPageOffset(), pageSize)
                .toActivityMessages(getLocale()));
      } else if (FROM_ACTOR_STREAM_TYPE.equals(streamType)) {
        pageMiniMessages.addAll(
            miniMessageService
                .getMiniMessageActivitiesFrom(getActor(), getCurrentPageOffset(), pageSize)
                .toActivityMessages(getLocale()));
      } else {
        log.error("Unknown stream type: " + streamType);
      }
      nextOffset = offset + pageMiniMessages.size();
      setResultsCount(UNKNOWN_SIZE_AFTER_QUERY);
    }
    return pageMiniMessages;
  }