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");
 }
Esempio n. 2
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
Esempio n. 3
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);
    }
  }
Esempio n. 4
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());
    }
  }
 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);
       }
     }
   }
 }
  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.");
    }
  }
  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) {
      }
    }
  }
Esempio n. 10
0
  /**
   * 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();
    }
  }
Esempio n. 11
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;
  }