Esempio n. 1
0
 public void restoreLocation(String cmd) {
   CommandExecutor cmdExe = new CommandExecutor(this);
   cmdExe.execute(cmd);
   if (linkedMode) {
     broadcastLocation();
   }
 }
Esempio n. 2
0
 private <TRequest> ClientCommandExecutor createExecutor(
     Membership.Member member, Command<TRequest> command) {
   CommandExecutor commandHandler = null;
   for (CommandExecutor ch : commandHandlers) {
     if (ch.canHandle(command.getType())) commandHandler = ch;
   }
   return new UdpClientCommandExecutor<>(member, command, commandHandler, logger);
 }
  @Test
  public final void injectCommand() throws Exception {
    final CommandExecutor ex = new CommandExecutor();

    ex.registerObserver(
        new IObserveUndoRedo() {

          @Override
          public void undoPossibleChanged(final boolean isUndoPossible) {
            CommandExecutorTest.this.observatorWasNotifiedUndoable = true;
          }

          @Override
          public void redoPossibleChanged(final boolean isRedoPossible) {
            CommandExecutorTest.this.observatorWasNotifiedRedoable = true;
          }
        });

    ex.executeCommand(
        new ICommand() {

          @Override
          public void undo() throws Exception {
            CommandExecutorTest.this.didUndo = true;
          }

          @Override
          public boolean isUndoable() {
            return true;
          }

          @Override
          public Object getReturnValue() {
            return "YIEAH!";
          }

          @Override
          public String getDescription() {
            return "Just a test command";
          }

          @Override
          public void execute() throws Exception {
            CommandExecutorTest.this.didExecute = true;
          }
        });
    assertTrue("Command was executed", this.didExecute);
    assertTrue("Observer was notified about undoable action", this.observatorWasNotifiedUndoable);
    this.observatorWasNotifiedUndoable = false;
    ex.undoLastCommand();
    assertTrue("Command was undone", this.didUndo);
    assertTrue("Observer was notified about redoable action", this.observatorWasNotifiedRedoable);
    this.didExecute = false;
    ex.redoLastCommand();
    assertTrue("Command was redone", this.didExecute);
    assertTrue("Observer was notified about undoable action", this.observatorWasNotifiedUndoable);
  }
Esempio n. 4
0
 public static void main(String[] args) {
   CommandExecutor executor = new CommandExecutorProxy("Asia", "wrong_pwd");
   try {
     executor.runCommand("ls -ltr");
     executor.runCommand(" rm -rf abc.pdf");
   } catch (Exception e) {
     System.out.println("Exception Message::" + e.getMessage());
   }
 }
  /**
   * Start the Android Emulator with the specified options.
   *
   * @throws org.apache.maven.plugin.MojoExecutionException
   * @see #emulatorAvd
   * @see #emulatorWait
   * @see #emulatorOptions
   */
  protected void startAndroidEmulator() throws MojoExecutionException {
    parseParameters();

    CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
    executor.setLogger(this.getLog());

    try {
      String filename;
      if (isWindows()) {
        filename = writeEmulatorStartScriptWindows();
      } else {
        filename = writeEmulatorStartScriptUnix();
      }

      final AndroidDebugBridge androidDebugBridge = initAndroidDebugBridge();
      if (androidDebugBridge.isConnected()) {
        List<IDevice> devices = Arrays.asList(androidDebugBridge.getDevices());
        int numberOfDevices = devices.size();
        getLog()
            .info("Found " + numberOfDevices + " devices connected with the Android Debug Bridge");

        IDevice existingEmulator = null;

        for (IDevice device : devices) {
          if (device.isEmulator()) {
            if (isExistingEmulator(device)) {
              existingEmulator = device;
              break;
            }
          }
        }

        if (existingEmulator == null) {
          getLog().info(START_EMULATOR_MSG + filename);
          executor.executeCommand(filename, null);

          getLog().info(START_EMULATOR_WAIT_MSG + parsedWait);
          // wait for the emulator to start up
          Thread.sleep(new Long(parsedWait));
        } else {
          getLog()
              .info(
                  String.format(
                      "Emulator already running [Serial No: '%s', AVD Name '%s']. Skipping start and wait.",
                      existingEmulator.getSerialNumber(), existingEmulator.getAvdName()));
        }
      }
    } catch (Exception e) {
      throw new MojoExecutionException("", e);
    }
  }
Esempio n. 6
0
  /**
   * The method does the following:
   *
   * <p>1.in case of none atomic command
   *
   * <p>- execute the command using the command executor
   *
   * <p>- notify all waiting thread about the command execution
   *
   * <p>2.in case of atomic command
   *
   * <p>- execute the command using the command executor
   *
   * <p>- notify all waiting thread about the command execution only
   *
   * <p>if the current command is the last element in the atomic command
   *
   * @param modelCommand
   * @throws PlanckDBException
   */
  @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
  public void doJobs(final Command modelCommand) throws PlanckDBException {
    boolean consume = true;
    if (modelCommand.getTransaction() == TRUE
        && modelCommand.getSessionId() == sessionMetaData.getSessionId()) {
      consume = false;
    }
    if (consume) {
      commandExecutor.consume(modelCommand);
    }
    if (atomicContainer.isPartOfAtomicCommand(modelCommand)) {
      Command rootCommand = atomicContainer.update(modelCommand);
      if (rootCommand != null) {
        synchronized (rootCommand) {
          rootCommand.notifyAll();
        }
      }

    } else {
      synchronized (modelCommand) {
        modelCommand.notifyAll();
      }
    }

    // log.debug("message done version : "+modelCommand.getVersion()+" id
    // "+modelCommand.getEntityId());
  }
Esempio n. 7
0
 public void listPoints() throws Exception {
   ListPointsCommand command = new ListPointsCommand();
   command = executor.executeCommand(command);
   for (Point point : command.getPoints()) {
     System.out.println("\t" + point);
   }
 }
  @Override
  public void deleteFile(SrvSession sess, TreeConnection tree, String name) throws IOException {
    if (logger.isDebugEnabled()) {
      logger.debug("deleteFile name:" + name);
    }
    try {
      ContentContext tctx = (ContentContext) tree.getContext();
      NodeRef rootNode = tctx.getRootNode();

      DriverState driverState = getDriverState(sess);

      String[] paths = FileName.splitPath(name);
      String folder = paths[0];
      String file = paths[1];

      EvaluatorContext ctx = getEvaluatorContext(driverState, folder);

      Operation o = new DeleteFileOperation(file, rootNode, name);
      Command c = ruleEvaluator.evaluate(ctx, o);
      commandExecutor.execute(sess, tree, c);

      releaseEvaluatorContextIfEmpty(driverState, ctx, folder);
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ade) {
      throw new AccessDeniedException("Unable to delete file " + name, ade);
    }
  } // End of deleteFile
  /**
   * Extracts the package name from an apk file.
   *
   * @param apkFile apk file to extract package name from.
   * @return the package name from inside the apk file.
   */
  protected String extractPackageNameFromApk(File apkFile) throws MojoExecutionException {
    CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
    executor.setLogger(this.getLog());
    executor.setCaptureStdOut(true);
    executor.setCaptureStdErr(true);

    AaptCommandBuilder commandBuilder =
        AaptCommandBuilder.dump(getLog())
            .xmlTree()
            .setPathToApk(apkFile.getAbsolutePath())
            .addAssetFile("AndroidManifest.xml");

    getLog().info(getAndroidSdk().getAaptPath() + " " + commandBuilder.toString());
    try {
      executor.executeCommand(getAndroidSdk().getAaptPath(), commandBuilder.build(), false);
      final String xmlTree = executor.getStandardOut();
      return extractPackageNameFromAndroidManifestXmlTree(xmlTree);
    } catch (ExecutionException e) {
      throw new MojoExecutionException(
          "Error while trying to figure out package name from inside apk file " + apkFile);
    } finally {
      String errout = executor.getStandardError();
      if ((errout != null) && (errout.trim().length() > 0)) {
        getLog().error(errout);
      }
    }
  }
Esempio n. 10
0
 public void removePoint(Point point) throws Exception {
   RemovePointCommand command = new RemovePointCommand(point);
   command = executor.executeCommand(command);
   if (command.isOk()) {
     System.out.println("Punto borrado.");
   } else {
     System.out.println("Punto no borrado.");
   }
 }
Esempio n. 11
0
 public void addPoint(Point point) throws Exception {
   AddPointCommand command = new AddPointCommand(point);
   command = executor.executeCommand(command);
   if (command.isOk()) {
     System.out.println("Punto añadido.");
   } else {
     System.out.println("Punto no añadido.");
   }
 }
Esempio n. 12
0
  public void containsPoint(Point point) throws Exception {
    ContainsPointCommand command = new ContainsPointCommand(point);
    command = executor.executeCommand(command);

    if (command.isContains()) {
      System.out.println("El servidor contiene el punto " + point);
    } else {
      System.out.println("El servidor no contiene el punto " + point);
    }
  }
 /**
  * Extracts the package name from an apk file.
  *
  * @param apkFile apk file to extract package name from.
  * @return the package name from inside the apk file.
  */
 protected String extractPackageNameFromApk(File apkFile) throws MojoExecutionException {
   CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
   executor.setLogger(this.getLog());
   List<String> commands = new ArrayList<String>();
   commands.add("dump");
   commands.add("xmltree");
   commands.add(apkFile.getAbsolutePath());
   commands.add("AndroidManifest.xml");
   getLog().info(getAndroidSdk().getPathForTool("aapt") + " " + commands.toString());
   try {
     executor.executeCommand(getAndroidSdk().getPathForTool("aapt"), commands, true);
     final String xmlTree = executor.getStandardOut();
     return extractPackageNameFromAndroidManifestXmlTree(xmlTree);
   } catch (ExecutionException e) {
     throw new MojoExecutionException(
         "Error while trying to figure out package name from inside apk file " + apkFile);
   } finally {
     getLog().error(executor.getStandardError());
   }
 }
  @Override
  public void terminate() {
    boolean wasTerminated;

    synchronized (this) {
      wasTerminated = terminated;
      terminated = true;
    }

    if (!wasTerminated) {
      partitionerFinished();
      documentListener.deregisterListener();

      commandExecutor.terminate();
      interpreter.interrupt();
      interpreter.terminate();
    }
  }
  private <C extends Command<R>, R extends Serializable> void registerExecutor(
      final NodeContext nodeContext, final CommandExecutor<C, R> executor, ZNode node) {
    final ZNode executorNode =
        node.createChild(znode().withPath(nodeNameOf(executor.getQualifier())));
    final ZNode queueNode = executorNode.createChild(znode().withPath("queue"));
    executorNode.createChild(znode().withPath("result"));

    log.debug("Created znodes for executor {}", executorNode.getPath());

    queueNode.addChildrenWatcher(
        new Watcher() {
          @Override
          public void process(WatchedEvent event) {
            if (event.getType() != Event.EventType.NodeChildrenChanged) {
              return;
            }

            synchronized (lock) {
              if (log.isDebugEnabled()) {
                log.debug(
                    "Children changed {} event type {}", queueNode.getPath(), event.getType());
              }

              List<QueueEntry<C, R>> entries = getEntries(queueNode, this);

              for (final QueueEntry<C, R> entry : entries) {
                Runnable run =
                    new Runnable() {

                      @Override
                      public void run() {
                        executeCommand(executor, executorNode, entry, nodeContext);
                      }
                    };

                ZookeeperCoordinator.this.executor.execute(run);
              }
            }
          }
        });
  }
  private static <C extends Command<R>, R extends Serializable> void executeCommand(
      CommandExecutor<C, R> executor,
      ZNode executorNode,
      final QueueEntry<C, R> entry,
      final NodeContext nodeContext) {
    String relativePath = entry.getResultPath().substring(executorNode.getPath().length() + 1);
    final ZNode output = executorNode.child(relativePath);
    final NodeCommandExecutionListener<C> listener = entry.getListener();

    try {
      C command = entry.getCommand();
      listener.onCommandExecutionStarted(command, nodeContext);
      R result = executor.execute(command, nodeContext);
      log.debug("Command {} executed", command);
      listener.onCommandExecuted(command);
      output.setObject(CommandExecutionResult.success(result));
    } catch (Throwable throwable) {
      // todo add fail event
      log.error("error during task execution", throwable);
      output.setObject(CommandExecutionResult.fail(throwable));
    }
  }
Esempio n. 17
0
  protected Response execute(String driverCommand, Map<String, ?> parameters) {
    Command command = new Command(sessionId, driverCommand, parameters);
    Response response;

    long start = System.currentTimeMillis();
    String currentName = Thread.currentThread().getName();
    Thread.currentThread()
        .setName("Forwarding " + driverCommand + " on session " + sessionId + " to remote");
    try {

      log(sessionId, command.getName(), command, When.BEFORE);
      response = executor.execute(command);
      log(sessionId, command.getName(), command, When.AFTER);

      if (response == null) {
        return null;
      }

      // Unwrap the response value by converting any JSON objects of the form
      // {"ELEMENT": id} to RemoteWebElements.
      Object value = converter.apply(response.getValue());
      response.setValue(value);
    } catch (SessionTerminatedException e) {
      throw e;
    } catch (Exception e) {
      log(sessionId, command.getName(), command, When.EXCEPTION);
      String errorMessage = "Error communicating with the remote browser. " + "It may have died.";
      if (driverCommand.equals(DriverCommand.NEW_SESSION)) {
        errorMessage =
            "Could not start a new session. Possible causes are "
                + "invalid address of the remote server or browser start-up failure.";
      }
      throw new UnreachableBrowserException(errorMessage, e);
    } finally {
      Thread.currentThread().setName(currentName);
    }

    return errorHandler.throwIfResponseFailed(response, System.currentTimeMillis() - start);
  }
 /**
  * Undeploys an apk, specified by package name, from a connected emulator or usb device.
  *
  * @param packageName the package name to undeploy.
  * @param deleteDataAndCacheDirectoriesOnDevice <code>true</code> to delete the application's data
  *     and cache directories on the device, <code>false</code> to keep them.
  * @return <code>true</code> if successfully undeployed, <code>false</code> otherwise.
  */
 protected boolean undeployApk(String packageName, boolean deleteDataAndCacheDirectoriesOnDevice)
     throws MojoExecutionException {
   CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
   executor.setLogger(this.getLog());
   List<String> commands = new ArrayList<String>();
   commands.add("uninstall");
   if (!deleteDataAndCacheDirectoriesOnDevice) {
     commands.add("-k"); // ('-k' means keep the data and cache directories)
   }
   commands.add(packageName);
   getLog().info(getAndroidSdk().getPathForTool("adb") + " " + commands.toString());
   try {
     executor.executeCommand(getAndroidSdk().getPathForTool("adb"), commands, false);
     getLog().debug(executor.getStandardOut());
     getLog().debug(executor.getStandardError());
     return true;
   } catch (ExecutionException e) {
     getLog().error(executor.getStandardOut());
     getLog().error(executor.getStandardError());
     return false;
   }
 }
  @Override
  public void closeFile(SrvSession sess, TreeConnection tree, NetworkFile param)
      throws IOException {
    if (logger.isDebugEnabled()) {
      logger.debug("closeFile:" + param.getFullName());
    }

    ContentContext tctx = (ContentContext) tree.getContext();
    NodeRef rootNode = tctx.getRootNode();

    DriverState driverState = getDriverState(sess);

    String[] paths = FileName.splitPath(param.getFullName());
    String folder = paths[0];
    String file = paths[1];

    try {
      EvaluatorContext ctx = getEvaluatorContext(driverState, folder);

      Operation o =
          new CloseFileOperation(
              file,
              param,
              rootNode,
              param.getFullName(),
              param.hasDeleteOnClose(),
              param.isForce());
      Command c = ruleEvaluator.evaluate(ctx, o);

      commandExecutor.execute(sess, tree, c);

      releaseEvaluatorContextIfEmpty(driverState, ctx, folder);
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ade) {
      throw new AccessDeniedException("Unable to close file " + param.getFullName(), ade);
    }
  }
  /**
   * Deploys an apk file to a connected emulator or usb device.
   *
   * @param apkFile the file to deploy
   * @throws MojoExecutionException If there is a problem deploying the apk file.
   */
  protected void deployApk(File apkFile) throws MojoExecutionException {
    CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
    executor.setLogger(this.getLog());
    List<String> commands = new ArrayList<String>();

    // Check if a specific device should be used
    if (StringUtils.isNotBlank(device)) {
      if ("usb".equals(device)) {
        commands.add("-d");
      } else if ("emulator".equals(device)) {
        commands.add("-e");
      } else {
        commands.add("-s");
        commands.add(device);
      }
    }

    commands.add("install");
    commands.add("-r");
    commands.add(apkFile.getAbsolutePath());
    getLog().info(getAndroidSdk().getPathForTool("adb") + " " + commands.toString());
    try {
      executor.executeCommand(getAndroidSdk().getPathForTool("adb"), commands, false);
      final String standardOut = executor.getStandardOut();
      if (standardOut != null && standardOut.contains("Failure")) {
        throw new MojoExecutionException(
            "Error deploying "
                + apkFile
                + " to device. You might want to add command line parameter -Dandroid.undeployBeforeDeploy=true or add plugin configuration tag <undeployBeforeDeploy>true</undeployBeforeDeploy>\n"
                + standardOut);
      }
    } catch (ExecutionException e) {
      getLog().error(executor.getStandardOut());
      getLog().error(executor.getStandardError());
      throw new MojoExecutionException("Error deploying " + apkFile + " to device.", e);
    }
  }
Esempio n. 21
0
 @Override
 public void feed(JsonEvent logEvent) {
   CommandExecutor exec = new CommandExecutor(this, logEvent);
   exec.run(workingDirectory, commandTemplate);
 }
Esempio n. 22
0
 public void removeModelChangedListener(NodeModelChangedListener nodeModelChangedListener) {
   commandExecutor.removeModelChangedListener(nodeModelChangedListener);
 }
Esempio n. 23
0
 public void addModelChangedListener(NodeModelChangedListener nodeModelChangedListener) {
   commandExecutor.addModelChangedListener(nodeModelChangedListener);
 }
  @Override
  public NetworkFile createFile(SrvSession sess, TreeConnection tree, FileOpenParams params)
      throws IOException {
    try {
      int attr = params.getAttributes();
      if (logger.isDebugEnabled()) {
        int sharedAccess = params.getSharedAccess();
        String strSharedAccess = SharingMode.getSharingModeAsString(sharedAccess);

        logger.debug(
            "createFile:"
                + params.getPath()
                + ", isDirectory: "
                + params.isDirectory()
                + ", isStream: "
                + params.isStream()
                + ", readOnlyAccess: "
                + params.isReadOnlyAccess()
                + ", readWriteAccess: "
                + params.isReadWriteAccess()
                + ", writeOnlyAccess:"
                + params.isWriteOnlyAccess()
                + ", attributesOnlyAccess:"
                + params.isAttributesOnlyAccess()
                + ", sequentialAccessOnly:"
                + params.isSequentialAccessOnly()
                + ", requestBatchOpLock:"
                + params.requestBatchOpLock()
                + ", requestExclusiveOpLock:"
                + params.requestExclusiveOpLock()
                + ", isDeleteOnClose:"
                + params.isDeleteOnClose()
                + ", sharedAccess: "
                + strSharedAccess
                + ", allocationSize: "
                + params.getAllocationSize()
                + ", isHidden:"
                + FileAttribute.isHidden(attr)
                + ", isSystem:"
                + FileAttribute.isSystem(attr));
      }

      long creationDateTime = params.getCreationDateTime();
      if (creationDateTime != 0) {
        logger.debug("creationDateTime is set:" + new Date(creationDateTime));
      }

      ContentContext tctx = (ContentContext) tree.getContext();
      NodeRef rootNode = tctx.getRootNode();

      String[] paths = FileName.splitPath(params.getPath());
      String folder = paths[0];
      String file = paths[1];

      DriverState driverState = getDriverState(sess);
      EvaluatorContext ctx = getEvaluatorContext(driverState, folder);

      Operation o =
          new CreateFileOperation(
              file,
              rootNode,
              params.getPath(),
              params.getAllocationSize(),
              FileAttribute.isHidden(attr));
      Command c = ruleEvaluator.evaluate(ctx, o);

      Object ret = commandExecutor.execute(sess, tree, c);

      if (ret != null && ret instanceof NetworkFile) {
        return (NetworkFile) ret;
      } else {
        // Error - contact broken
        logger.error(
            "contract broken - NetworkFile not returned. " + ret == null
                ? "Return value is null"
                : ret);
        return null;
      }
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ade) {
      throw new AccessDeniedException("Unable to create file " + params.getPath(), ade);
    }
  }
  @Override
  public void registerNode(
      NodeContext nodeContext, Set<Worker> workers, final StatusChangeListener listener)
      throws CoordinatorException {
    log.info("Going to register node {} with {} workers", nodeContext.getId(), workers.size());

    ZNode typeNode = rootNode.child(CoordinationUtil.nodeNameOf(nodeContext.getId().getType()));
    ZNode node = typeNode.createChild(znode().withPath(nodeContext.getId().getIdentifier()));

    Set<CommandExecutor<?, ?>> executors = Sets.newHashSet();
    Set<Qualifier<?>> qualifiers = Sets.newHashSet();

    for (Worker worker : workers) {
      for (CommandExecutor<?, ?> executor : worker.getExecutors()) {
        Qualifier<?> qualifier = executor.getQualifier();
        if (qualifiers.contains(qualifier)) {
          throw new CoordinatorException(
              "Executor for qualifier " + qualifier + " is already registered");
        }

        executors.add(executor);
      }
    }

    for (CommandExecutor<?, ?> executor : executors) {
      registerExecutor(nodeContext, executor, node);
    }

    rootNode.addNodeWatcher(
        new Watcher() {
          @Override
          public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.Disconnected) {
              listener.onCoordinatorDisconnected();
            }

            if (event.getState() == Event.KeeperState.SyncConnected) {
              listener.onCoordinatorConnected();
            }
          }
        });

    ZNode statuses = rootNode.child(CoordinationUtil.STATUSES_NODE_NAME);

    statuses.createChild(znode().ephemeralSequential().withDataObject(nodeContext.getId()));

    Lock lock = new ReentrantLock();

    lock.lock();
    try {
      Collection<NodeId> nodeIds = Sets.newHashSet();
      StatusWatcher statusWatcher = new StatusWatcher(statuses, lock, nodeIds, listener);
      List<ZNode> nodes = statuses.children(statusWatcher);
      for (ZNode zNode : nodes) {
        nodeIds.add(zNode.getObject(NodeId.class));
      }
    } finally {
      lock.unlock();
    }

    node.createChild(znode().withPath(CoordinationUtil.AVAILABLE_NODE_NAME));
  }
  @Override
  public void renameFile(SrvSession sess, TreeConnection tree, String oldPath, String newPath)
      throws IOException {
    ContentContext tctx = (ContentContext) tree.getContext();
    NodeRef rootNode = tctx.getRootNode();

    if (logger.isDebugEnabled()) {
      logger.debug("renameFile oldPath:" + oldPath + ", newPath:" + newPath);
    }

    DriverState driverState = getDriverState(sess);

    // Is this a rename within the same folder or a move between folders?

    String[] paths = FileName.splitPath(oldPath);
    String oldFolder = paths[0];
    String oldFile = paths[1];

    paths = FileName.splitPath(newPath);
    String newFolder = paths[0];
    String newFile = paths[1];

    try {
      if (oldFolder.equalsIgnoreCase(newFolder)) {
        logger.debug("renameFileCommand - is a rename within the same folder");

        EvaluatorContext ctx = getEvaluatorContext(driverState, oldFolder);

        Operation o = new RenameFileOperation(oldFile, newFile, oldPath, newPath, rootNode);
        Command c = ruleEvaluator.evaluate(ctx, o);
        commandExecutor.execute(sess, tree, c);

        ruleEvaluator.notifyRename(ctx, o, c);

        releaseEvaluatorContextIfEmpty(driverState, ctx, oldFolder);

      } else {
        logger.debug("moveFileCommand - move between folders");

        Operation o = new MoveFileOperation(oldFile, newFile, oldPath, newPath, rootNode);

        /*
         * Note: At the moment we only have move scenarios for the destination folder - so
         * we only need to evaluate against a single (destination) context/folder.
         * This will require re-design as and when we need to have scenarios for the source/folder
         */

        // EvaluatorContext ctx1 = getEvaluatorContext(driverState, oldFolder);
        EvaluatorContext ctx2 = getEvaluatorContext(driverState, newFolder);

        Command c = ruleEvaluator.evaluate(ctx2, o);

        commandExecutor.execute(sess, tree, c);

        releaseEvaluatorContextIfEmpty(driverState, ctx2, newFolder);

        //  diskInterface.renameFile(sess, tree, oldPath, newPath);

      }
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ade) {
      throw new AccessDeniedException("Unable to rename file file " + oldPath, ade);
    }
  }
Esempio n. 27
0
 /**
  * Directly execute a message. This is usually called from runWorker(), but is also called
  * externally to execute a message for TxLogPlayback
  */
 public void execute(SourcedMessage message) {
   commandExecutor.execute(message);
 }
  @Override
  public NetworkFile openFile(SrvSession sess, TreeConnection tree, FileOpenParams param)
      throws IOException {
    String path = param.getPath();

    boolean truncate = param.isOverwrite();

    if (logger.isDebugEnabled()) {
      int sharedAccess = param.getSharedAccess();
      String strSharedAccess = SharingMode.getSharingModeAsString(sharedAccess);

      logger.debug(
          "openFile:"
              + path
              + ", isDirectory: "
              + param.isDirectory()
              + ", isStream: "
              + param.isStream()
              + ", readOnlyAccess: "
              + param.isReadOnlyAccess()
              + ", readWriteAccess: "
              + param.isReadWriteAccess()
              + ", writeOnlyAccess:"
              + param.isWriteOnlyAccess()
              + ", attributesOnlyAccess:"
              + param.isAttributesOnlyAccess()
              + ", sequentialAccessOnly:"
              + param.isSequentialAccessOnly()
              + ", writeThrough:"
              + param.isWriteThrough()
              + ", truncate:"
              + truncate
              + ", requestBatchOpLock:"
              + param.requestBatchOpLock()
              + ", requestExclusiveOpLock:"
              + param.requestExclusiveOpLock()
              + ", isDeleteOnClose:"
              + param.isDeleteOnClose()
              + ", allocationSize:"
              + param.getAllocationSize()
              + ", sharedAccess: "
              + strSharedAccess
              + ", openAction: "
              + param.getOpenAction()
              + param);
    }

    ContentContext tctx = (ContentContext) tree.getContext();
    NodeRef rootNode = tctx.getRootNode();

    DriverState driverState = getDriverState(sess);

    String[] paths = FileName.splitPath(path);
    String folder = paths[0];
    String file = paths[1];

    EvaluatorContext ctx = getEvaluatorContext(driverState, folder);

    OpenFileMode openMode = OpenFileMode.READ_ONLY;

    if (param.isAttributesOnlyAccess()) {
      openMode = OpenFileMode.ATTRIBUTES_ONLY;
    } else if (param.isReadWriteAccess()) {
      openMode = OpenFileMode.READ_WRITE;
    } else if (param.isWriteOnlyAccess()) {
      openMode = OpenFileMode.WRITE_ONLY;
    } else if (param.isReadOnlyAccess()) {
      openMode = OpenFileMode.READ_ONLY;
    } else if (param.isDeleteOnClose()) {
      if (logger.isDebugEnabled()) {
        logger.debug("open file has delete on close");
      }
      openMode = OpenFileMode.DELETE;
    }

    try {
      Operation o = new OpenFileOperation(file, openMode, truncate, rootNode, path);
      Command c = ruleEvaluator.evaluate(ctx, o);
      Object ret = commandExecutor.execute(sess, tree, c);

      if (ret != null && ret instanceof NetworkFile) {
        NetworkFile x = (NetworkFile) ret;

        if (logger.isDebugEnabled()) {
          logger.debug("returning open file: for path:" + path + ", ret:" + ret);
        }
        return x;
      } else {
        // Error - contact broken
        logger.error(
            "contract broken - NetworkFile not returned. " + ret == null
                ? "Return value is null"
                : ret);
        return null;
      }
    } catch (org.alfresco.repo.security.permissions.AccessDeniedException ade) {
      throw new AccessDeniedException("Unable to open file " + param.getPath(), ade);
    }

    // return diskInterface.openFile(sess, tree, params);
  } // End of OpenFile