@NotNull
  @Override
  public CommandStatus execute(
      @NotNull CouchbaseMock mock, @NotNull Command command, @NotNull JsonObject payload) {
    super.execute(mock, command, payload);
    try {
      executeReal(payload, command);
    } catch (AccessControlException e) {
      error = e.getMessage();
    }

    return getResponse();
  }
Ejemplo n.º 2
0
  @Test
  public void mustChangePassword() {
    // PRE: reset vivaldi's password
    UserPatch userPatch = new UserPatch();
    userPatch.setKey("b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee");
    userPatch.setPassword(new PasswordPatch.Builder().value("password321").build());
    userService.update(userPatch);

    // 0. access as vivaldi -> succeed
    SyncopeClient vivaldiClient = clientFactory.create("vivaldi", "password321");
    Pair<Map<String, Set<String>>, UserTO> self = vivaldiClient.self();
    assertFalse(self.getRight().isMustChangePassword());

    // 1. update user vivaldi (3) requirig password update
    userPatch = new UserPatch();
    userPatch.setKey("b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee");
    userPatch.setMustChangePassword(new BooleanReplacePatchItem.Builder().value(true).build());
    UserTO vivaldi = updateUser(userPatch).getEntity();
    assertTrue(vivaldi.isMustChangePassword());

    // 2. attempt to access -> fail
    try {
      vivaldiClient.getService(ResourceService.class).list();
      fail();
    } catch (AccessControlException e) {
      assertNotNull(e);
      assertEquals("Please change your password first", e.getMessage());
    }

    // 3. change password
    vivaldiClient.getService(UserSelfService.class).changePassword("password123");

    // 4. verify it worked
    self = clientFactory.create("vivaldi", "password123").self();
    assertFalse(self.getRight().isMustChangePassword());
  }
Ejemplo n.º 3
0
  /**
   * Wait until a proper shutdown command is received, then return. This keeps the main thread alive
   * - the thread pool listening for http connections is daemon threads.
   *
   * <p>NOTE: This method has been copied and modified slightly from
   * org.apache.catalina.core.StandardServer.await() We should have just called
   * container.getServer().await() but it returns null for getServer() and i do not know why :)
   */
  public void await() {
    // Set up a server socket to wait on
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port, 1, InetAddress.getByName(address));
    } catch (IOException e) {
      System.out.println(
          "TomcatManager.await: create[" + address + ":" + port + "]: " + e.getMessage());
      System.exit(1);
    }

    // Loop waiting for a connection and a valid command
    while (true) {

      // Wait for the next connection
      Socket socket = null;
      InputStream stream = null;
      try {
        socket = serverSocket.accept();
        socket.setSoTimeout(10 * 1000); // Ten seconds
        stream = socket.getInputStream();
      } catch (AccessControlException ace) {
        System.out.println("TomcatManager.accept security exception: " + ace.getMessage());
        continue;
      } catch (IOException e) {
        System.out.println("TomcatManager.await: accept: " + e.getMessage());
        System.exit(1);
      }

      // Read a set of characters from the socket
      StringBuilder command = new StringBuilder();
      int expected = 1024; // Cut off to avoid DoS attack
      while (expected < shutdown.length()) {
        if (random == null) {
          random = new Random();
        }
        expected += (random.nextInt() % 1024);
      }
      while (expected > 0) {
        int ch = -1;
        try {
          ch = stream.read();
        } catch (IOException e) {
          System.out.println("TomcatManager.await: read: " + e.getMessage());
          ch = -1;
        }
        if (ch < 32) { // Control character or EOF terminates loop
          break;
        }
        command.append((char) ch);
        expected--;
      }

      // Close the socket now that we are done with it
      try {
        socket.close();
      } catch (IOException e) {
        // Ignore
      }

      // Match against our command string
      boolean match = command.toString().equals(shutdown);
      if (match) {
        System.out.println("TomcatManager.shutdownViaPort");
        break;
      } else {
        System.out.println(
            "TomcatManager.await: Invalid command '" + command.toString() + "' received");
      }
    }

    // Close the server socket and return
    try {
      serverSocket.close();
    } catch (IOException e) {
      // Ignore
    }
  }
  /**
   * Read configuration for the specified classloader.
   *
   * @param classLoader
   * @throws IOException Error
   */
  protected void readConfiguration(ClassLoader classLoader) throws IOException {

    InputStream is = null;
    // Special case for URL classloaders which are used in containers:
    // only look in the local repositories to avoid redefining loggers 20 times
    try {
      if (classLoader instanceof URLClassLoader) {
        URL logConfig = ((URLClassLoader) classLoader).findResource("logging.properties");

        if (null != logConfig) {
          if (Boolean.getBoolean(DEBUG_PROPERTY))
            System.err.println(
                getClass().getName()
                    + ".readConfiguration(): "
                    + "Found logging.properties at "
                    + logConfig);

          is = classLoader.getResourceAsStream("logging.properties");
        } else {
          if (Boolean.getBoolean(DEBUG_PROPERTY))
            System.err.println(
                getClass().getName() + ".readConfiguration(): " + "Found no logging.properties");
        }
      }
    } catch (AccessControlException ace) {
      // No permission to configure logging in context
      // Log and carry on
      ClassLoaderLogManagerClassLoaderLogInfo info =
          classLoaderLoggers.get(ClassLoader.getSystemClassLoader());
      if (info != null) {
        Logger log = info.getLoggers().get("");
        if (log != null) {
          Permission perm = ace.getPermission();
          if (perm instanceof FilePermission && perm.getActions().equals("read")) {
            log.warning(
                "Reading "
                    + perm.getName()
                    + " is not permitted. See \"per context logging\" in the default catalina.policy file.");
          } else {
            log.warning(
                "Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file.");
            log.warning("Original error was: " + ace.getMessage());
          }
        }
      }
    }
    if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) {
      String configFileStr = System.getProperty("java.util.logging.config.file");
      if (configFileStr != null) {
        try {
          is = new FileInputStream(replace(configFileStr));
        } catch (IOException e) {
          // Ignore
        }
      }
      // Try the default JVM configuration
      if (is == null) {
        File defaultFile =
            new File(new File(System.getProperty("java.home"), "lib"), "logging.properties");
        try {
          is = new FileInputStream(defaultFile);
        } catch (IOException e) {
          // Critical problem, do something ...
        }
      }
    }

    Logger localClassLoaderLogManagerRootLogger = new ClassLoaderLogManagerRootLogger();
    if (is == null) {
      // Retrieve the root logger of the parent classloader instead
      ClassLoader current = classLoader.getParent();
      ClassLoaderLogManagerClassLoaderLogInfo info = null;
      while (current != null && info == null) {
        info = getClassLoaderInfo(current);
        current = current.getParent();
      }
      if (info != null) {
        localClassLoaderLogManagerRootLogger.setParent(info.getRootNode().getLogger());
      }
    }
    ClassLoaderLogManagerClassLoaderLogInfo info =
        new ClassLoaderLogManagerClassLoaderLogInfo(
            new ClassLoaderLogManagerLogNode(null, localClassLoaderLogManagerRootLogger));
    classLoaderLoggers.put(classLoader, info);

    if (is != null) {
      readConfiguration(is, classLoader);
    }
    addLogger(localClassLoaderLogManagerRootLogger);
  }
Ejemplo n.º 5
0
  /**
   * Wait until a proper shutdown command is received, then return. This keeps the main thread alive
   * - the thread pool listening for http connections is daemon threads.
   */
  public void await() {
    // Negative values - don't wait on port - tomcat is embedded or we just don't like ports
    if (port == -2) {
      // undocumented yet - for embedding apps that are around, alive.
      return;
    }
    if (port == -1) {
      while (true) {
        try {
          Thread.sleep(10000);
        } catch (InterruptedException ex) {
        }
        if (stopAwait) return;
      }
    }

    // Set up a server socket to wait on
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port, 1, InetAddress.getByName("localhost"));
    } catch (IOException e) {
      log.error("StandardServer.await: create[" + port + "]: ", e);
      System.exit(1);
    }

    // Loop waiting for a connection and a valid command
    while (true) {

      // Wait for the next connection
      Socket socket = null;
      InputStream stream = null;
      try {
        socket = serverSocket.accept();
        socket.setSoTimeout(10 * 1000); // Ten seconds
        stream = socket.getInputStream();
      } catch (AccessControlException ace) {
        log.warn("StandardServer.accept security exception: " + ace.getMessage(), ace);
        continue;
      } catch (IOException e) {
        log.error("StandardServer.await: accept: ", e);
        System.exit(1);
      }

      // Read a set of characters from the socket
      StringBuffer command = new StringBuffer();
      int expected = 1024; // Cut off to avoid DoS attack
      while (expected < shutdown.length()) {
        if (random == null) random = new Random();
        expected += (random.nextInt() % 1024);
      }
      while (expected > 0) {
        int ch = -1;
        try {
          ch = stream.read();
        } catch (IOException e) {
          log.warn("StandardServer.await: read: ", e);
          ch = -1;
        }
        if (ch < 32) // Control character or EOF terminates loop
        break;
        command.append((char) ch);
        expected--;
      }

      // Close the socket now that we are done with it
      try {
        socket.close();
      } catch (IOException e) {;
      }

      // Match against our command string
      boolean match = command.toString().equals(shutdown);
      if (match) {
        break;
      } else
        log.warn("StandardServer.await: Invalid command '" + command.toString() + "' received");
    }

    // Close the server socket and return
    try {
      serverSocket.close();
    } catch (IOException e) {;
    }
  }
Ejemplo n.º 6
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void run() {
    init();
    this.state = 3;
    this.percentage = 5;
    try {
      loadJarURLs();
      String path =
          (String)
              AccessController.doPrivileged(
                  new PrivilegedExceptionAction() {
                    public Object run() throws Exception {
                      return Util.getWorkingDirectory() + File.separator + "bin" + File.separator;
                    }
                  });
      File dir = new File(path);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      if (this.latestVersion != null) {
        File versionFile = new File(dir, "version");
        boolean cacheAvailable = false;
        if ((versionFile.exists())
            && ((this.latestVersion.equals("-1"))
                || (this.latestVersion.equals(readVersionFile(versionFile))))) {
          cacheAvailable = true;
          this.percentage = 90;
        }
        boolean updateLauncher = false;
        if (this.forceUpdate == 1) {
          updateLauncher = true;
        }
        try {
          String versionLauncher = "";
          URL url_version = new URL(versionFileTxt);
          try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url_version.openStream()));
            versionLauncher = in.readLine();
          } catch (Exception e) {
            System.err.println(e);
          }
          File current_versionLauncher = new File(dir, "vose.txt");
          if (!current_versionLauncher.exists()) {
            updateLauncher = true;
            try {
              BufferedWriter bw = new BufferedWriter(new FileWriter(current_versionLauncher));
              bw.append(versionLauncher);
              bw.close();
            } catch (IOException e) {
              System.out.println("Erreur");
            }
          } else {
            try {
              Scanner scanner = new Scanner(current_versionLauncher);
              while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                if (!versionLauncher.equals(line)) {
                  updateLauncher = true;
                  try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(current_versionLauncher));
                    bw.append(versionLauncher);
                    bw.close();
                  } catch (IOException e) {
                    System.out.println("Erreur");
                  }
                }
              }

              scanner.close();
            } catch (IOException e) {
              System.out.println("Erreur" + e.getMessage());
            }
          }
        } catch (Exception localException1) {
        }
        if ((!cacheAvailable) || (updateLauncher)) {
          downloadJars(path);
          extractJars(path);
          extractNatives(path);
          if (this.latestVersion != null) {
            this.percentage = 90;
            writeVersionFile(versionFile, this.latestVersion);
          }
        }
      }
      updateClassPath(dir);
      this.state = 10;
    } catch (AccessControlException ace) {
      fatalErrorOccured(ace.getMessage(), ace);
      this.certificateRefused = true;
    } catch (Exception e) {
      fatalErrorOccured(e.getMessage(), e);
    } finally {
      this.loaderThread = null;
    }
  }