Exemplo n.º 1
0
  private void handleRemoveFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("removing feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String feedId = request.getParameter(PARAM_FEED_ID);

      LOG.info(String.format("Removing feed %s for user %s", feedId, user));

      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (feedId == null || feedId.equals("")) {
        LOG.error("feed not specified");
        // ttt1 show some error
        return;
      }

      if (user.feedIds.remove(
          feedId)) { // ttt2 clean up the global feed table; that's probably better done if nobody
                     // accesses a feed for 3 months or so
        userDb.updateFeeds(user);
        LOG.info(String.format("Removed feed %s for user %s", feedId, user));
      } else {
        LOG.info(String.format("No feed found with ID %s for user %s", feedId, user));
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
 /**
  * Write the startup header for the logs to show what our inputs are.
  *
  * @param log The logger
  */
 private void logStartHeader(Log log) {
   log.info("Started Octopus Deploy");
   log.info("======================");
   log.info("Project: " + project);
   log.info("Version: " + releaseVersion);
   log.info("Environment: " + environment);
   log.info("======================");
 }
Exemplo n.º 3
0
  /**
   * See if the provided object reference has any children that may help satisfy the recognition
   * string. This is essentially how this Iterator is "reentrant". Objects matching pieces of our
   * ObjectVector are added to the statically shared matches collection until the final Object
   * satisfying the entire ObjectVector is found.
   *
   * <p>Throughout the process we must maintain an accurate count of each class and its associated
   * object type in each child branch. In this way, we keep track of when we have found the nth
   * Index of a class or an associated object type in the branch. Thus, for each object encountered,
   * we must increment both the class count, and t he object type count for that class in this
   * branch.
   *
   * <p>Note, as we go down an object hierarchy branch, the counts increment. However, when we reset
   * back up to a higher level in the object hierarchy to go down a new branch, the counts must be
   * reset to those counts that were valid on entry at that level.
   *
   * <p>This function is only called internally.
   *
   * <p>
   *
   * @param achild the Object to process for children.
   *     <p>
   * @param agovVector the currently active GuiObjectVector.
   *     <p>
   * @param agovLevel the hierarchy level in the GuiObjectVector we are trying to satisfy.
   *     <p>
   * @param aobjLevel the level in the actual object hierarchy we are searching.
   *     <p>
   * @param classindices the storage of current class counts.
   *     <p>
   * @param typeindices the storage of current object type counts.
   * @author Carl Nagle, SEP 02, 2004 modified processChildren to skip checking children of
   *     Comboboxes
   */
  protected void processChildren(
      Object achild,
      GuiObjectVector agovVector,
      int agovLevel,
      int aobjLevel,
      Hashtable classindices,
      Hashtable typeindices,
      String typeclass) {

    GuiObjectRecognition agor = agovVector.getParentGuiObjectRecognition();
    String classname = agor.getObjectClassName(achild);

    // CANAGL -- do not seek children in comboboxes.  messes pushbutton counts!
    try {
      if (GuiClassData.classtypeContainsClassType(typeclass, "ComboBox")) {
        Log.debug("GCI: No children sought for ComboBoxes");
        return;
      }
      // if Domain = HTML and typeclass = PushButton
      if ((classname.toLowerCase().startsWith("html"))
          && (GuiClassData.classtypeContainsClassType(typeclass, "PushButton"))) {
        Log.debug("GCI: No children sought for HTML PushButtons");
        return;
      }
    } catch (Exception x) {;
    }

    // may be cached keys to proxies during EXTERNAL_PROCESSING
    Object[] childsChildren = agovVector.getChildObjects(achild);

    if ((childsChildren instanceof Object) && (childsChildren.length > 0)) {

      Log.info("GCI: " + childsChildren.length + " children in " + classname);
      Log.info("..........Child:" + classname + ", typeclass: " + typeclass);
      GuiChildIterator it = agovVector.createGuiChildIterator(gather);

      boolean isTab =
          (GuiClassData.classtypeContainsClassType(typeclass, "TabControl"))
              || (GuiClassData.classtypeContainsClassType(classname, "Html.HtmlBrowser"));

      // childsChildren may be cached keys during EXTERNAL_PROCESSING
      it.processNextLevel(
          childsChildren, agovVector, agovLevel, aobjLevel, classindices, typeindices, isTab);
    } else {
      Log.debug("GCI: No children found for " + classname);
    }
  }
  /**
   * Returns control when task is complete.
   *
   * @param json
   * @param logger
   */
  private String waitForDeploymentCompletion(JSON json, OctopusApi api, Log logger) {
    final long WAIT_TIME = 5000;
    final double WAIT_RANDOM_SCALER = 100.0;
    JSONObject jsonObj = (JSONObject) json;
    String id = jsonObj.getString("TaskId");
    Task task = null;
    String lastState = "Unknown";
    try {
      task = api.getTask(id);
    } catch (IOException ex) {
      logger.error("Error getting task: " + ex.getMessage());
      return null;
    }

    logger.info("Task info:");
    logger.info("\tId: " + task.getId());
    logger.info("\tName: " + task.getName());
    logger.info("\tDesc: " + task.getDescription());
    logger.info("\tState: " + task.getState());
    logger.info("\n\nStarting wait...");
    boolean completed = task.getIsCompleted();
    while (!completed) {
      try {
        task = api.getTask(id);
      } catch (IOException ex) {
        logger.error("Error getting task: " + ex.getMessage());
        return null;
      }

      completed = task.getIsCompleted();
      lastState = task.getState();
      logger.info("Task state: " + lastState);
      if (completed) {
        break;
      }
      try {
        Thread.sleep(WAIT_TIME + (long) (Math.random() * WAIT_RANDOM_SCALER));
      } catch (InterruptedException ex) {
        logger.info("Wait interrupted!");
        logger.info(ex.getMessage());
        completed = true; // bail out of wait loop
      }
    }
    logger.info("Wait complete!");
    return lastState;
  }
Exemplo n.º 5
0
 public void run() {
   try {
     if (isRegistered()) {
       register();
     }
   } catch (IOException e) {
     Log.info("Failed to reRegister " + e.getMessage());
   }
 }
Exemplo n.º 6
0
 @Override
 public void run() {
   for (CacheStatus lcacheStatus : toBeDeletedCache) {
     synchronized (lcacheStatus) {
       Path fullUniqueParentDir =
           new Path(lcacheStatus.localizedBaseDir, lcacheStatus.uniqueParentDir);
       try {
         LOG.info("Deleting local cached path: " + fullUniqueParentDir.toString());
         deleteLocalPath(asyncDiskService, fs, fullUniqueParentDir);
         // decrement the size of the cache from baseDirSize
         deleteCacheInfoUpdate(lcacheStatus);
         LOG.info("Removed cache " + lcacheStatus.localizedLoadPath);
       } catch (IOException e) {
         LOG.warn("Error when deleting " + fullUniqueParentDir, e);
       }
     }
   }
 }
Exemplo n.º 7
0
 /**
  * <br>
  * <em>Purpose:</em> load the resource defined in 'bundleName' * <br>
  * <em>Side Effects:</em> 'textResources' * <br>
  * <em>State Read:</em> 'bundleName' * <br>
  * NOTE: the ".properties" is assumed by the 'ResourceBundle.getBundle' method
  */
 public void loadResource() throws MissingResourceException {
   try {
     textResources =
         ResourceBundle.getBundle(bundleName, locale, ClassLoader.getSystemClassLoader());
     Log.info("GetText loading " + bundleName);
   } catch (MissingResourceException mr) {
     Log.info("GetText retrying load of " + bundleName);
     try {
       textResources =
           ResourceBundle.getBundle(
               bundleName, locale, Thread.currentThread().getContextClassLoader());
       Log.info("GetText loading " + bundleName);
     } catch (MissingResourceException mr2) {
       Log.info("GetText failed to load " + bundleName);
       throw mr2;
     }
   }
 }
Exemplo n.º 8
0
  // the method which actually copies the caches locally and unjars/unzips them
  // and does chmod for the files
  private static Path localizeCache(
      Configuration conf, URI cache, long confFileStamp, CacheStatus cacheStatus, boolean isArchive)
      throws IOException {
    FileSystem fs = getFileSystem(cache, conf);
    FileSystem localFs = FileSystem.getLocal(conf);
    Path parchive = null;

    if (isArchive) {
      parchive =
          new Path(
              cacheStatus.localizedLoadPath, new Path(cacheStatus.localizedLoadPath.getName()));
    } else {
      parchive = cacheStatus.localizedLoadPath;
    }
    if (!localFs.mkdirs(parchive.getParent())) {
      throw new IOException(
          "Mkdirs failed to create directory " + cacheStatus.localizedLoadPath.toString());
    }
    String cacheId = cache.getPath();

    fs.copyToLocalFile(new Path(cacheId), parchive);
    if (isArchive) {
      String tmpArchive = parchive.toString().toLowerCase();
      File srcFile = new File(parchive.toString());
      File destDir = new File(parchive.getParent().toString());
      if (tmpArchive.endsWith(".jar")) {
        RunJar.unJar(srcFile, destDir);
      } else if (tmpArchive.endsWith(".zip")) {
        FileUtil.unZip(srcFile, destDir);
      } else if (isTarFile(tmpArchive)) {
        FileUtil.unTar(srcFile, destDir);
      }
      // else will not do anyhting
      // and copy the file into the dir as it is
    }
    long cacheSize = FileUtil.getDU(new File(parchive.getParent().toString()));
    cacheStatus.size = cacheSize;
    addCacheInfoUpdate(cacheStatus);

    // do chmod here
    try {
      // Setting recursive permission to grant everyone read and execute
      Path localDir = new Path(cacheStatus.localizedBaseDir, cacheStatus.uniqueParentDir);
      LOG.info("Doing chmod on localdir :" + localDir);
      FileUtil.chmod(localDir.toString(), "ugo+rx", true);
    } catch (InterruptedException e) {
      LOG.warn("Exception in chmod" + e.toString());
    }

    // update cacheStatus to reflect the newly cached file
    cacheStatus.mtime = getTimestamp(conf, cache);
    return cacheStatus.localizedLoadPath;
  }
Exemplo n.º 9
0
  private void logOut(String browserId) throws Exception {
    // ttt2 the right way to do it is to go through all the sessions of the current browser, which
    // would require a new field and a new index;
    // not sure if it's worth it, but this would work: A logs in, forgets to log out, B delets the
    // cookies, logs in, A sees B is logged in, then B
    // restores the cookies and uses A's account
    if (browserId == null) {
      return;
    }

    List<LoginInfo> loginInfos = loginInfoDb.getLoginsForBrowser(browserId);
    long expireTarget = System.currentTimeMillis() - Utils.ONE_DAY;
    for (LoginInfo loginInfo : loginInfos) {
      if (loginInfo.expiresOn <= expireTarget) {
        LOG.info(String.format("LoginInfo %s is enough in the past", loginInfo));
      } else {
        LOG.info(String.format("Logging out: %s", loginInfo));
        loginInfoDb.updateExpireTime(browserId, loginInfo.sessionId, expireTarget);
      }
    }
  }
Exemplo n.º 10
0
 private void addPrebuiltJsp(String path, String className) {
   try {
     Class clazz =
         Class.forName(
             className); // ttt2 see if possible to not use this, preferably without doing
                         // redirections like RedirectServlet
     Object obj = clazz.newInstance();
     addServlet(new ServletHolder((Servlet) obj), path);
     LOG.info("Added prebuilt JSP: " + obj.toString());
   } catch (Exception e) {
     LOG.fatal(String.format("Failed to load prebuilt JSP for %s and %s", path, className), e);
   }
 }
Exemplo n.º 11
0
  public synchronized boolean configClearspace() {
    // If the task is running, stop it
    if (configClearspaceTask != null) {
      configClearspaceTask.cancel();
      Log.debug("Stopping previous configuration Clearspace task.");
    }

    boolean configured = false;
    try {
      doConfigClearspace();
      updateClearspaceClientSettings();
      configured = true;
    } catch (UnauthorizedException e) {
      Log.info("Unauthorized to configure Clearspace.", e);
    } catch (UnsupportedOperationException e) {
      Log.info("Error configuring Clearspace.", e);
    }

    if (!configured) {
      startClearspaceConfig();
    }
    return configured;
  }
Exemplo n.º 12
0
  protected void doCommon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
      if (log.isDebugEnabled()) log.debug(HttpUtils.fmtRequest(httpRequest));

      // getRequestURL is the exact string used by the caller in the request.
      // Internally, it's the "request URI" that names the service

      // String requestURL = httpRequest.getRequestURL().toString() ;
      String uri = httpRequest.getRequestURI();

      if (uri.length() > urlLimit) {
        httpResponse.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG);
        return;
      }

      String serviceURI = chooseServiceURI(uri, httpRequest);
      serviceURI = Service.canonical(serviceURI);

      String sender = httpRequest.getRemoteAddr();
      log.info("[" + sender + "] Service URI = <" + serviceURI + ">");

      // MIME-Type
      String contentType = httpRequest.getContentType();

      //            if ( Joseki.contentSPARQLUpdate.equals(contentType) ||
      //                Joseki.contentSPARQLUpdate_X.equals(contentType) )
      //            {}

      Request request = setupRequest(serviceURI, httpRequest);
      request.setParam(Joseki.VERB, httpRequest.getMethod());

      Response response = new ResponseHttp(request, httpRequest, httpResponse);
      Dispatcher.dispatch(serviceURI, request, response);
    } catch (Exception ex) {
      try {
        log.warn("Internal server error", ex);
        //                httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ;
        //                httpResponse.flushBuffer() ;
        //                httpResponse.getWriter().close() ;
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      } catch (Exception e) {
      }
    }
  }
Exemplo n.º 13
0
 private static Path checkCacheStatusValidity(
     Configuration conf,
     URI cache,
     long confFileStamp,
     CacheStatus cacheStatus,
     FileStatus fileStatus,
     boolean isArchive)
     throws IOException {
   FileSystem fs = FileSystem.get(cache, conf);
   // Has to be
   if (!ifExistsAndFresh(conf, fs, cache, confFileStamp, cacheStatus, fileStatus)) {
     throw new IOException(
         "Stale cache file: " + cacheStatus.localizedLoadPath + " for cache-file: " + cache);
   }
   LOG.info(
       String.format(
           "Using existing cache of %s->%s", cache.toString(), cacheStatus.localizedLoadPath));
   return cacheStatus.localizedLoadPath;
 }
Exemplo n.º 14
0
 /**
  * Delete a local path with asyncDiskService if available, or otherwise synchronously with local
  * file system.
  */
 private static void deleteLocalPath(
     MRAsyncDiskService asyncDiskService, LocalFileSystem fs, Path path) throws IOException {
   boolean deleted = false;
   if (asyncDiskService != null) {
     // Try to delete using asyncDiskService
     String localPathToDelete = path.toUri().getPath();
     deleted = asyncDiskService.moveAndDeleteAbsolutePath(localPathToDelete);
     if (!deleted) {
       LOG.warn(
           "Cannot find DistributedCache path "
               + localPathToDelete
               + " on any of the asyncDiskService volumes!");
     }
   }
   if (!deleted) {
     // If no asyncDiskService, we will delete the files synchronously
     fs.delete(path, true);
   }
   LOG.info("Deleted path " + path);
 }
 protected void fetchResource(
     String publicName,
     String category,
     String defaultName,
     File result,
     boolean verbose,
     File publicRoot)
     throws IOException {
   URL u = locateResource(publicName, category, defaultName, verbose, publicRoot);
   if (u != null) {
     IOUtils.copyFromURL(u, result);
   } else {
     if (verbose) {
       Log.info(
           MessageFormat.format(
               I18N.getString("message.using-default-resource"),
               category == null ? "" : "[" + category + "] ",
               publicName));
     }
   }
 }
 protected void fetchResource(
     String publicName,
     String category,
     File defaultFile,
     File result,
     boolean verbose,
     File publicRoot)
     throws IOException {
   URL u = locateResource(publicName, category, null, verbose, publicRoot);
   if (u != null) {
     IOUtils.copyFromURL(u, result);
   } else {
     IOUtils.copyFile(defaultFile, result);
     if (verbose) {
       Log.info(
           MessageFormat.format(
               I18N.getString("message.using-custom-resource-from-file"),
               category == null ? "" : "[" + category + "] ",
               defaultFile.getAbsoluteFile()));
     }
   }
 }
Exemplo n.º 17
0
  private void handleAddFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("adding feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String url = request.getParameter(PARAM_NEW_FEED_URL);
      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (url == null || url.equals("")) {
        LOG.error("New feed not specified");
        // ttt1 show some error
        return;
      }

      MessageDigest digest = MessageDigest.getInstance("MD5");
      String feedId = PrintUtils.byteArrayAsUrlString(digest.digest(url.getBytes("UTF-8")));
      feedId = feedId.substring(0, Config.getConfig().feedIdSize);

      Feed feed = feedDb.get(feedId);
      if (feed == null) {
        feed = new Feed(feedId, url);
        feedDb.add(feed);
      }

      if (user.feedIds.contains(feedId)) {
        LOG.error(String.format("Trying to add existing feed %s to user %s", feedId, user));
      } else {
        user.feedIds.add(feedId);
        userDb.updateFeeds(user);
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
 private URL locateResource(
     String publicName, String category, String defaultName, boolean verbose, File publicRoot)
     throws IOException {
   URL u = null;
   boolean custom = false;
   if (publicName != null) {
     if (publicRoot != null) {
       File publicResource = new File(publicRoot, publicName);
       if (publicResource.exists() && publicResource.isFile()) {
         u = publicResource.toURI().toURL();
       }
     } else {
       u = baseResourceLoader.getClassLoader().getResource(publicName);
     }
     custom = (u != null);
   }
   if (u == null && defaultName != null) {
     u = baseResourceLoader.getResource(defaultName);
   }
   String msg = null;
   if (custom) {
     msg =
         MessageFormat.format(
             I18N.getString("message.using-custom-resource-from-classpath"),
             category == null ? "" : "[" + category + "] ",
             publicName);
   } else if (u != null) {
     msg =
         MessageFormat.format(
             I18N.getString("message.using-default-resource-from-classpath"),
             category == null ? "" : "[" + category + "] ",
             publicName);
   }
   if (verbose && u != null) {
     Log.info(msg);
   }
   return u;
 }
  @Override
  public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
    // This method deserves a refactor and cleanup.
    boolean success = true;
    Log log = new Log(listener);
    if (Result.FAILURE.equals(build.getResult())) {
      log.info("Not deploying due to job being in FAILED state.");
      return success;
    }

    logStartHeader(log);
    // todo: getting from descriptor is ugly. refactor?
    getDescriptorImpl().setGlobalConfiguration();
    OctopusApi api = getDescriptorImpl().api;

    VariableResolver resolver = build.getBuildVariableResolver();
    EnvVars envVars;
    try {
      envVars = build.getEnvironment(listener);
    } catch (Exception ex) {
      log.fatal(
          String.format(
              "Failed to retrieve environment variables for this build - '%s'", ex.getMessage()));
      return false;
    }
    EnvironmentVariableValueInjector envInjector =
        new EnvironmentVariableValueInjector(resolver, envVars);
    // NOTE: hiding the member variables of the same name with their env-injected equivalents
    String project = envInjector.injectEnvironmentVariableValues(this.project);
    String releaseVersion = envInjector.injectEnvironmentVariableValues(this.releaseVersion);
    String environment = envInjector.injectEnvironmentVariableValues(this.environment);
    String variables = envInjector.injectEnvironmentVariableValues(this.variables);

    com.octopusdeploy.api.Project p = null;
    try {
      p = api.getProjectByName(project);
    } catch (Exception ex) {
      log.fatal(
          String.format(
              "Retrieving project name '%s' failed with message '%s'", project, ex.getMessage()));
      success = false;
    }
    com.octopusdeploy.api.Environment env = null;
    try {
      env = api.getEnvironmentByName(environment);
    } catch (Exception ex) {
      log.fatal(
          String.format(
              "Retrieving environment name '%s' failed with message '%s'",
              environment, ex.getMessage()));
      success = false;
    }
    if (p == null) {
      log.fatal("Project was not found.");
      success = false;
    }
    if (env == null) {
      log.fatal("Environment was not found.");
      success = false;
    }
    if (!success) // Early exit
    {
      return success;
    }
    Set<com.octopusdeploy.api.Release> releases = null;
    try {
      releases = api.getReleasesForProject(p.getId());
    } catch (Exception ex) {
      log.fatal(
          String.format(
              "Retrieving releases for project '%s' failed with message '%s'",
              project, ex.getMessage()));
      success = false;
    }
    if (releases == null) {
      log.fatal("Releases was not found.");
      return false;
    }
    Release releaseToDeploy = null;
    for (Release r : releases) {
      if (releaseVersion.equals(r.getVersion())) {
        releaseToDeploy = r;
        break;
      }
    }
    if (releaseToDeploy == null) // early exit
    {
      log.fatal(
          String.format(
              "Unable to find release version %s for project %s", releaseVersion, project));
      return false;
    }
    Properties properties = new Properties();
    try {
      properties.load(new StringReader(variables));
    } catch (Exception ex) {
      log.fatal(
          String.format(
              "Unable to load entry variables failed with message '%s'", ex.getMessage()));
      success = false;
    }

    // TODO: Can we tell if we need to call? For now I will always try and get variable and use if I
    // find them
    Set<com.octopusdeploy.api.Variable> variablesForDeploy = null;

    try {
      String releaseId = releaseToDeploy.getId();
      String environmentId = env.getId();
      variablesForDeploy =
          api.getVariablesByReleaseAndEnvironment(releaseId, environmentId, properties);
    } catch (Exception ex) {
      log.fatal(
          String.format(
              "Retrieving variables for release '%s' to environment '%s' failed with message '%s'",
              releaseToDeploy.getId(), env.getName(), ex.getMessage()));
      success = false;
    }
    try {
      String results =
          api.executeDeployment(releaseToDeploy.getId(), env.getId(), variablesForDeploy);
      if (isTaskJson(results)) {
        JSON resultJson = JSONSerializer.toJSON(results);
        String urlSuffix = ((JSONObject) resultJson).getJSONObject("Links").getString("Web");
        String url = getDescriptorImpl().octopusHost;
        if (url.endsWith("/")) {
          url = url.substring(0, url.length() - 2);
        }
        log.info("Deployment executed: \n\t" + url + urlSuffix);
        build.addAction(
            new BuildInfoSummary(
                BuildInfoSummary.OctopusDeployEventType.Deployment, url + urlSuffix));
        if (waitForDeployment) {

          log.info("Waiting for deployment to complete.");
          String resultState = waitForDeploymentCompletion(resultJson, api, log);
          if (resultState == null) {
            log.info("Marking build failed due to failure in waiting for deployment to complete.");
            success = false;
          }

          if ("Failed".equals(resultState)) {
            log.info("Marking build failed due to deployment task status.");
            success = false;
          }
        }
      }
    } catch (IOException ex) {
      log.fatal("Failed to deploy: " + ex.getMessage());
      success = false;
    }

    return success;
  }
Exemplo n.º 20
0
  @Override
  public void doHandle(
      String target,
      Request request,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse)
      throws IOException, ServletException {

    LOG.info("handling " + target);

    // !!! doHandle() is called twice for a request when using redirectiion, first time with
    // request.getPathInfo()
    // set to the URI and target set to the path, then with request.getPathInfo() set to null and
    // target set to the .jsp
    try {
      // request.setHandled(true);
      boolean secured;
      if (request.getScheme().equals("https")) {
        secured = true;
      } else if (request.getScheme().equals("http")) {
        secured = false;
      } else {
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unknown scheme %s at %s</h1>",
                    request.getScheme(), request.getUri().getDecodedPath()));
        return;
      }

      if (request.getMethod().equals("GET")) {
        if (isInJar || target.endsWith(".jsp")) {
          // !!! when not in jar there's no need to do anything about params if it's not a .jsp,
          // as this will get called again for the corresponding .jsp
          if (prepareForJspGet(target, request, httpServletResponse, secured)) {
            return;
          }
        }
        if (target.startsWith(PATH_OPEN_ARTICLE)) {
          handleOpenArticle(request, httpServletResponse, target);
          return;
        }
        super.doHandle(target, request, httpServletRequest, httpServletResponse);
        LOG.info("handling of " + target + " went to super");

        // httpServletResponse.setDateHeader("Date", System.currentTimeMillis());     //ttt2 review
        // these, probably not use
        // httpServletResponse.setDateHeader("Expires", System.currentTimeMillis() + 60000);

        return;
      }

      if (request.getMethod().equals("POST")) {
        if (request.getUri().getDecodedPath().equals(PATH_LOGIN)) {
          handleLoginPost(request, httpServletResponse, secured);
        } else if (request.getUri().getDecodedPath().equals(PATH_SIGNUP)) {
          handleSignupPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_PASSWORD)) {
          handleChangePasswordPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_UPDATE_FEED_LIST)) {
          handleUpdateFeedListPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_ADD_FEED)) {
          handleAddFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_REMOVE_FEED)) {
          handleRemoveFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_SETTINGS)) {
          handleChangeSettingsPost(request, httpServletResponse);
        }
      }

      /*{ // for tests only;
          httpServletResponse.getWriter().println(String.format("<h1>Unable to process request %s</h1>",
                  request.getUri().getDecodedPath()));
          request.setHandled(true);
      }*/
    } catch (Exception e) {
      LOG.error("Error processing request", e);
      try {
        // redirectToError(e.toString(), request, httpServletResponse); //!!! redirectToError leads
        // to infinite loop, probably related to
        // the fact that we get 2 calls for a regular request when redirecting
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unable to process request %s</h1>", // ttt1 generate some HTML
                    request.getUri().getDecodedPath()));
        request.setHandled(true);
      } catch (Exception e1) {
        LOG.error("Error redirecting", e1);
      }
    }
  }
Exemplo n.º 21
0
  /**
   * Normally sets the path and a few attributes that the JSPs are likely to need. Also verifies the
   * login information. If necessary, just redirects to the login page.
   *
   * @param target
   * @param request
   * @param httpServletResponse
   * @param secured
   * @return true if the request is already handled so the .jsp shouldn't get called
   * @throws Exception
   */
  private boolean prepareForJspGet(
      String target, Request request, HttpServletResponse httpServletResponse, boolean secured)
      throws Exception {

    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    LOG.info(
        String.format(
            "hndl - %s ; %s; %s ; %s",
            target,
            request.getPathInfo(),
            request.getMethod(),
            secured ? "secured" : "not secured"));

    String path = request.getUri().getDecodedPath();

    boolean redirectToLogin = path.equals(PATH_LOGOUT);
    LoginInfo loginInfo = null;
    if (sessionInfo.isNull()) {
      redirectToLogin = true;
      LOG.info("Null session info. Logging in again.");
    } else {
      loginInfo =
          loginInfoDb.get(
              sessionInfo.browserId,
              sessionInfo.sessionId); // ttt2 use a cache, to avoid going to DB
      if (loginInfo == null || loginInfo.expiresOn < System.currentTimeMillis()) {
        LOG.info("Session has expired. Logging in again. Info: " + loginInfo);
        redirectToLogin = true;
      }
    }

    if (!path.equals(PATH_LOGIN) && !path.equals(PATH_SIGNUP) && !path.equals(PATH_ERROR)) {

      if (redirectToLogin) {
        // ttt2 perhaps store URI, to return to it after login
        logOut(sessionInfo.browserId);
        addLoginParams(request, loginInfo);
        httpServletResponse.sendRedirect(PATH_LOGIN);
        return true;
      }

      User user = userDb.get(loginInfo.userId);
      if (user == null) {
        WebUtils.redirectToError("Unknown user", request, httpServletResponse);
        return true;
      }
      if (!user.active) {
        WebUtils.redirectToError("Account is not active", request, httpServletResponse);
        return true;
      }
      request.setAttribute(VAR_FEED_DB, feedDb);
      request.setAttribute(VAR_USER_DB, userDb);
      request.setAttribute(VAR_ARTICLE_DB, articleDb);
      request.setAttribute(VAR_READ_ARTICLES_COLL_DB, readArticlesCollDb);

      request.setAttribute(VAR_USER, user);
      request.setAttribute(VAR_LOGIN_INFO, loginInfo);

      MultiMap<String> params = new MultiMap<>();
      params.put(PARAM_PATH, path);
      request.setParameters(params);
    }

    if (path.equals(PATH_LOGIN)) {
      addLoginParams(request, loginInfo);
    }
    return false;
  }
  /**
   * For all packages, find all sources belonging to the package, group the sources based on their
   * transformers and apply the transformers on each source code group.
   */
  private boolean perform(File outputDir, Map<String, Transformer> suffixRules) {
    boolean rc = true;
    // Group sources based on transforms. A source file can only belong to a single transform.
    Map<Transformer, Map<String, Set<URI>>> groupedSources = new HashMap<>();
    for (Source src : now.sources().values()) {
      Transformer t = suffixRules.get(src.suffix());
      if (t != null) {
        if (taintedPackages.contains(src.pkg().name()) && !src.isLinkedOnly()) {
          addFileToTransform(groupedSources, t, src);
        }
      }
    }
    // Go through the transforms and transform them.
    for (Map.Entry<Transformer, Map<String, Set<URI>>> e : groupedSources.entrySet()) {
      Transformer t = e.getKey();
      Map<String, Set<URI>> srcs = e.getValue();
      // These maps need to be synchronized since multiple threads will be writing results into
      // them.
      Map<String, Set<URI>> packageArtifacts =
          Collections.synchronizedMap(new HashMap<String, Set<URI>>());
      Map<String, Set<String>> packageDependencies =
          Collections.synchronizedMap(new HashMap<String, Set<String>>());
      Map<String, String> packagePublicApis =
          Collections.synchronizedMap(new HashMap<String, String>());

      boolean r =
          t.transform(
              srcs,
              visibleSrcs,
              visibleClasses,
              prev.dependents(),
              outputDir.toURI(),
              packageArtifacts,
              packageDependencies,
              packagePublicApis,
              0,
              isIncremental(),
              numCores,
              out,
              err);
      if (!r) rc = false;

      for (String p : srcs.keySet()) {
        recompiledPackages.add(p);
      }
      // The transform is done! Extract all the artifacts and store the info into the Package
      // objects.
      for (Map.Entry<String, Set<URI>> a : packageArtifacts.entrySet()) {
        Module mnow = now.findModuleFromPackageName(a.getKey());
        mnow.addArtifacts(a.getKey(), a.getValue());
      }
      // Extract all the dependencies and store the info into the Package objects.
      for (Map.Entry<String, Set<String>> a : packageDependencies.entrySet()) {
        Set<String> deps = a.getValue();
        Module mnow = now.findModuleFromPackageName(a.getKey());
        mnow.setDependencies(a.getKey(), deps);
      }
      // Extract all the pubapis and store the info into the Package objects.
      for (Map.Entry<String, String> a : packagePublicApis.entrySet()) {
        Module mprev = prev.findModuleFromPackageName(a.getKey());
        List<String> pubapi = Package.pubapiToList(a.getValue());
        Module mnow = now.findModuleFromPackageName(a.getKey());
        mnow.setPubapi(a.getKey(), pubapi);
        if (mprev.hasPubapiChanged(a.getKey(), pubapi)) {
          // Aha! The pubapi of this package has changed!
          // It can also be a new compile from scratch.
          if (mprev.lookupPackage(a.getKey()).existsInJavacState()) {
            // This is an incremental compile! The pubapi
            // did change. Trigger recompilation of dependents.
            packagesWithChangedPublicApis.add(a.getKey());
            Log.info("The pubapi of " + Util.justPackageName(a.getKey()) + " has changed!");
          }
        }
      }
    }
    return rc;
  }
  /** Load a javac_state file. */
  public static JavacState load(
      String[] args,
      File binDir,
      File gensrcDir,
      File headerDir,
      boolean permitUnidentifiedArtifacts,
      PrintStream out,
      PrintStream err) {
    JavacState db =
        new JavacState(
            args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, false, out, err);
    Module lastModule = null;
    Package lastPackage = null;
    Source lastSource = null;
    boolean noFileFound = false;
    boolean foundCorrectVerNr = false;
    boolean newCommandLine = false;
    boolean syntaxError = false;

    try (BufferedReader in = new BufferedReader(new FileReader(db.javacStateFilename))) {
      for (; ; ) {
        String l = in.readLine();
        if (l == null) break;
        if (l.length() >= 3 && l.charAt(1) == ' ') {
          char c = l.charAt(0);
          if (c == 'M') {
            lastModule = db.prev.loadModule(l);
          } else if (c == 'P') {
            if (lastModule == null) {
              syntaxError = true;
              break;
            }
            lastPackage = db.prev.loadPackage(lastModule, l);
          } else if (c == 'D') {
            if (lastModule == null || lastPackage == null) {
              syntaxError = true;
              break;
            }
            lastPackage.loadDependency(l);
          } else if (c == 'I') {
            if (lastModule == null || lastPackage == null) {
              syntaxError = true;
              break;
            }
            lastPackage.loadPubapi(l);
          } else if (c == 'A') {
            if (lastModule == null || lastPackage == null) {
              syntaxError = true;
              break;
            }
            lastPackage.loadArtifact(l);
          } else if (c == 'S') {
            if (lastModule == null || lastPackage == null) {
              syntaxError = true;
              break;
            }
            lastSource = db.prev.loadSource(lastPackage, l, false);
          } else if (c == 'G') {
            if (lastModule == null || lastPackage == null) {
              syntaxError = true;
              break;
            }
            lastSource = db.prev.loadSource(lastPackage, l, true);
          } else if (c == 'R') {
            String ncmdl = "R " + db.theArgs;
            if (!l.equals(ncmdl)) {
              newCommandLine = true;
            }
          } else if (c == '#') {
            if (l.startsWith("# javac_state ver ")) {
              int sp = l.indexOf(" ", 18);
              if (sp != -1) {
                String ver = l.substring(18, sp);
                if (!ver.equals("0.3")) {
                  break;
                }
                foundCorrectVerNr = true;
              }
            }
          }
        }
      }
    } catch (FileNotFoundException e) {
      // Silently create a new javac_state file.
      noFileFound = true;
    } catch (IOException e) {
      Log.info("Dropping old javac_state because of errors when reading it.");
      db =
          new JavacState(
              args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);
      foundCorrectVerNr = true;
      newCommandLine = false;
      syntaxError = false;
    }
    if (foundCorrectVerNr == false && !noFileFound) {
      Log.info("Dropping old javac_state since it is of an old version.");
      db =
          new JavacState(
              args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);
    } else if (newCommandLine == true && !noFileFound) {
      Log.info("Dropping old javac_state since a new command line is used!");
      db =
          new JavacState(
              args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);
    } else if (syntaxError == true) {
      Log.info("Dropping old javac_state since it contains syntax errors.");
      db =
          new JavacState(
              args, binDir, gensrcDir, headerDir, permitUnidentifiedArtifacts, true, out, err);
    }
    db.prev.calculateDependents();
    return db;
  }
Exemplo n.º 24
0
 private void handleUpdateFeedListPost(Request request, HttpServletResponse httpServletResponse)
     throws Exception {
   LOG.info("updating feed list"); // ttt2 implement
   httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
 }
Exemplo n.º 25
0
 public Servlet(String string) {
   log.info("-------- " + string);
 }
Exemplo n.º 26
0
  private void handleLoginPost(
      Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String password = request.getParameter(PARAM_PASSWORD);
    String rememberAccountStr = request.getParameter(PARAM_REMEMBER_ACCOUNT);
    boolean rememberAccount = Boolean.parseBoolean(rememberAccountStr);
    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    logOut(sessionInfo.browserId);

    User user = userDb.get(userId);
    if (user == null) {
      WebUtils.redirectToError("User " + userId + " not found", request, httpServletResponse);
      return;
    }

    if (!user.checkPassword(password)) {
      WebUtils.redirectToError("Invalid password", request, httpServletResponse);
      return;
    }

    if (!user.active) {
      WebUtils.redirectToError(
          "Account for User " + userId + " needs to be activated", request, httpServletResponse);
      return;
    }

    LOG.info("Logged in user " + userId);

    sessionInfo.sessionId = null;
    if (sessionInfo.browserId == null) {
      sessionInfo.browserId = getRandomId();
    } else {
      for (LoginInfo loginInfo : loginInfoDb.getLoginsForBrowser(sessionInfo.browserId)) {
        if (userId.equals(loginInfo.userId)) {
          sessionInfo.sessionId = loginInfo.sessionId;
          break;
        }
      }
    }

    long expireOn = System.currentTimeMillis() + Config.getConfig().loginExpireInterval;
    if (sessionInfo.sessionId == null) {
      sessionInfo.sessionId = getRandomId();
      Config config = Config.getConfig();
      loginInfoDb.add(
          new LoginInfo(
              sessionInfo.browserId,
              sessionInfo.sessionId,
              userId,
              expireOn,
              rememberAccount,
              config.defaultStyle,
              config.defaultItemsPerPage,
              config.defaultFeedDateFormat));
      LOG.info(String.format("Logging in in a new session. User: %s", user));
    } else {
      loginInfoDb.updateExpireTime(sessionInfo.browserId, sessionInfo.sessionId, expireOn);
      LOG.info(String.format("Logging in in an existing session. User: %s", user));
    }

    WebUtils.saveCookies(
        httpServletResponse, secured, sessionInfo.browserId, sessionInfo.sessionId);

    httpServletResponse.sendRedirect("/");
  }
Exemplo n.º 27
0
  /**
   * Called only once by some external routine kicking off a TestObject search. The govLevel and
   * objLevel in the ObjectVector will be assumed to be 0. The routine will install an initial class
   * and type indices for the provided parent.
   *
   * <p>If we can deduce that the parent actually exists in the path vector then that govLevel of
   * the vector will be matched and skipped. If we find that the parent info is NOT in the provided
   * vector then we will not skip the govLevel.
   *
   * <p>We can assume the parent info is in the path if the path begins with "\;". The next item in
   * the path is assumed to be the topmost parent.
   *
   * <p>We can ignore the first path info if it instead begins with ".\;". The next item would be
   * considered to be the first child of the parent.
   *
   * <p>
   *
   * @param aparent the topmost parent to search.
   *     <p>
   * @param agovVector the govVector (recognition string) to satisfy with the search.
   *     <p>
   * @param gather, List containing names matched, if null, then match first name
   */
  public GuiChildIterator(Object aparent, GuiObjectVector agovVector, java.util.List gather) {
    this(gather);
    if (agovVector.isFullPathSearchMode()) {
      setSearchMode(FULLPATH_SEARCH_MODE);
    } else {
      setSearchMode(CLASSIC_SEARCH_MODE);
    }
    Hashtable classindices = new Hashtable(8);
    Hashtable typeindices = new Hashtable(8);
    matches = new Vector(10, 3);
    notFound = true;
    hasFinalMatch = false;

    // class (ex: JFrame) and Type (ex: Window) counters are complimentary
    // for each class that is a known type BOTH counters get incremented.

    // always initialize class index counters for the retrieved class

    // it is possible this "parent" info is actually info for the first child govLevel 0
    GuiObjectRecognition gorParent = agovVector.getParentGuiObjectRecognition();
    GuiClassData classdata = agovVector.getGuiClassData();

    String classname = gorParent.getObjectClassName(aparent);
    Log.info("GCI: processing children of parent:" + classname);
    classindices.put(classname, new Integer(1));

    // always initialize the Type index counter if it is equivalent to a known type
    String typeclass = classdata.getMappedClassType(classname, aparent);
    Log.info("GCI: processing parent of type:" + typeclass);
    if (typeclass instanceof String) {
      StringTokenizer toker = new StringTokenizer(typeclass, classdata.DEFAULT_TYPE_SEPARATOR);
      String atoken = null;
      while (toker.hasMoreTokens()) {
        atoken = toker.nextToken().trim();
        typeindices.put(atoken, new Integer(1));
      }
    }

    // add our entry govVector and parent object as the first match
    // CANAGL - modifying to only store finalMatches
    // MatchData adata = new MatchData(agovVector, 0, 0, aparent);
    // matches.addElement(adata);

    int agovDepth = agovVector.getRecognitionDepth();
    Log.info(
        "GCI: processing GOV with depth of:" + agovDepth + ", path=" + agovVector.getPathVector());

    // begin the reentrant search for the matching child
    int startlevel = (agovDepth > 1) ? 1 : 0;
    if ((gorParent.getGovLevel() == 0)
        && (!(gorParent.pathInfo.equals(GuiObjectVector.ACTIVE_WINDOW_REFERENCE)))) {

      // Robot Java recognition strings often contain a JavaWindow reference
      // to the parent window that needs to be skipped.	Same with Flex recognition strings(JunwuMa).
      if (!gorParent.getClassRecognition().equalsIgnoreCase("Type=JavaWindow")
          && !gorParent.getClassRecognition().equalsIgnoreCase("Type=FlexWindow")) {
        startlevel = 0;
      } else {
        Log.info(
            "GCI: bypassing govLevel=0 for child 'Type=JavaWindow'. Assuming duplicate parent info.");
      }
    }
    // Try to match the parent for some popupmenu
    Hashtable save_classindices = (Hashtable) classindices.clone();
    Hashtable save_typeindices = (Hashtable) typeindices.clone();

    processParent(aparent, agovVector, startlevel, 1, classindices, typeindices, typeclass);
    Object matchedObject = this.getMatchedGuiObject();

    if (matchedObject == null) {
      if (SEARCH_MODE != FULLPATH_SEARCH_MODE) {
        Log.info("GCI: CLASSIC_SEARCH_MODE calling processChildren...");
        processChildren(aparent, agovVector, startlevel, 1, classindices, typeindices, typeclass);
      } else {
        Log.info("GCI: FULLPATH_SEARCH_MODE calling processChildren...");
        processChildren(
            aparent, agovVector, startlevel, 1, save_classindices, save_typeindices, typeclass);
      }
    }
  }
Exemplo n.º 28
0
  /**
   * @param child
   * @param govVector
   * @param objLevel
   * @param govLevel
   * @param classindices
   * @param typeindices
   * @param classname
   * @return NULL if error occurs relating to gorInfo creation, or NULL if object is NOT to be
   *     processed. Otherwise, return a valid ClassTypeInfo object with all appropriate settings.
   */
  protected ClassTypeInfo incrementClassTypeIndices(
      Object child,
      GuiObjectVector govVector,
      int govLevel,
      int objLevel,
      Hashtable classindices,
      Hashtable typeindices,
      String classname) {
    Log.info("GCI: getting child GOR info. GOV level:" + govLevel);
    ClassTypeInfo cti = new ClassTypeInfo();
    final String TOOLTIP_SUFFIX = "TOOLTIP";
    cti.classname = classname;
    try {
      cti.gorInfo = govVector.getChildGuiObjectRecognition(govLevel);
    } catch (ArrayIndexOutOfBoundsException x) {
      Log.debug(
          "GCI: sought govLevel:"
              + govLevel
              + ", exceeds 0-based recognition path information:"
              + govVector.getPathVector());
      return null;
    }
    GuiClassData classdata = govVector.getGuiClassData();
    cti.typeclass = classdata.getMappedClassType(classname, child);

    // bypass panels that harbor tooltip(s)
    Object tooltip = null;
    String tooltipclass = null;
    String tooltipmapped = null;
    String gortypeclass = cti.gorInfo.getClassValue();
    // only perform check if we are NOT looking for a tooltip
    if ((gortypeclass == null)
        || (gortypeclass != null && !gortypeclass.toUpperCase().endsWith(TOOLTIP_SUFFIX))) {
      try {
        Log.info("GCI.incrementClassTypeIndices evaluating possible TOOLTIP container...");
        if (classdata.isToolTipContainerType(cti.typeclass)) {
          Object[] childsChildren = govVector.getChildObjects(child);
          if (childsChildren != null && childsChildren.length > 0) {
            tooltip = childsChildren[0];
            tooltipclass = cti.gorInfo.getObjectClassName(tooltip);
            try {
              if (tooltipclass.toUpperCase().endsWith(TOOLTIP_SUFFIX)) {
                Log.info("GCI.incrementClassTypeIndices bypassing active TOOLTIP class!");
                return null; // skip panel with tooltip
              }
              tooltipmapped = classdata.getMappedClassType(tooltipclass, tooltip);
              if (tooltipmapped.toUpperCase().endsWith(TOOLTIP_SUFFIX)) {
                Log.info("GCI.incrementClassTypeIndices bypassing active TOOLTIP type!");
                return null; // skip panel with tooltip
              }
            } catch (Exception x) {
              Log.debug(
                  "GCI.incrementClassTypeIndices ToolTip test IGNORING "
                      + x.getClass().getSimpleName());
            }
          }
        }
        Log.info("GCI.incrementClassTypeIndices container NOT a TOOLTIP container.");
      } catch (Exception x) {
        Log.debug(
            "GCI.incrementClassTypeIndices ToolTip Container test IGNORING "
                + x.getClass().getSimpleName());
      }
    }
    // increment class index counters for the retrieved class?
    Log.info("GCI: incrementing class indices for:" + classname);
    Integer classindex = (Integer) classindices.get(classname);
    classindex = (classindex == null) ? new Integer(1) : new Integer(classindex.intValue() + 1);
    classindices.put(classname, classindex);
    cti.classindex = classindex.intValue();
    Log.info("GCI: classindices.put(" + classname + ", " + classindex + ")");

    Integer absclassindex = (Integer) absindices.get(classname);
    absclassindex =
        (absclassindex == null) ? new Integer(1) : new Integer(absclassindex.intValue() + 1);
    absindices.put(classname, absclassindex);
    cti.absoluteclassindex = absclassindex.intValue();
    Log.info("GCI: absindices.put(" + classname + ", " + absclassindex + ")");

    // also increment the Type index counter if it is equivalent to a known type
    String gorClassType = cti.gorInfo.getClassValue();
    Log.info("GCI: " + classname + " mappedClassType: " + cti.typeclass);
    Integer typeindex = new Integer(0);
    Integer abstypeindex = new Integer(0);

    if (cti.typeclass instanceof String) {
      StringTokenizer toker = new StringTokenizer(cti.typeclass, classdata.DEFAULT_TYPE_SEPARATOR);
      String atoken = null;
      Integer tmptypeindex = null;
      Integer tmpabstypeindex = null;

      while (toker.hasMoreTokens()) {
        atoken = toker.nextToken().toUpperCase().trim();
        tmptypeindex = (Integer) typeindices.get(atoken);
        Log.info("GCI: getting: " + atoken + ", " + tmptypeindex);
        tmptypeindex =
            (tmptypeindex == null) ? new Integer(1) : new Integer(tmptypeindex.intValue() + 1);
        Log.index(
            "GCI: ... "
                + StringUtils.getSpaces(new Integer(objLevel))
                + atoken
                + ":"
                + tmptypeindex);
        typeindices.put(atoken, tmptypeindex);
        tmpabstypeindex = (Integer) absindices.get(atoken);
        tmpabstypeindex =
            (tmpabstypeindex == null)
                ? new Integer(1)
                : new Integer(tmpabstypeindex.intValue() + 1);
        absindices.put(atoken, tmpabstypeindex);
        Log.info("TYPE:absindices.put(" + atoken + ", " + tmpabstypeindex + ")");

        // use the correct typeindex for the classtype that matches recognition string
        if (atoken.equalsIgnoreCase(gorClassType)) {
          typeindex = tmptypeindex;
          cti.typeindex = typeindex.intValue();
          abstypeindex = tmpabstypeindex;
          cti.absolutetypeindex = abstypeindex.intValue();
        }
      }
    }
    return cti;
  }
Exemplo n.º 29
0
  /**
   * Called internally by processChildren only.
   *
   * <p>
   *
   * @param children -- array of child objects to examine to see if any one of them satisfies the
   *     piece of the recognition string for the current object vector level--the current substring
   *     of the full recognition string. May be array of cached keys if GuiObjectVector is in
   *     EXTERNAL_PROCESSING_MODE.
   *     <p>
   * @param govVector -- the currently active GuiObjectVector.
   *     <p>
   * @param govLevel -- the hierarchy level (current substring)in the GuiObjectVector we are trying
   *     to satisfy.
   *     <p>
   * @param objLevel -- the depth in the actual application's object hierarchy currently being
   *     searched.
   *     <p>
   * @param entry_classindices -- the storage for class counts.
   *     <p>
   * @param entry_typeindices -- the storage for object type counts.
   *     <p>
   * @param onlyOneChildVisible -- true if parent is a TabControl-like component,
   */
  protected void processNextLevel(
      Object[] children, // children\key array to process
      GuiObjectVector govVector, // the full recognition vector
      int govLevel, // depth within the vector to process
      int objLevel, // depth within obj hierarchy being processed
      Hashtable entry_classindices, // class=count storage for class indices
      Hashtable entry_typeindices, // class=count storage for object indices
      boolean onlyOneChildVisible) { // if true, parent is tab
    boolean notDone = true;

    Hashtable classindices = entry_classindices;
    Hashtable typeindices = entry_typeindices;
    Hashtable save_classindices = (Hashtable) entry_classindices.clone();
    Hashtable save_typeindices = (Hashtable) entry_typeindices.clone();

    for (int i = 0; ((notFound) && (notDone) && (i < children.length)); i++) {

      Object _child = null;
      Object child = null;
      Object[] childsChildren = new Object[0];

      // reset indices for all but the last level of searching:
      // when dealing with things like TabControls with non-visible panels
      // and in CLASSIC_SEARCH_MODE.
      // In FULLPATH_SEARCH_MODE these hidden panels get unique indices
      if ((govLevel < govVector.getRecognitionDepth() - 1 && onlyOneChildVisible)
          && (SEARCH_MODE != FULLPATH_SEARCH_MODE)) {
        if (i > 0) {
          Log.info(".....class/type indices reset for all but the last level of searching");
          classindices = (Hashtable) save_classindices.clone();
          typeindices = (Hashtable) save_typeindices.clone();
        }
      }

      // get next child and reset index counters
      // only play with GuiTestObjects
      Log.info("GCI: Seeking child(" + i + ")outof(" + children.length + ")...");
      _child = children[i];
      child = _child;
      if (!govVector.isValidGuiObject(_child)) {
        Log.debug("GCI: skipping invalid Gui Object found in child array.");
        continue;
      }
      Log.info("GCI: child(" + i + ") is a valid GUI object.");

      if (govVector.getProcessMode() == GuiObjectVector.MODE_EXTERNAL_PROCESSING) {
        try {
          child = govVector.getCachedItem(_child);
        } catch (Exception e) {
        }
      }
      GuiObjectRecognition gor = govVector.getParentGuiObjectRecognition();
      String classname = gor.getObjectClassName(child);
      ClassTypeInfo typeinfo = null;

      // **** if (! classname.equalsIgnoreCase("Html.!")) { // this kills IE
      Log.info("GCI: child classname is:" + classname);

      // check to see if it is visible
      if (!gor.isObjectShowing(child)) {

        // if not, skip it if it is a container (like a TabControl Panel)
        Log.info("GCI: child is not showing.");
        if (govVector.isValidGuiContainer(_child)) {
          if (govVector.isFullPathSearchMode()) {
            incrementClassTypeIndices(
                child, govVector, govLevel, objLevel, classindices, typeindices, classname);
          }
          Log.info("GCI: skipping non-visible Gui Container: " + classname);
          continue;
        }
      }
      // } end if classname == "Html.!"
      typeinfo =
          incrementClassTypeIndices(
              child, govVector, govLevel, objLevel, classindices, typeindices, classname);
      if (typeinfo == null) continue; // invalid gorInfo at this level

      int classindex = typeinfo.classindex;
      int typeindex = typeinfo.typeindex;
      int abstypeindex = typeinfo.absolutetypeindex;
      String typeclass = typeinfo.typeclass;
      GuiObjectRecognition gorInfo = typeinfo.gorInfo;

      // classname  will ALWAYS have a class value
      // classindex will ALWAYS be at least 1
      // typeclass MAY BE null if we can't match the type
      // typeindex MAY BE  0   if we can't match the type
      int passindex, abspassindex;
      if (gorInfo.getClassCategoryID() == gorInfo.CATEGORY_CLASS_ID) {
        passindex = classindex;
        abspassindex = typeinfo.absoluteclassindex;
      }
      // TYPE is only alternative to CLASS right now
      else {
        passindex = typeindex;
        abspassindex = abstypeindex;
      }
      // see if we match the object at this level
      boolean classMatch;
      try {
        String[] tmpName = null;
        if (gather != null) tmpName = new String[1];
        classMatch =
            gorInfo.isMatchingObject(
                child, passindex,
                abspassindex, tmpName);

        // this is a special case test when we are doing this algorithm
        // but we want to gather *ALL* of the names which match, rather
        // than just the first name.  In that event, the parameter
        // 'gather' is used.  If not null, then don't let 'classMatch' get
        // beyond this place as 'true', but instead, stuff the name
        // into the List 'gather' and use 'false' for the classMatch...
        if (gather != null) {
          if (tmpName != null && tmpName[0] != null) {
            Log.info(" .....  ADD TO GATHER: " + tmpName[0]);
            gather.add(tmpName[0]);
          } else { // maybe use the index
            Log.info(
                " .....  GATHER INDEX?? passindex, abspassindex: "
                    + passindex
                    + ", "
                    + abspassindex
                    + ", classmatch would be: "
                    + classMatch);
          }
          // if we are gathering then lets also gather matched child objects
          if (classMatch) {
            // for recognitions with Path=, we must get that object
            // this is primarily used when we want ALL possible objects of
            // a given type.  For example, all HTMLLinks on a page.
            Object matchObject = gorInfo.getMatchingObject(child);
            MatchData adata = new MatchData(govVector, govLevel, objLevel, matchObject);
            matches.addElement(adata);
          }
          classMatch = false;
        }
      } catch (SAFSObjectRecognitionException ore) {
        classMatch = false;
        Log.debug(ore.getMessage());
      }

      if (classMatch) {
        // see if we have matched to the last object vector recognition level
        notDone = (govLevel < (govVector.getRecognitionDepth() - 1));
        Log.debug(
            "GCI: notDone matching vector: "
                + notDone
                + " :govLevel="
                + govLevel
                + ", maxLevel="
                + (govVector.getRecognitionDepth() - 1)
                + ", path="
                + govVector.getPathVector());
        if (notDone) {
          // see if this child has some children
          try {
            int lenchildren =
                (typeinfo.childsChildren != null)
                    ? typeinfo.childsChildren.length
                    : govVector.getChildObjects(child).length;
            if (lenchildren > 0) {
              // Log.index("notDone: processChildren: "+(objLevel+1));
              if (SEARCH_MODE == FULLPATH_SEARCH_MODE) {
                processChildren(
                    child,
                    govVector,
                    govLevel + 1,
                    objLevel + 1,
                    save_classindices,
                    save_typeindices,
                    typeclass);
              } else { // assume CLASSIC_SEARCH_MODE
                processChildren(
                    child,
                    govVector,
                    govLevel + 1,
                    objLevel + 1,
                    classindices,
                    typeindices,
                    typeclass);
              }
            }
            // if there are no children, then we are done going down this branch
            // and this path will not be a match for our recognition string
            else {
              // signal this branch is done
              // should this just be a continue?
              Log.debug("GCI: Branch completed. 0 children for " + gorInfo);
              notDone = false;
            }
            // signal this branch is done if no children (exception thrown for .length)
          } catch (Exception np) {
            Log.debug("GCI: Branch completed. NullPointer/No children for " + gorInfo, np);
            notDone = false;
          }
        }
        // **************************************************************
        // **** see if this is THEE child that completes our search! ****
        // **************************************************************
        else {
          hasFinalMatch = gorInfo.isFinalMatch(child);
          notFound = !hasFinalMatch;
          // for recognitions with Path=, we must get that object
          Object matchObject = gorInfo.getMatchingObject(child);
          // removing this unregister because currently unregistering any one reference
          // to an object seems to unregister ALL stored references to an object,
          // including cached references in our AppMaps.
          // // must unregister child if a subitem was actually the finalObject
          // if( !(matchObject == child)) {
          //   Log.debug("RGCI: Unregistering parent "+ child.getObjectClassName() +" from JVM as
          // needed.");
          //   child.unregister();
          // }
          //
          MatchData adata = new MatchData(govVector, govLevel, objLevel, matchObject);
          matches.addElement(adata);
        }
      }
      // not a class match for this object
      // we have to handle looking for the nth match inside a container
      // if not complete match, see if the match is farther down the hierarchy
      // but only for the CLASSIC_SEARCH_MODE.
      // We do not go down hierarchy paths for FULLPATH_SEARCH_MODE if the parent did not match
      else if (SEARCH_MODE
          != FULLPATH_SEARCH_MODE) { // will be CLASSIC_SEARCH_MODE (or anything else) by default
        // Log.index("processChildren: "+(objLevel+1));
        processChildren(
            child, govVector, govLevel, objLevel + 1, classindices, typeindices, typeclass);
      }
    } // end FOR LOOP
  }