public ReaderHandler(LowLevelDbAccess lowLevelDbAccess, String webDir) {

    loginInfoDb = new LoginInfo.DB(lowLevelDbAccess);
    userDb = new User.DB(lowLevelDbAccess);
    feedDb = new Feed.DB(lowLevelDbAccess);
    articleDb = new Article.DB(lowLevelDbAccess);
    readArticlesCollDb = new ReadArticlesColl.DB(lowLevelDbAccess);
    userHelpers = new UserHelpers(loginInfoDb, userDb);

    setContextPath("/");

    File warPath = new File(webDir);
    setWar(warPath.getAbsolutePath());

    if (isInJar) {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addPrebuiltJsp(entry.getKey(), "jsp." + entry.getValue().replaceAll("_", "_005f") + "_jsp");
      }
    } else {
      for (Map.Entry<String, String> entry : PATH_MAPPING.entrySet()) {
        addServlet(
            new ServletHolder(new RedirectServlet("/" + entry.getValue() + ".jsp")),
            entry.getKey());
      }
    }

    setErrorHandler(new ReaderErrorHandler());
  }
Example #2
0
 private static void endInterpreter(String contextId) throws EvalError {
   Interpreter i = interpreters.get(contextId);
   if (i == null) return;
   i.eval("clear();"); // can't hurt to tell bsh to clean up internally
   interpreters.remove(contextId); // now wait for GC
   Log.log("Destroyed context: " + contextId + " (" + i + ")");
 }
  /** Gets all Genomic Data. */
  private ProfileDataSummary getGenomicData(
      String cancerStudyId,
      HashMap<String, GeneticProfile> defaultGeneticProfileSet,
      SampleList defaultSampleSet,
      String geneListStr,
      ArrayList<SampleList> sampleList,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException, DaoException {

    // parse geneList, written in the OncoPrintSpec language (except for changes by XSS clean)
    double zScore =
        ZScoreUtil.getZScore(
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            request);
    double rppaScore = ZScoreUtil.getRPPAScore(request);

    ParserOutput theOncoPrintSpecParserOutput =
        OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(
            geneListStr,
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            zScore,
            rppaScore);

    ArrayList<String> geneList = new ArrayList<String>();
    geneList.addAll(theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes());

    ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
    Set<String> warningUnion = new HashSet<String>();

    for (GeneticProfile profile : defaultGeneticProfileSet.values()) {
      try {
        GetProfileData remoteCall =
            new GetProfileData(
                profile, geneList, StringUtils.join(defaultSampleSet.getSampleList(), " "));
        ProfileData pData = remoteCall.getProfileData();
        warningUnion.addAll(remoteCall.getWarnings());
        profileDataList.add(pData);
      } catch (IllegalArgumentException e) {
        e.getStackTrace();
      }
    }

    ProfileMerger merger = new ProfileMerger(profileDataList);
    ProfileData mergedProfile = merger.getMergedProfile();

    ProfileDataSummary dataSummary =
        new ProfileDataSummary(
            mergedProfile,
            theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(),
            zScore,
            rppaScore);
    return dataSummary;
  }
  /**
   * Returns true if the user represented by the current request plays the named role.
   *
   * @param role the named role to test.
   * @return true if the user plays the role.
   */
  public boolean isUserInRole(String role) {
    ServletInvocation invocation = getInvocation();

    if (invocation == null) {
      if (getRequest() != null) return getRequest().isUserInRole(role);
      else return false;
    }

    HashMap<String, String> roleMap = invocation.getSecurityRoleMap();

    if (roleMap != null) {
      String linkRole = roleMap.get(role);

      if (linkRole != null) role = linkRole;
    }

    String runAs = getRunAs();

    if (runAs != null) return runAs.equals(role);

    WebApp webApp = getWebApp();

    Principal user = getUserPrincipal();

    if (user == null) {
      if (log.isLoggable(Level.FINE)) log.fine(this + " no user for isUserInRole");

      return false;
    }

    RoleMapManager roleManager = webApp != null ? webApp.getRoleMapManager() : null;

    if (roleManager != null) {
      Boolean result = roleManager.isUserInRole(role, user);

      if (result != null) {
        if (log.isLoggable(Level.FINE)) log.fine(this + " userInRole(" + role + ")->" + result);

        return result;
      }
    }

    Login login = webApp == null ? null : webApp.getLogin();

    boolean inRole = login != null && login.isUserInRole(user, role);

    if (log.isLoggable(Level.FINE)) {
      if (login == null) log.fine(this + " no Login for isUserInRole");
      else if (user == null) log.fine(this + " no user for isUserInRole");
      else if (inRole) log.fine(this + " " + user + " is in role: " + role);
      else log.fine(this + " failed " + user + " in role: " + role);
    }

    return inRole;
  }
 static {
   PATH_MAPPING.put("", "home_page");
   PATH_MAPPING.put(PATH_LOGIN, "login");
   PATH_MAPPING.put(PATH_LOGOUT, "login"); // !!! after logout we get redirected to /login
   PATH_MAPPING.put(PATH_SIGNUP, "signup");
   PATH_MAPPING.put(PATH_ERROR, "error");
   PATH_MAPPING.put(PATH_FEED_ADMIN, "feed_admin");
   PATH_MAPPING.put(PATH_SETTINGS, "settings");
   PATH_MAPPING.put(PATH_FEEDS, "feeds");
   PATH_MAPPING.put(PATH_FEED + "/*", "feed");
   PATH_MAPPING.put(PATH_ADMIN, "admin");
 }
Example #6
0
  /** Returns a JarDiff for the given request */
  public synchronized DownloadResponse getJarDiffEntry(
      ResourceCatalog catalog, DownloadRequest dreq, JnlpResource res) {
    if (dreq.getCurrentVersionId() == null) return null;

    // check whether the request is from javaws 1.0/1.0.1
    // do not generate minimal jardiff if it is from 1.0/1.0.1
    boolean doJarDiffWorkAround = isJavawsVersion(dreq, "1.0*");

    // First do a lookup to find a match
    JarDiffKey key =
        new JarDiffKey(
            res.getName(),
            dreq.getCurrentVersionId(),
            res.getReturnVersionId(),
            !doJarDiffWorkAround);

    JarDiffEntry entry = (JarDiffEntry) _jarDiffEntries.get(key);
    // If entry is not found, then the querty has not been made.
    if (entry == null) {
      if (_log.isInformationalLevel()) {
        _log.addInformational(
            "servlet.log.info.jardiff.gen",
            res.getName(),
            dreq.getCurrentVersionId(),
            res.getReturnVersionId());
      }
      File f = generateJarDiff(catalog, dreq, res, doJarDiffWorkAround);
      if (f == null) {
        _log.addWarning(
            "servlet.log.warning.jardiff.failed",
            res.getName(),
            dreq.getCurrentVersionId(),
            res.getReturnVersionId());
      }
      // Store entry in table
      entry = new JarDiffEntry(f);
      _jarDiffEntries.put(key, entry);
    }

    // Check for no JarDiff to return
    if (entry.getJarDiffFile() == null) {
      return null;
    } else {
      return DownloadResponse.getFileDownloadResponse(
          entry.getJarDiffFile(),
          _jarDiffMimeType,
          entry.getJarDiffFile().lastModified(),
          res.getReturnVersionId());
    }
  }
 private String getShortcutScript(HashMap<String, String> usedButtonShortCuts) {
   StringBuffer shortcuts = new StringBuffer();
   shortcuts.append(" function buttonListShorcuts() {\n");
   Iterator<String> ik = usedButtonShortCuts.keySet().iterator();
   Iterator<String> iv = usedButtonShortCuts.values().iterator();
   while (ik.hasNext() && iv.hasNext()) {
     shortcuts
         .append("  keyArray[keyArray.length] = new keyArrayItem(\"")
         .append(ik.next())
         .append("\", \"")
         .append(iv.next())
         .append("\", null, \"altKey\", false, \"onkeydown\");\n");
   }
   shortcuts.append(" return true;\n}");
   return shortcuts.toString();
 }
Example #8
0
  public void init() throws ServletException {
    super.init();
    // allow = ThreddsConfig.getBoolean("NetcdfSubsetService.allow", true);
    // String radarLevel2Dir = ThreddsConfig.get("NetcdfSubsetService.radarLevel2DataDir",
    // "/data/ldm/pub/native/radar/level2/");
    // if (!allow) return;
    contentPath = ServletUtil.getContentPath();
    rm = new RadarMethods(contentPath, logServerStartup);

    // read in radarCollections.xml catalog
    InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation
    cat = readCatalog(factory, getPath() + catName, contentPath + getPath() + catName);
    if (cat == null) {
      logServerStartup.info("cat initialization failed");
      return;
    }
    // URI tmpURI = cat.getBaseURI();
    cat.setBaseURI(catURI);
    // get path and location from cat
    List parents = cat.getDatasets();
    for (int i = 0; i < parents.size(); i++) {
      InvDataset top = (InvDataset) parents.get(i);
      datasets = top.getDatasets(); // dataset scans

      for (int j = 0; j < datasets.size(); j++) {
        InvDatasetScan ds = (InvDatasetScan) datasets.get(j);
        if (ds.getPath() != null) {
          dataLocation.put(ds.getPath(), ds.getScanLocation());
          logServerStartup.info("path =" + ds.getPath() + " location =" + ds.getScanLocation());
        }
        ds.setXlinkHref(ds.getPath() + "/dataset.xml");
      }
    }
    logServerStartup.info(getClass().getName() + " initialization complete ");
  } // end init
Example #9
0
 /**
  * 把数据源HashMap转换成json
  *
  * @param map
  */
 public static String hashMapToJson(HashMap map) {
   String string = "{";
   for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
     Entry e = (Entry) it.next();
     string += "'" + e.getKey() + "':";
     string += "'" + e.getValue() + "',";
   }
   string = string.substring(0, string.lastIndexOf(","));
   string += "}";
   return string;
 }
 private String getServerAddress(String servletName) {
   // System.out.println("finding server for "+servletName);
   Integer res = methodHashCodesToClusterIds.get(servletName.hashCode());
   if (res != null) {
     // System.out.println("servlet "+servletName+" going to "+res);
     return serverAddresses[res % numberOfServers];
   } else {
     // System.out.println("could not find info on servlet "+servletName);
     return serverAddresses[0];
   }
 }
  /**
   * Initializes the servlet context, based on the servlet context. Parses all context parameters
   * and passes them on to the database context.
   *
   * @param sc servlet context
   * @throws IOException I/O exception
   */
  static synchronized void init(final ServletContext sc) throws IOException {
    // skip process if context has already been initialized
    if (context != null) return;

    // set servlet path as home directory
    final String path = sc.getRealPath("/");
    System.setProperty(Prop.PATH, path);

    // parse all context parameters
    final HashMap<String, String> map = new HashMap<String, String>();
    // store default web root
    map.put(MainProp.HTTPPATH[0].toString(), path);

    final Enumeration<?> en = sc.getInitParameterNames();
    while (en.hasMoreElements()) {
      final String key = en.nextElement().toString();
      if (!key.startsWith(Prop.DBPREFIX)) continue;

      // only consider parameters that start with "org.basex."
      String val = sc.getInitParameter(key);
      if (eq(key, DBUSER, DBPASS, DBMODE, DBVERBOSE)) {
        // store servlet-specific parameters as system properties
        System.setProperty(key, val);
      } else {
        // prefix relative paths with absolute servlet path
        if (key.endsWith("path") && !new File(val).isAbsolute()) {
          val = path + File.separator + val;
        }
        // store remaining parameters (without project prefix) in map
        map.put(key.substring(Prop.DBPREFIX.length()).toUpperCase(Locale.ENGLISH), val);
      }
    }
    context = new Context(map);

    if (SERVER.equals(System.getProperty(DBMODE))) {
      new BaseXServer(context);
    } else {
      context.log = new Log(context);
    }
  }
 public void init(FilterConfig filterConfig) {
   this.config = filterConfig;
   this.encoding = config.getInitParameter("encoding");
   if (encoding == null || encoding.length() == 0) {
     encoding = "GBK";
   }
   expiresMap = new HashMap();
   Enumeration names = config.getInitParameterNames();
   while (names.hasMoreElements()) {
     String paramName = (String) names.nextElement();
     if (!"encoding".equals(paramName)) {
       String paramValue = config.getInitParameter(paramName);
       try {
         Integer expires = Integer.valueOf(config.getInitParameter(paramName));
         expiresMap.put(paramName, expires);
       } catch (Exception ex) {
         // LogUtil.logError( "Filter."+paramValue+"="+paramValue);
       }
     }
   }
 }
 private void setResponseHeader(
     HttpServletResponse response, String uri, String transferEncoding) {
   // LogUtil.logDebug( uri + ".Accept-Encoding: "+ transferEncoding);
   String ext = null;
   int dot = uri.lastIndexOf(".");
   if (dot != -1) {
     ext = uri.substring(dot + 1);
   }
   if (ext != null && ext.length() > 0) {
     Integer expires = (Integer) expiresMap.get(ext);
     if (expires != null) {
       // LogUtil.logDebug( uri + ".Expires: "+ expires.intValue());
       if (expires.intValue() > 0) {
         response.setHeader("Cache-Control", "max-age=" + expires.intValue()); // HTTP 1.1
       } else {
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Pragma", "no-cache"); // HTTP 1.0
         response.setDateHeader("Expires", expires.intValue());
       }
     }
   }
 }
  public LDAPolicy(String[] serverAddresses) {
    super(serverAddresses);
    numberOfServers = serverAddresses.length;
    serverRequests = new int[numberOfServers];

    // System.out.println("Loading input data from "+localPath);

    servletNameToClusterIds =
        (HashMap<String, Integer>)
            DataReader.loadSerializedObject(localPath + "servletNameToClusterId.serialized");
    methodHashCodesToClusterIds =
        (HashMap<Integer, Integer>)
            DataReader.loadSerializedObject(localPath + "hashCodesToClusterIds.serialized");

    if (servletNameToClusterIds != null && methodHashCodesToClusterIds != null) {
      for (String s : servletNameToClusterIds.keySet()) {
        // System.out.println("Servlet["+s+"] in
        // cluster["+methodHashCodesToClusterIds.get(s.hashCode())+"]");
      }
    } else {
      throw new Error(
          "Could not load properly the load balancing input data. Terminating application");
    }
  }
  public LoadItemVariantsBean() {
    productVariants.put("ITM11_VARIANTS_1", "ITM16_PRODUCT_VARIANTS_1");
    productVariants.put("ITM12_VARIANTS_2", "ITM17_PRODUCT_VARIANTS_2");
    productVariants.put("ITM13_VARIANTS_3", "ITM18_PRODUCT_VARIANTS_3");
    productVariants.put("ITM14_VARIANTS_4", "ITM19_PRODUCT_VARIANTS_4");
    productVariants.put("ITM15_VARIANTS_5", "ITM20_PRODUCT_VARIANTS_5");

    variantTypes.put("ITM11_VARIANTS_1", "ITM06_VARIANT_TYPES_1");
    variantTypes.put("ITM12_VARIANTS_2", "ITM07_VARIANT_TYPES_2");
    variantTypes.put("ITM13_VARIANTS_3", "ITM08_VARIANT_TYPES_3");
    variantTypes.put("ITM14_VARIANTS_4", "ITM09_VARIANT_TYPES_4");
    variantTypes.put("ITM15_VARIANTS_5", "ITM10_VARIANT_TYPES_5");

    variantTypeJoins.put("ITM11_VARIANTS_1", "VARIANT_TYPE_ITM06");
    variantTypeJoins.put("ITM12_VARIANTS_2", "VARIANT_TYPE_ITM07");
    variantTypeJoins.put("ITM13_VARIANTS_3", "VARIANT_TYPE_ITM08");
    variantTypeJoins.put("ITM14_VARIANTS_4", "VARIANT_TYPE_ITM09");
    variantTypeJoins.put("ITM15_VARIANTS_5", "VARIANT_TYPE_ITM10");

    variantCodeJoins.put("ITM11_VARIANTS_1", "VARIANT_CODE_ITM11");
    variantCodeJoins.put("ITM12_VARIANTS_2", "VARIANT_CODE_ITM12");
    variantCodeJoins.put("ITM13_VARIANTS_3", "VARIANT_CODE_ITM13");
    variantCodeJoins.put("ITM14_VARIANTS_4", "VARIANT_CODE_ITM14");
    variantCodeJoins.put("ITM15_VARIANTS_5", "VARIANT_CODE_ITM15");
  }
  /** Business logic to execute. */
  public VOListResponse loadItemVariants(GridParams pars, String serverLanguageId, String username)
      throws Throwable {

    PreparedStatement pstmt = null;

    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      String tableName = (String) pars.getOtherGridParams().get(ApplicationConsts.TABLE_NAME);
      ItemPK pk = (ItemPK) pars.getOtherGridParams().get(ApplicationConsts.ITEM_PK);
      String productVariant = (String) productVariants.get(tableName);
      String variantType = (String) variantTypes.get(tableName);
      String variantTypeJoin = (String) variantTypeJoins.get(tableName);
      String variantCodeJoin = (String) variantCodeJoins.get(tableName);

      String sql =
          "select "
              + tableName
              + "."
              + variantTypeJoin
              + ","
              + tableName
              + ".VARIANT_CODE,A.DESCRIPTION,B.DESCRIPTION, "
              + tableName
              + ".PROGRESSIVE_SYS10,"
              + variantType
              + ".PROGRESSIVE_SYS10 "
              + "from "
              + tableName
              + ","
              + variantType
              + ",SYS10_COMPANY_TRANSLATIONS A,SYS10_COMPANY_TRANSLATIONS B "
              + "where "
              + tableName
              + ".COMPANY_CODE_SYS01=? and "
              + tableName
              + ".COMPANY_CODE_SYS01="
              + variantType
              + ".COMPANY_CODE_SYS01 and "
              + tableName
              + "."
              + variantTypeJoin
              + "="
              + variantType
              + ".VARIANT_TYPE and "
              + tableName
              + ".COMPANY_CODE_SYS01=A.COMPANY_CODE_SYS01 and "
              + tableName
              + ".PROGRESSIVE_SYS10=A.PROGRESSIVE and A.LANGUAGE_CODE=? and "
              + variantType
              + ".COMPANY_CODE_SYS01=B.COMPANY_CODE_SYS01 and "
              + variantType
              + ".PROGRESSIVE_SYS10=B.PROGRESSIVE and B.LANGUAGE_CODE=? and "
              + tableName
              + ".ENABLED='Y' and "
              + variantType
              + ".ENABLED='Y' and "
              + // and not "+tableName+"."+variantTypeJoin+"=? and "+
              "not "
              + tableName
              + ".VARIANT_CODE=? "
              + "order by "
              + tableName
              + "."
              + variantTypeJoin
              + ","
              + tableName
              + ".CODE_ORDER";

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("variantType", tableName + "." + variantTypeJoin);
      attribute2dbField.put("variantCode", tableName + ".VARIANT_CODE");
      attribute2dbField.put("variantDesc", "A.DESCRIPTION");
      attribute2dbField.put("variantTypeDesc", "B.DESCRIPTION");
      attribute2dbField.put("variantProgressiveSys10", tableName + ".PROGRESSIVE_SYS10");
      attribute2dbField.put("variantTypeProgressiveSys10", variantType + ".PROGRESSIVE_SYS10");

      ArrayList values = new ArrayList();
      values.add(pk.getCompanyCodeSys01ITM01());
      values.add(serverLanguageId);
      values.add(serverLanguageId);
      // values.add(ApplicationConsts.JOLLY);
      values.add(ApplicationConsts.JOLLY);

      // read from ITMxxx table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              new UserSessionParameters(username),
              sql,
              values,
              attribute2dbField,
              ItemVariantVO.class,
              "Y",
              "N",
              null,
              pars,
              50,
              true);

      if (!answer.isError()) {
        java.util.List vos = ((VOListResponse) answer).getRows();
        HashMap map = new HashMap();
        ItemVariantVO vo = null;
        for (int i = 0; i < vos.size(); i++) {
          vo = (ItemVariantVO) vos.get(i);
          vo.setCompanyCodeSys01(pk.getCompanyCodeSys01ITM01());
          vo.setItemCodeItm01(pk.getItemCodeITM01());
          vo.setTableName(tableName);
          map.put(vo.getVariantType() + "." + vo.getVariantCode(), vo);
        }

        pstmt =
            conn.prepareStatement(
                "select "
                    + productVariant
                    + "."
                    + variantTypeJoin
                    + ","
                    + productVariant
                    + "."
                    + variantCodeJoin
                    + " "
                    + "from "
                    + productVariant
                    + " "
                    + "where "
                    + productVariant
                    + ".COMPANY_CODE_SYS01=? and "
                    + productVariant
                    + ".ITEM_CODE_ITM01=? and "
                    + productVariant
                    + ".ENABLED='Y' ");
        pstmt.setString(1, pk.getCompanyCodeSys01ITM01());
        pstmt.setString(2, pk.getItemCodeITM01());
        ResultSet rset = pstmt.executeQuery();

        while (rset.next()) {
          vo = (ItemVariantVO) map.get(rset.getString(1) + "." + rset.getString(2));
          if (vo != null) vo.setSelected(Boolean.TRUE);
        }
        rset.close();
        pstmt.close();
      }

      if (answer.isError()) throw new Exception(answer.getErrorMessage());
      else return (VOListResponse) answer;

    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "getItemVariants",
          "Error while fetching item variants list",
          ex);
      throw new Exception(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      Response responseVO =
          bean.insertItem(
              conn,
              (JournalHeaderVO) inputPar,
              userSessionPars,
              request,
              response,
              userSession,
              context);
      if (responseVO.isError()) {
        conn.rollback();
        return responseVO;
      }

      if (inputPar instanceof JournalHeaderWithVatVO) {
        JournalHeaderWithVatVO vo = (JournalHeaderWithVatVO) inputPar;

        // insert vat rows in the specified vat register...
        Response regRes =
            vatRegisterAction.insertVatRows(
                conn, vo.getVats(), userSessionPars, request, response, userSession, context);
        if (regRes.isError()) {
          conn.rollback();
          return regRes;
        }

        // retrieve payment instalments...
        Response payRes =
            payAction.executeCommand(
                new LookupValidationParams(vo.getPaymentCodeREG10(), new HashMap()),
                userSessionPars,
                request,
                response,
                userSession,
                context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        PaymentVO payVO = (PaymentVO) ((VOListResponse) payRes).getRows().get(0);
        GridParams gridParams = new GridParams();
        gridParams
            .getOtherGridParams()
            .put(ApplicationConsts.PAYMENT_CODE_REG10, vo.getPaymentCodeREG10());
        payRes =
            paysAction.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        java.util.List rows = ((VOListResponse) payRes).getRows();

        // create expirations in DOC19 ONLY if:
        // - there are more than one instalment OR
        // - there is only one instalment and this instalment has more than 0 instalment days
        if (rows.size() > 1
            || (rows.size() == 1
                && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() > 0)) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          PaymentInstalmentVO inVO = null;
          pstmt =
              conn.prepareStatement(
                  "insert into DOC19_EXPIRATIONS(COMPANY_CODE_SYS01,DOC_TYPE,DOC_YEAR,DOC_NUMBER,DOC_SEQUENCE,PROGRESSIVE,DOC_DATE,EXPIRATION_DATE,NAME_1,NAME_2,VALUE,PAYED,DESCRIPTION,CUSTOMER_SUPPLIER_CODE,PROGRESSIVE_REG04,CURRENCY_CODE_REG03) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
          long startTime = vo.getItemDateACC05().getTime(); // item date...
          if (payVO.getStartDayREG10().equals(ApplicationConsts.START_DAY_END_MONTH)) {
            Calendar cal = Calendar.getInstance();
            if (cal.get(cal.MONTH) == 10
                || cal.get(cal.MONTH) == 3
                || cal.get(cal.MONTH) == 5
                || cal.get(cal.MONTH) == 8) cal.set(cal.DAY_OF_MONTH, 30);
            else if (cal.get(cal.MONTH) == 1) {
              if (cal.get(cal.YEAR) % 4 == 0) cal.set(cal.DAY_OF_MONTH, 29);
              else cal.set(cal.DAY_OF_MONTH, 28);
            } else cal.set(cal.DAY_OF_MONTH, 31);
            startTime = cal.getTime().getTime();
          }
          BigDecimal amount = null;

          for (int i = 0; i < rows.size(); i++) {
            inVO = (PaymentInstalmentVO) rows.get(i);
            pstmt.setString(1, vo.getCompanyCodeSys01ACC05());
            pstmt.setString(2, vo.getDocTypeDOC19());
            pstmt.setBigDecimal(3, vo.getItemYearACC05());
            pstmt.setBigDecimal(4, null);
            pstmt.setBigDecimal(5, vo.getDocSequenceDOC19());
            pstmt.setBigDecimal(
                6,
                ProgressiveUtils.getConsecutiveProgressive(
                    "DOC19_EXPIRATIONS", "PROGRESSIVE", conn));
            pstmt.setDate(7, vo.getItemDateACC05());
            pstmt.setDate(
                8,
                new java.sql.Date(
                    startTime
                        + inVO.getInstalmentDaysREG17().longValue()
                            * 86400
                            * 1000)); // expiration date
            pstmt.setString(9, vo.getName_1REG04());
            pstmt.setString(10, vo.getName_2REG04());
            amount =
                vo.getTotalValue()
                    .multiply(inVO.getPercentageREG17())
                    .divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP)
                    .setScale(vo.getTotalValue().scale(), BigDecimal.ROUND_HALF_UP); // value

            pstmt.setBigDecimal(11, amount);
            pstmt.setString(12, "N");

            if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE))
              pstmt.setString(
                  13,
                  resources.getResource("sale generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            else
              pstmt.setString(
                  13,
                  resources.getResource("purchase generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            pstmt.setString(14, vo.getCustomerCodeSAL07());
            pstmt.setBigDecimal(15, vo.getProgressiveREG04());
            pstmt.setString(16, vo.getCurrencyCodeREG01());
            pstmt.execute();
          }
          pstmt.close();
        }

        // create an item registration for proceeds, according to expiration settings (e.g. retail
        // selling):
        // there must be only one instalment and this instalment has 0 instalment days
        if (rows.size() == 1
            && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() == 0) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          HashMap map = new HashMap();
          map.put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01ACC05());
          map.put(ApplicationConsts.PARAM_CODE, ApplicationConsts.CASE_ACCOUNT);
          Response res =
              userParamAction.executeCommand(
                  map, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
          String caseAccountCode = ((VOResponse) res).getVo().toString();

          JournalHeaderVO jhVO = new JournalHeaderVO();
          jhVO.setCompanyCodeSys01ACC05(vo.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jhVO.setDescriptionACC05(
                resources.getResource("sale generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("customer")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_INVOICE_PROCEEDS);
          } else {
            jhVO.setDescriptionACC05(
                resources.getResource("purchase generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("supplier")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_PURCHASE_INVOICE_PAYED);
          }

          jhVO.setItemDateACC05(new java.sql.Date(System.currentTimeMillis()));
          jhVO.setItemYearACC05(new BigDecimal(Calendar.getInstance().get(Calendar.YEAR)));

          JournalRowVO jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setAccountCodeAcc02ACC06(vo.getCreditAccountCodeAcc02SAL07());
            jrVO.setAccountCodeACC06(vo.getCustomerCodeSAL07());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_CUSTOMER);
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setAccountCodeAcc02ACC06(vo.getDebitAccountCodeAcc02PUR01());
            jrVO.setAccountCodeACC06(vo.getSupplierCodePUR01());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_SUPPLIER);
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);

          jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          jrVO.setAccountCodeAcc02ACC06(caseAccountCode);
          jrVO.setAccountCodeACC06(caseAccountCode);
          jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_ACCOUNT);
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);
          Response proceedsRes =
              bean.insertItem(conn, jhVO, userSessionPars, request, response, userSession, context);
          if (proceedsRes.isError()) {
            conn.rollback();
            return proceedsRes;
          }
        }
      }

      Response answer = responseVO;

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while inserting a new item in the journal",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
Example #18
0
  private void datasetInfoXml(RadarType radarType, String pathInfo, PrintWriter pw)
      throws IOException {

    try {
      pw.println(
          "<catalog xmlns=\"http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" name=\"Radar Data\" version=\"1.0.1\">\n");
      // add service
      pw.println(
          "  <service name=\"radarServer\" base=\"/thredds/radarServer/\" serviceType=\"DQC\" />\n");
      pathInfo = pathInfo.replace("/dataset.xml", "");
      pathInfo = pathInfo.replace("/catalog.xml", "");
      if (pathInfo.startsWith("/")) pathInfo = pathInfo.substring(1);
      for (int i = 0; i < datasets.size(); i++) {
        InvDatasetScan ds = (InvDatasetScan) datasets.get(i);
        if (!(pathInfo.equals(ds.getPath()))) {
          continue;
        }

        pw.println("  <dataset ID=\"" + ds.getID() + "\" serviceName=\"radarServer\">");

        pw.println("    <urlpath>" + ds.getPath() + "</urlpath>");
        pw.println("    <dataType>" + ds.getDataType() + "</dataType>");

        pw.println("    <dataFormat>" + ds.getDataFormatType() + "</dataFormat>");

        pw.println("   <serviceName>radarServer</serviceName>");

        pw.println("    <metadata inherited=\"true\">");

        pw.println("    <documentation type=\"summary\">" + ds.getSummary() + "</documentation>");
        CalendarDateRange dr = ds.getCalendarDateCoverage();
        pw.println("      <TimeSpan>");
        pw.print("        <start>");
        if (pathInfo.contains("IDD")) {
          pw.print(rm.getStartDateTime(ds.getPath()));
        } else {
          pw.print(dr.getStart().toString());
        }
        pw.println("</start>");
        pw.println("        <end>" + dr.getEnd().toString() + "</end>");
        pw.println("      </TimeSpan>");
        ThreddsMetadata.GeospatialCoverage gc = ds.getGeospatialCoverage();
        LatLonRect bb = new LatLonRect();
        gc.setBoundingBox(bb);
        pw.println("      <LatLonBox>");
        pw.println("        <north>" + gc.getLatNorth() + "</north>");
        pw.println("        <south>" + gc.getLatSouth() + "</south>");
        pw.println("        <east>" + gc.getLonEast() + "</east>");
        pw.println("        <west>" + gc.getLonWest() + "</west>");
        pw.println("      </LatLonBox>");

        ThreddsMetadata.Variables cvs = (ThreddsMetadata.Variables) ds.getVariables().get(0);
        List vl = cvs.getVariableList();

        pw.println("      <Variables>");
        for (int j = 0; j < vl.size(); j++) {
          ThreddsMetadata.Variable v = (ThreddsMetadata.Variable) vl.get(j);
          pw.println(
              "        <variable name=\""
                  + v.getName()
                  + "\" vocabulary_name=\""
                  + v.getVocabularyName()
                  + "\" units=\""
                  + v.getUnits()
                  + "\" />");
        }
        pw.println("      </Variables>");
        String[] stations = rm.stationsDS(radarType, dataLocation.get(ds.getPath()));
        rm.printStations(stations, pw, radarType);

        pw.println("    </metadata>");
        pw.println("  </dataset>");
      }
      pw.println("</catalog>");
      pw.flush();
    } catch (Throwable e) {
      log.error("RadarServer.datasetInfoXml", e);
    }
    return;
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    try {

      response.setHeader("Cache-Control", "no-cache");
      response.setCharacterEncoding("UTF-8");

      String task = request.getParameter("task");

      Element data = null;

      // process help request
      if (request.getParameter("help") != null) data = getDescription(task);

      // redirect to home page if there is no task
      if (data == null && task == null) {
        response.setContentType("text/html");
        response
            .getWriter()
            .append(
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><html><head><meta http-equiv=\"REFRESH\" content=\"0;url="
                    + context.getInitParameter("server_path")
                    + "></head><body></body></html>");
        return;
      }

      // process definition request
      if (data == null && task.equals("define")) {
        int id = resolveIntegerArg(request.getParameter("id"), -1);
        int length = resolveIntegerArg(request.getParameter("length"), definer.getDefaultLength());
        int format = resolveIntegerArg(request.getParameter("format"), definer.getDefaultFormat());
        int maxImageWidth =
            resolveIntegerArg(
                request.getParameter("maxImageWidth"), definer.getDefaultMaxImageWidth());
        int maxImageHeight =
            resolveIntegerArg(
                request.getParameter("maxImageHeight"), definer.getDefaultMaxImageHeight());
        int linkDestination =
            resolveIntegerArg(
                request.getParameter("linkDestination"), definer.getDefaultLinkDestination());
        boolean getImages = resolveBooleanArg(request.getParameter("getImages"), false);

        data =
            definer.getDefinition(
                id, length, format, linkDestination, getImages, maxImageWidth, maxImageHeight);
      }

      // all of the remaining tasks require data to be cached, so lets make sure that is finished
      // before continuing.
      if (!cachingThread.isOk()) throw new ServletException("Could not cache wikipedia data");

      double progress = cachingThread.getProgress();
      if (data == null && (progress < 1 || task.equals("progress"))) {
        // still caching up data, not ready to return a response yet.

        data = doc.createElement("loading");
        data.setAttribute("progress", df.format(progress));
        task = "loading";
      }

      // process search request
      if (data == null && task.equals("search")) {
        String term = request.getParameter("term");
        String id = request.getParameter("id");
        int linkLimit =
            resolveIntegerArg(request.getParameter("linkLimit"), searcher.getDefaultMaxLinkCount());
        int senseLimit =
            resolveIntegerArg(
                request.getParameter("senseLimit"), searcher.getDefaultMaxSenseCount());

        if (id == null) data = searcher.doSearch(term, linkLimit, senseLimit);
        else data = searcher.doSearch(Integer.parseInt(id), linkLimit);
      }

      // process compare request
      if (data == null && task.equals("compare")) {
        String term1 = request.getParameter("term1");
        String term2 = request.getParameter("term2");
        int linkLimit =
            resolveIntegerArg(request.getParameter("linkLimit"), comparer.getDefaultMaxLinkCount());
        boolean details =
            resolveBooleanArg(request.getParameter("details"), comparer.getDefaultShowDetails());

        data = comparer.getRelatedness(term1, term2, details, linkLimit);
      }

      // process wikify request
      if (data == null && task.equals("wikify")) {

        if (this.wikifier == null)
          throw new ServletException(
              "Wikifier is not available. You must configure the servlet so that it has access to link detection and disambiguation models.");

        String source = request.getParameter("source");
        int sourceMode =
            resolveIntegerArg(request.getParameter("sourceMode"), Wikifier.SOURCE_AUTODETECT);
        String linkColor = request.getParameter("linkColor");
        String baseColor = request.getParameter("baseColor");
        double minProb =
            resolveDoubleArg(
                request.getParameter("minProbability"), wikifier.getDefaultMinProbability());
        int repeatMode =
            resolveIntegerArg(request.getParameter("repeatMode"), wikifier.getDefaultRepeatMode());
        boolean showTooltips =
            resolveBooleanArg(
                request.getParameter("showTooltips"), wikifier.getDefaultShowTooltips());
        String bannedTopics = request.getParameter("bannedTopics");

        boolean wrapInXml = resolveBooleanArg(request.getParameter("wrapInXml"), true);

        if (wrapInXml) {
          data =
              wikifier.wikifyAndWrapInXML(
                  source,
                  sourceMode,
                  minProb,
                  repeatMode,
                  bannedTopics,
                  baseColor,
                  linkColor,
                  showTooltips);
        } else {
          response.setContentType("text/html");
          response
              .getWriter()
              .append(
                  wikifier.wikify(
                      source,
                      sourceMode,
                      minProb,
                      repeatMode,
                      bannedTopics,
                      baseColor,
                      linkColor,
                      showTooltips));
          return;
        }
      }

      if (data == null) throw new Exception("Unknown Task");

      // wrap data
      Element wrapper = doc.createElement("WikipediaMinerResponse");
      wrapper.setAttribute("server_path", context.getInitParameter("server_path"));
      wrapper.setAttribute("service_name", context.getInitParameter("service_name"));
      wrapper.appendChild(data);

      data = wrapper;

      // Transform or serialize xml data as appropriate

      Transformer tf = null;

      if (request.getParameter("xml") == null) {
        // we need to transform the data into html
        tf = transformersByName.get(task);

        if (request.getParameter("help") != null) tf = transformersByName.get("help");
      }

      if (tf == null) {
        // we need to serialize the data as xml
        tf = transformersByName.get("serializer");
        response.setContentType("application/xml");
      } else {
        // output will be transformed to html
        response.setContentType("text/html");
        response
            .getWriter()
            .append(
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n");
      }

      tf.transform(new DOMSource(data), new StreamResult(response.getWriter()));

    } catch (Exception error) {
      response.reset();
      response.setContentType("application/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.setCharacterEncoding("UTF8");

      Element xmlError = doc.createElement("Error");
      if (error.getMessage() != null) xmlError.setAttribute("message", error.getMessage());

      Element xmlStackTrace = doc.createElement("StackTrace");
      xmlError.appendChild(xmlStackTrace);

      for (StackTraceElement ste : error.getStackTrace()) {

        Element xmlSte = doc.createElement("StackTraceElement");
        xmlSte.setAttribute("message", ste.toString());
        xmlStackTrace.appendChild(xmlSte);
      }
      try {
        transformersByName
            .get("serializer")
            .transform(new DOMSource(xmlError), new StreamResult(response.getWriter()));
      } catch (Exception e) {
        // TODO: something for when an error is thrown processing an error????

      }
      ;
    }
  }
Example #20
0
  private static Interpreter getInterpreter(String contextId) throws EvalError {
    // Get the appropriate interpreter
    Interpreter i = null;
    boolean createdInterp = false;
    synchronized (interpreters) { // serialize two gets of the same name
      i = interpreters.get(contextId);
      if (i == null) {
        i = new Interpreter();
        interpreters.put(contextId, i);
        createdInterp = true;
      }
    }
    if (createdInterp) {
      Log.log("Created context: " + contextId + " (" + i + ")");

      // Now configure stdin and stdout to capture 10k of content
      // Store references to the circular buffers within the interpreter itself.
      // This provides a nice place to store them plus theoretically allows
      // advanced use from within the bsh environment.
      // On Windows print() outputs \r\n but in XQuery that's normalized to \n
      // so the 10k of Java buffer may produce less than 10k of content in XQuery!
      OutputStream circularOutput = new CircularByteArrayOutputStream(10240);
      PrintStream printOutput = new PrintStream(circularOutput);
      i.setOut(printOutput);
      i.set("mljamout", circularOutput);

      OutputStream circularError = new CircularByteArrayOutputStream(10240);
      PrintStream printError = new PrintStream(circularError);
      i.setErr(printError);
      i.set("mljamerr", circularError);

      // Capture the built-in System.out and System.err also.
      // (Commented out since System appears global, can't do per interpreter.)
      // i.set("mljamprintout", printOutput);
      // i.set("mljamprinterr", printError);
      // i.eval("System.setOut(mljamprintout);");
      // i.eval("System.setErr(mljamprinterr);");

      // Need to expose hexdecode() and base64decode() built-in functions
      i.eval("hexdecode(String s) { return com.xqdev.jam.MLJAM.hexDecode(s); }");
      i.eval("base64decode(String s) { return com.xqdev.jam.MLJAM.base64Decode(s); }");

      // Let's tell the context what its id is
      i.set("mljamid", contextId);
    }

    // Update the last accessed time, used for cleaning
    i.set("mljamlast", System.currentTimeMillis());

    // If it's been long enough, go snooping for stale contexts
    if (System.currentTimeMillis() > lastClean + CLEAN_INTERVAL) {
      Log.log("Initiated periodic scan for stale context objects");
      lastClean = System.currentTimeMillis();
      Iterator<Interpreter> itr = interpreters.values().iterator();
      while (itr.hasNext()) {
        Interpreter interp = itr.next();
        Long last = (Long) interp.get("mljamlast");
        if (System.currentTimeMillis() > last + STALE_TIMEOUT) {
          itr.remove();
          Log.log("Staled context: " + interp.get("mljamid") + " (" + interp + ")");
        } else if ((System.currentTimeMillis() > last + TEMP_STALE_TIMEOUT)
            && ("" + interp.get("mljamid")).startsWith("temp:")) {
          itr.remove();
          Log.log("Staled temp context: " + interp.get("mljamid") + " (" + interp + ")");
        }
      }
    }

    return i;
  }
Example #21
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.jsp.jspException");
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    String _value = null;
    try {

      if (_jspx_inited == false) {
        synchronized (this) {
          if (_jspx_inited == false) {
            _jspx_init();
            _jspx_inited = true;
          }
        }
      }
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html; charset=GBK");
      pageContext =
          _jspxFactory.getPageContext(this, request, response, "/error.jsp", true, 8192, true);

      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();

      // HTML // begin [file="/search/accountroleinfo.jsp";from=(2,96);to=(3,0)]
      out.write("\r\n");

      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(3,56);to=(4,0)]
      out.write("\r\n");

      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(4,55);to=(5,0)]
      out.write("\r\n");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(5,0);to=(5,49)]
      /* ----  power:checkpower ---- */
      com.kingsoft.gmsystem.web.taglib.PowerTag _jspx_th_power_checkpower_0 =
          new com.kingsoft.gmsystem.web.taglib.PowerTag();
      _jspx_th_power_checkpower_0.setPageContext(pageContext);
      _jspx_th_power_checkpower_0.setParent(null);
      _jspx_th_power_checkpower_0.setModulecode("accountroleinfo");
      try {
        int _jspx_eval_power_checkpower_0 = _jspx_th_power_checkpower_0.doStartTag();
        if (_jspx_eval_power_checkpower_0 == javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_BUFFERED)
          throw new JspTagException(
              "Since tag handler class com.kingsoft.gmsystem.web.taglib.PowerTag does not implement BodyTag, it can't return BodyTag.EVAL_BODY_TAG");
        if (_jspx_eval_power_checkpower_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
          do {
            // end
            // begin [file="/search/accountroleinfo.jsp";from=(5,0);to=(5,49)]
          } while (_jspx_th_power_checkpower_0.doAfterBody()
              == javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN);
        }
        if (_jspx_th_power_checkpower_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE)
          return;
      } finally {
        _jspx_th_power_checkpower_0.release();
      }
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(5,49);to=(6,0)]
      out.write("\r\n");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(6,2);to=(19,0)]

      String account =
          new String(Util.setNullToEmpty(request.getParameter("account")).getBytes("ISO-8859-1"));
      String roleName =
          new String(Util.setNullToEmpty(request.getParameter("roleName")).getBytes("ISO-8859-1"));
      String zonecode = request.getParameter("zonecode2");
      String game_code = request.getParameter("game_code");
      String gatewayName = request.getParameter("gatewayName");

      GMHelper gh = new GMHelper();
      List gatewayList = gh.getGatewayList();
      Iterator it = gatewayList.iterator();
      Iterator accountRoleIterator = null;
      if (null != request.getAttribute("accountRoleList"))
        accountRoleIterator = ((ArrayList) request.getAttribute("accountRoleList")).iterator();
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(19,2);to=(27,14)]
      out.write(
          "\r\n<html>\r\n\t<!-- InstanceBegin template=\"/Templates/normal.dwt\" codeOutsideHTMLIsLocked=\"false\" -->\r\n\t<head>\r\n\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=GBK\">\r\n\t\t<!-- InstanceBeginEditable name=\"doctitle\" -->\r\n\t\t<title>玩家帐号角色互查</title>\r\n\t\t<!-- InstanceEndEditable -->\r\n\t\t<link href=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(27,17);to=(27,41)]
      out.print(request.getContextPath());
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(27,43);to=(29,8)]
      out.write(
          "/css/public.css\" rel=\"stylesheet\" type=\"text/css\">\r\n\t\t<script language=\"JavaScript\"\r\n\t\t\tsrc=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(29,11);to=(29,35)]
      out.print(request.getContextPath());
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(29,37);to=(31,16)]
      out.write(
          "/js/public.js\"></script>\r\n\t\t<script language=\"JavaScript\">\r\n\t\t\tvar AbsPath=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(31,19);to=(31,43)]
      out.print(request.getContextPath());
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(31,45);to=(34,2)]
      out.write(
          "\";   \r\n\t\t</script>\r\n\t\t<!-- InstanceBeginEditable name=\"head\" -->\r\n\t\t");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(34,4);to=(34,4)]
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(34,6);to=(36,15)]
      out.write("\r\n<script language=\"JavaScript\">\r\nvar game_code=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(36,18);to=(36,48)]
      out.print(Util.setNullToEmpty(game_code));
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(36,50);to=(37,14)]
      out.write("\";\r\nvar zonecode=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(37,17);to=(37,46)]
      out.print(Util.setNullToEmpty(zonecode));
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(37,48);to=(38,18)]
      out.write("\";\r\nvar gatewayNames=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(38,21);to=(38,53)]
      out.print(Util.setNullToEmpty(gatewayName));
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(38,55);to=(41,0)]
      out.write("\";\r\nvar gatewayAry = new Array();\r\n\r\n");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(41,2);to=(49,0)]

      HashMap hm = null;
      int cnt = 0;
      while (it.hasNext()) {
        hm = (HashMap) it.next();
        out.println(
            "gatewayAry["
                + cnt++
                + "] =new Array('"
                + hm.get("game_id")
                + "','"
                + hm.get("zonecode")
                + "','"
                + hm.get("gateway_name")
                + "','"
                + hm.get("area")
                + "','"
                + hm.get("group")
                + "','"
                + hm.get("region")
                + "'); ");
      }
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(49,2);to=(126,19)]
      out.write(
          "\r\n\r\nfunction checkValue()\r\n{\r\n\tvar strErr=\"\";\r\n\tif(IsEmpty(\"account\")&&IsEmpty(\"roleName\")) strErr+=\"*玩家帐号或角色信息不能同时为空\\n\";\r\n\tif(strErr!=\"\"){\r\n\t\talert(strErr);\t\r\n\t\treturn false;\r\n\t}else{\t\t\r\n\t\tvar objDiv = document.all(\"gateway\");\r\n\t\tvar aryCheck = objDiv.all.tags(\"INPUT\");\r\n\t\tvar intCheckLength = aryCheck.length;\r\n\t\tvar gateways = \"\";\r\n\t\tfor (i = 0; i < intCheckLength; i++) {\t\r\n\t\t\tif (aryCheck[i].checked) {\r\n\t\t\t\tgateways += aryCheck[i].name + \",\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tdocument.all(\"gatewayName\").value = gateways;\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\nfunction onChangeGameId()\r\n{\r\n\tvar objSel=document.all(\"zonecode2\");\r\n\tvar objSelTemp=document.all(\"zonecodeTemp\");\r\n\tvar objOption;\r\n\tobjSel.length=0;\r\n\tvar j=0;\r\n\tfor(i=0;i<objSelTemp.length;i++)\r\n\t{\r\n\t\tobjOption=objSelTemp.options[i];\r\n\t\tif(objOption.game_id==document.all(\"game_code\").value)\r\n\t\t{\r\n\t\t \tj+=1;\r\n\t\t \tif(j==1){\r\n\t\t\tobjSel.options[objSel.length]=new Option(0+\".所有区\",'all');\r\n\t\t\tobjSel.options[objSel.length-1].setAttribute(\"game_id\",objOption.game_id);\r\n\t\t \t}\r\n\t\t\tobjSel.options[objSel.length]=new Option(j+\".\"+objOption.text,objOption.value);\r\n\t\t\tobjSel.options[objSel.length-1].setAttribute(\"game_id\",objOption.game_id);\r\n\t\t}\t\t\r\n\t}\r\n}\r\n</script>\r\n\t</head>\r\n\t<!-- InstanceEndEditable -->\r\n\r\n\t<body>\r\n\t\t<table width=\"100%\" height=\"100%\" border=\"0\" align=\"center\"\r\n\t\t\tcellspacing=\"0\">\r\n\t\t\t<tr>\r\n\t\t\t\t<td height=\"20\" bgcolor=\"#BBDDFD\">\r\n\t\t\t\t\t&nbsp;&nbsp;当前位置:\r\n\t\t\t\t\t<!-- InstanceBeginEditable name=\"position\" -->\r\n\t\t\t\t\t<span class=\"title\">查询功能</span> &gt;&gt;\r\n\t\t\t\t\t<span class=\"title\">玩家帐号角色互查</span>\r\n\t\t\t\t\t<!-- InstanceEndEditable -->\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td align=\"center\" valign=\"top\">\r\n\t\t\t\t\t<!-- InstanceBeginEditable name=\"main\" -->\r\n\t\t\t\t\t<div id=\"divPrompt\"\r\n\t\t\t\t\t\tstyle=\"width: 250px; position: absolute; display: none; left: 340px; top: 300px; height: 44px;\">\r\n\t\t\t\t\t\t<table width=\"100%\" height=\"100%\" border=\"1\" align=\"center\"\r\n\t\t\t\t\t\t\tcellspacing=\"0\" bordercolor=\"#0000FF\" bgcolor=\"#FFFFFF\">\r\n\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t<td align=\"center\" valign=\"middle\">\r\n\t\t\t\t\t\t\t\t\t正在查询和等待返回结果,请稍候......\r\n\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t</table>\r\n\t\t\t\t\t</div>\r\n\t\t\t\t\t<br>\r\n\t\t\t\t\t<form action=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(126,22);to=(126,46)]
      out.print(request.getContextPath());
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(126,48);to=(139,8)]
      out.write(
          "/GMCServlet?action=accountroleinfo\" method=\"post\" onsubmit=\"return checkValue()\">\r\n\t\t\t\t\t<table width=\"100%\" border=\"0\" cellspacing=\"0\">\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td align=\"center\">\r\n\t\t\t\t\t\t\t\t所属游戏\r\n\t\t\t\t\t\t\t\t<select id=\"selectGamename\" name=\"game_code\"\r\n\t\t\t\t\t\t\t\t\tonmouseover=\"this.focus()\" onchange=\"onChangeGameId()\">\r\n\t\t\t\t\t\t\t\t\t<OPTION value='88'>\r\n\t\t\t\t\t\t\t\t\t\t剑网3\r\n\t\t\t\t\t\t\t\t\t</OPTION>\r\n\t\t\t\t\t\t\t\t</select>\r\n\t\t\t\t\t\t\t\t所在区\r\n\t\t\t\t\t\t\t\t<select name=\"zonecode2\"></select>\r\n\t\t\t\t\t\t\t\t");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(139,8);to=(140,58)]
      /* ----  display:display ---- */
      com.kingsoft.gmsystem.web.taglib.UserTag _jspx_th_display_display_0 =
          new com.kingsoft.gmsystem.web.taglib.UserTag();
      _jspx_th_display_display_0.setPageContext(pageContext);
      _jspx_th_display_display_0.setParent(null);
      _jspx_th_display_display_0.setDisplayCode("select_zone_all");
      _jspx_th_display_display_0.setProperty("zonecodeTemp");
      _jspx_th_display_display_0.setParameter("display:none");
      try {
        int _jspx_eval_display_display_0 = _jspx_th_display_display_0.doStartTag();
        if (_jspx_eval_display_display_0 == javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_BUFFERED)
          throw new JspTagException(
              "Since tag handler class com.kingsoft.gmsystem.web.taglib.UserTag does not implement BodyTag, it can't return BodyTag.EVAL_BODY_TAG");
        if (_jspx_eval_display_display_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
          do {
            // end
            // HTML // begin [file="/search/accountroleinfo.jsp";from=(140,58);to=(141,8)]
            out.write("\r\n\t\t\t\t\t\t\t\t");

            // end
            // begin [file="/search/accountroleinfo.jsp";from=(141,8);to=(141,26)]
          } while (_jspx_th_display_display_0.doAfterBody()
              == javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN);
        }
        if (_jspx_th_display_display_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) return;
      } finally {
        _jspx_th_display_display_0.release();
      }
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(141,26);to=(149,16)]
      out.write(
          "\r\n\t\t\t\t\t\t\t\t<input type=\"hidden\" name=\"gatewayName\"/>\r\n\t\t\t\t\t\t\t\t所在服\r\n\t\t\t\t\t\t\t\t<div id=\"gateway\">\r\n\t\t\t\t\t\t\t\t</div>\r\n\r\n\t\t\t\t\t\t\t\t玩家帐号\r\n\t\t\t\t\t\t\t\t<input name=\"account\" type=\"text\" class=\"text\"\r\n\t\t\t\t\t\t\t\t\tvalue=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(149,19);to=(149,26)]
      out.print(account);
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(149,28);to=(152,63)]
      out.write(
          "\" onmouseover=\"this.focus()\" size=\"20\"\r\n\t\t\t\t\t\t\t\t\tmaxlength=\"30\">\r\n\t\t\t\t\t\t\t\t玩家角色\r\n\t\t\t\t\t\t\t\t<input type=\"text\" name=\"roleName\" class=\"text\" value=\"");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(152,66);to=(152,74)]
      out.print(roleName);
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(152,76);to=(154,45)]
      out.write(
          "\"\r\n\t\t\t\t\t\t\t\t\tonmouseover=\"this.focus()\" size=\"20\" maxlength=\"30\">\r\n\t\t\t\t\t\t\t\t<input type=\"checkbox\" name=\"isLike\" ");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(154,48);to=(154,128)]
      out.print(Util.setNullToEmpty(request.getParameter("isLike")).equals("") ? "" : "checked");
      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(154,130);to=(183,9)]
      out.write(
          ">模糊查询\r\n\t\t\t\t\t\t\t\t<input type=\"submit\" name=\"btnSearch\" value=\"查询\"/>\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t<td align=\"center\">\r\n\t\t\t\t\t\t\t\t<br>\r\n\t\t\t\t\t\t\t\t<table width=\"773\" border=\"1\" cellpadding=\"0\" cellspacing=\"0\"\r\n\t\t\t\t\t\t\t\t\tclass=\"tablelist\">\r\n\t\t\t\t\t\t\t\t\t<tr align=\"left\" bgcolor=\"#419ADC\">\r\n\t\t\t\t\t\t\t\t\t\t<td height=\"31\" colspan=\"6\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t<font color=#ffffff><b>&nbsp;&#8226;&nbsp;玩家帐号基本信息</b>\r\n\t\t\t\t\t\t\t\t\t\t\t</font>\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t玩家帐号\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t玩家角色\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t所在区\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t所在服\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t");

      // end
      // begin [file="/search/accountroleinfo.jsp";from=(183,11);to=(187,9)]

      if (null != accountRoleIterator) {
        while (accountRoleIterator.hasNext()) {
          hm = (HashMap) accountRoleIterator.next();

          // end
          // HTML // begin [file="/search/accountroleinfo.jsp";from=(187,11);to=(191,11)]
          out.write(
              "\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<tr>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t");

          // end
          // begin [file="/search/accountroleinfo.jsp";from=(191,14);to=(191,32)]
          out.print(hm.get("account"));
          // end
          // HTML // begin [file="/search/accountroleinfo.jsp";from=(191,34);to=(194,11)]
          out.write(
              "\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t");

          // end
          // begin [file="/search/accountroleinfo.jsp";from=(194,14);to=(194,33)]
          out.print(hm.get("RoleName"));
          // end
          // HTML // begin [file="/search/accountroleinfo.jsp";from=(194,35);to=(197,11)]
          out.write(
              "\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t");

          // end
          // begin [file="/search/accountroleinfo.jsp";from=(197,14);to=(197,33)]
          out.print(hm.get("ZoneName"));
          // end
          // HTML // begin [file="/search/accountroleinfo.jsp";from=(197,35);to=(200,11)]
          out.write(
              "\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t\t<td width=\"25%\" height=\"25\" align=\"right\" nowrap>\r\n\t\t\t\t\t\t\t\t\t\t\t");

          // end
          // begin [file="/search/accountroleinfo.jsp";from=(200,14);to=(200,36)]
          out.print(hm.get("GatewayName"));
          // end
          // HTML // begin [file="/search/accountroleinfo.jsp";from=(200,38);to=(203,9)]
          out.write(
              "\r\n\t\t\t\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t\t\t\t\t");

          // end
          // begin [file="/search/accountroleinfo.jsp";from=(203,11);to=(206,9)]

        }
      }

      // end
      // HTML // begin [file="/search/accountroleinfo.jsp";from=(206,11);to=(260,0)]
      out.write(
          "\r\n\t\t\t\t\t\t\t\t</table>\r\n\t\t\t\t\t\t\t</td>\r\n\t\t\t\t\t\t</tr>\r\n\t\t\t\t\t</table>\r\n\t\t\t\t\t</form>\r\n\t\t\t\t\t<script language=\"JavaScript\">\r\ndocument.getElementById(\"zonecode2\").onchange = function onChangeZoneCode(){\r\n\tvar objSel = document.getElementById(\"zonecode2\");\r\n\tvar objOpt = objSel.options[objSel.selectedIndex];\r\n\tvar tmp = \"\";\r\n\tfor(var cnt=0;cnt<gatewayAry.length;cnt++){\r\n\t\tif(gatewayAry[cnt][0]==objOpt.game_id&&gatewayAry[cnt][1]==objOpt.value){\t\r\n\t\t\ttmp +=\" <input type='checkbox' name='\"+gatewayAry[cnt][5]+\"'>\"+gatewayAry[cnt][2];\r\n\t\t}\r\n\t}\r\n\tdocument.getElementById(\"gateway\").innerHTML = tmp;\r\n}\r\n\r\n\t  if(game_code!=\"\"){\r\n\t\tSetSelValue(\"game_code\",game_code);\r\n        onChangeGameId();\r\n        SetSelValue(\"zonecode2\",zonecode);\r\n\t  }else{\r\n          onChangeGameId();\r\n       }\r\n      if(zonecode!=\"\"){\r\n\t\tonChangeZoneCode();\r\n\t\tif(gatewayNames!=\"\"){\r\n\t\t\tvar objDiv = document.all(\"gateway\");\r\n\t\t\tvar aryCheck = objDiv.all.tags(\"INPUT\");\r\n\t\t\tvar intCheckLength = aryCheck.length;\r\n\t\t\tvar gateways = \"\";\r\n\t\t\tfor (i = 0; i < intCheckLength; i++) {\t\r\n\t\t\t\tif (gatewayNames.indexOf(aryCheck[i].name+\",\")>-1) {\r\n\t\t\t\t\taryCheck[i].checked=true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\t\t\r\n\t\t\r\n   \t  }\r\n\t</script>\r\n\t\t\t\t\t<!-- InstanceEndEditable -->\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t\t<tr>\r\n\t\t\t\t<td height=\"16\" align=\"center\" bgcolor=\"#BBDDFD\">\r\n\t\t\t\t\tCopyright &copy; 2005 Kingsoft Corp,All Rights Reserved\r\n\t\t\t\t</td>\r\n\t\t\t</tr>\r\n\t\t</table>\r\n\t</body>\r\n\t<!-- InstanceEnd -->\r\n</html>\r\n");

      // end

    } catch (Throwable t) {
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    context = config.getServletContext();

    TextProcessor tp = new CaseFolder();

    try {
      wikipedia =
          new Wikipedia(
              context.getInitParameter("mysql_server"),
              context.getInitParameter("mysql_database"),
              context.getInitParameter("mysql_user"),
              context.getInitParameter("mysql_password"));
    } catch (Exception e) {
      throw new ServletException("Could not connect to wikipedia database.");
    }

    // Escaper escaper = new Escaper() ;

    definer = new Definer(this);
    comparer = new Comparer(this);
    searcher = new Searcher(this);

    try {
      wikifier = new Wikifier(this, tp);

    } catch (Exception e) {
      System.err.println("Could not initialize wikifier");
    }

    try {
      File dataDirectory = new File(context.getInitParameter("data_directory"));

      if (!dataDirectory.exists() || !dataDirectory.isDirectory()) {
        throw new Exception();
      }

      cachingThread = new CacherThread(dataDirectory, tp);
      cachingThread.start();
    } catch (Exception e) {
      throw new ServletException("Could not locate wikipedia data directory.");
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();

      transformersByName = new HashMap<String, Transformer>();
      transformersByName.put(
          "help", buildTransformer("help", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "loading", buildTransformer("loading", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "search", buildTransformer("search", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "compare", buildTransformer("compare", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "wikify", buildTransformer("wikify", new File("/research/wikipediaminer/web/xsl"), tf));

      Transformer serializer = TransformerFactory.newInstance().newTransformer();
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
      transformersByName.put("serializer", serializer);

    } catch (Exception e) {
      throw new ServletException("Could not load xslt library.");
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws javax.servlet.ServletException if a servlet-specific error occurs
   * @throws java.io.IOException if an I/O error occurs
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    XDebug xdebug = new XDebug();
    xdebug.startTimer();

    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();

    try {
      List resultsList = new LinkedList();

      // Get the gene list
      String geneList = request.getParameter(QueryBuilder.GENE_LIST);
      if (request instanceof XssRequestWrapper) {
        geneList = ((XssRequestWrapper) request).getRawParameter(QueryBuilder.GENE_LIST);
      }
      String cancerStudyIdListString = request.getParameter(QueryBuilder.CANCER_STUDY_LIST);
      String[] cancerStudyIdList = cancerStudyIdListString.split(",");

      // Get the priority
      Integer dataTypePriority;
      try {
        dataTypePriority =
            Integer.parseInt(request.getParameter(QueryBuilder.DATA_PRIORITY).trim());
      } catch (NumberFormatException e) {
        dataTypePriority = 0;
      }

      //  Cancer All Cancer Studies
      List<CancerStudy> cancerStudiesList = accessControl.getCancerStudies();
      HashMap<String, Boolean> studyMap = new HashMap<>();
      for (String studyId : cancerStudyIdList) {
        studyMap.put(studyId, Boolean.TRUE);
      }
      for (CancerStudy cancerStudy : cancerStudiesList) {
        String cancerStudyId = cancerStudy.getCancerStudyStableId();
        if (!studyMap.containsKey(cancerStudyId)) {
          continue;
        }
        if (cancerStudyId.equalsIgnoreCase("all")) continue;

        Map cancerMap = new LinkedHashMap();
        cancerMap.put("studyId", cancerStudyId);
        cancerMap.put("typeOfCancer", cancerStudy.getTypeOfCancerId());

        //  Get all Genetic Profiles Associated with this Cancer Study ID.
        ArrayList<GeneticProfile> geneticProfileList =
            GetGeneticProfiles.getGeneticProfiles(cancerStudyId);

        //  Get all Patient Lists Associated with this Cancer Study ID.
        ArrayList<SampleList> sampleSetList = GetSampleLists.getSampleLists(cancerStudyId);

        //  Get the default patient set
        AnnotatedSampleSets annotatedSampleSets =
            new AnnotatedSampleSets(sampleSetList, dataTypePriority);
        SampleList defaultSampleSet = annotatedSampleSets.getDefaultSampleList();
        if (defaultSampleSet == null) {
          continue;
        }

        List<String> sampleIds = defaultSampleSet.getSampleList();

        //  Get the default genomic profiles
        CategorizedGeneticProfileSet categorizedGeneticProfileSet =
            new CategorizedGeneticProfileSet(geneticProfileList);
        HashMap<String, GeneticProfile> defaultGeneticProfileSet = null;
        switch (dataTypePriority) {
          case 2:
            defaultGeneticProfileSet = categorizedGeneticProfileSet.getDefaultCopyNumberMap();
            break;
          case 1:
            defaultGeneticProfileSet = categorizedGeneticProfileSet.getDefaultMutationMap();
            break;
          case 0:
          default:
            defaultGeneticProfileSet =
                categorizedGeneticProfileSet.getDefaultMutationAndCopyNumberMap();
        }

        String mutationProfile = "", cnaProfile = "";
        for (GeneticProfile geneticProfile : defaultGeneticProfileSet.values()) {
          GeneticAlterationType geneticAlterationType = geneticProfile.getGeneticAlterationType();
          if (geneticAlterationType.equals(GeneticAlterationType.COPY_NUMBER_ALTERATION)) {
            cnaProfile = geneticProfile.getStableId();
          } else if (geneticAlterationType.equals(GeneticAlterationType.MUTATION_EXTENDED)) {
            mutationProfile = geneticProfile.getStableId();
          }
        }

        cancerMap.put("mutationProfile", mutationProfile);
        cancerMap.put("cnaProfile", cnaProfile);

        cancerMap.put("caseSetId", defaultSampleSet.getStableId());
        cancerMap.put("caseSetLength", sampleIds.size());

        ProfileDataSummary genomicData =
            getGenomicData(
                cancerStudyId,
                defaultGeneticProfileSet,
                defaultSampleSet,
                geneList,
                sampleSetList,
                request,
                response);

        ArrayList<GeneWithScore> geneFrequencyList = genomicData.getGeneFrequencyList();
        ArrayList<String> genes = new ArrayList<String>();
        for (GeneWithScore geneWithScore : geneFrequencyList) genes.add(geneWithScore.getGene());
        int noOfMutated = 0,
            noOfCnaUp = 0,
            noOfCnaDown = 0,
            noOfCnaLoss = 0,
            noOfCnaGain = 0,
            noOfOther = 0,
            noOfAll = 0;

        boolean skipStudy = defaultGeneticProfileSet.isEmpty();
        if (!skipStudy) {

          for (String sampleId : sampleIds) {
            if (sampleId == null) {
              continue;
            }
            if (!genomicData.isCaseAltered(sampleId)) continue;

            boolean isAnyMutated = false,
                isAnyCnaUp = false,
                isAnyCnaDown = false,
                isAnyCnaLoss = false,
                isAnyCnaGain = false;

            for (String gene : genes) {
              isAnyMutated |= genomicData.isGeneMutated(gene, sampleId);
              GeneticTypeLevel cnaLevel = genomicData.getCNALevel(gene, sampleId);
              boolean isCnaUp = cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.Amplified);
              isAnyCnaUp |= isCnaUp;
              boolean isCnaDown =
                  cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.HomozygouslyDeleted);
              isAnyCnaDown |= isCnaDown;
              boolean isCnaLoss =
                  cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.HemizygouslyDeleted);
              isAnyCnaLoss |= isCnaLoss;
              boolean isCnaGain = cnaLevel != null && cnaLevel.equals(GeneticTypeLevel.Gained);
              isAnyCnaGain |= isCnaGain;
            }

            boolean isAnyCnaChanged = isAnyCnaUp || isAnyCnaDown;
            if (isAnyMutated && !isAnyCnaChanged) noOfMutated++;
            else if (isAnyMutated && isAnyCnaChanged) noOfOther++;
            else if (isAnyCnaUp) noOfCnaUp++;
            else if (isAnyCnaDown) noOfCnaDown++;
            else if (isAnyCnaGain) noOfCnaGain++;
            else if (isAnyCnaLoss) noOfCnaLoss++;

            noOfAll++;
          }
        }

        Map alterations = new LinkedHashMap();
        cancerMap.put("alterations", alterations);
        alterations.put("all", noOfAll);
        alterations.put("mutation", noOfMutated);
        alterations.put("cnaUp", noOfCnaUp);
        alterations.put("cnaDown", noOfCnaDown);
        alterations.put("cnaLoss", noOfCnaLoss);
        alterations.put("cnaGain", noOfCnaGain);
        alterations.put("other", noOfOther);
        cancerMap.put("genes", genes);
        cancerMap.put("skipped", skipStudy);

        resultsList.add(cancerMap);
      }

      JSONValue.writeJSONString(resultsList, writer);
    } catch (DaoException e) {
      throw new ServletException(e);
    } catch (ProtocolException e) {
      throw new ServletException(e);
    } finally {
      writer.close();
    }
  }