Ejemplo n.º 1
0
    public MisoPrintService mapRow(ResultSet rs, int rowNum) throws SQLException {
      try {
        MisoPrintService printService = new DefaultPrintService();
        printService.setServiceId(rs.getLong("serviceId"));
        printService.setName(rs.getString("serviceName"));
        printService.setEnabled(rs.getBoolean("enabled"));
        printService.setPrintServiceFor(
            Class.forName(rs.getString("printServiceFor")).asSubclass(Barcodable.class));

        PrintContext pc = printManager.getPrintContext(rs.getString("contextName"));
        JSONObject contextFields = JSONObject.fromObject(rs.getString("contextFields"));
        PrintServiceUtils.mapJSONToContextFields(contextFields, pc);

        pc.getLabelFactory().setSecurityManager(securityManager);
        pc.getLabelFactory().setFilesManager(misoFilesManager);

        printService.setPrintContext(pc);

        return printService;
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (JSONException e) {
        e.printStackTrace();
      }
      return null;
    }
Ejemplo n.º 2
0
    /**
     * Parses the raw response from Google
     *
     * @param rawResponse The raw, unparsed response from Google
     * @return Returns the parsed response.
     */
    void parseResponse(String rawResponse, GoogleResponse googleResponse) {
        try {
            JSONObject json = JSONObject.fromObject(rawResponse);
            int status = json.getInt("status");

            if (status == 0) {
                JSONArray hypotheses = json.getJSONArray("hypotheses");

                for (int index = 0; index < hypotheses.size(); index++) {
                    JSONObject hypothese = (JSONObject) hypotheses.get(index);

                    if (hypothese.containsKey(CONFIDENCE)) {
                        googleResponse.setResponse(hypothese.getString("utterance"));
                        googleResponse.setConfidence(hypothese.getDouble(CONFIDENCE) + "");
                    } else {
                        googleResponse.getOtherPossibleResponses().add(hypothese.getString("utterance"));
                    }
                }
            } else {
                Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, "status: {0}", status);
            }
        } catch (JSONException e) {
            Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, e.getLocalizedMessage(), e);
        }
    }
Ejemplo n.º 3
0
  /** Accepts submission from the configuration page. */
  @RequirePOST
  public synchronized void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException, FormException {
    checkPermission(CONFIGURE);

    description = req.getParameter("description");

    keepDependencies = req.getParameter("keepDependencies") != null;

    try {
      JSONObject json = req.getSubmittedForm();

      setDisplayName(json.optString("displayNameOrNull"));

      if (req.getParameter("logrotate") != null)
        logRotator = LogRotator.DESCRIPTOR.newInstance(req, json.getJSONObject("logrotate"));
      else logRotator = null;

      DescribableList<JobProperty<?>, JobPropertyDescriptor> t =
          new DescribableList<JobProperty<?>, JobPropertyDescriptor>(NOOP, getAllProperties());
      t.rebuild(
          req,
          json.optJSONObject("properties"),
          JobPropertyDescriptor.getPropertyDescriptors(Job.this.getClass()));
      properties.clear();
      for (JobProperty p : t) {
        p.setOwner(this);
        properties.add(p);
      }

      submit(req, rsp);

      save();
      ItemListener.fireOnUpdated(this);

      String newName = req.getParameter("name");
      final ProjectNamingStrategy namingStrategy = Jenkins.getInstance().getProjectNamingStrategy();
      if (newName != null && !newName.equals(name)) {
        // check this error early to avoid HTTP response splitting.
        Jenkins.checkGoodName(newName);
        namingStrategy.checkName(newName);
        rsp.sendRedirect("rename?newName=" + URLEncoder.encode(newName, "UTF-8"));
      } else {
        if (namingStrategy.isForceExistingJobs()) {
          namingStrategy.checkName(name);
        }
        FormApply.success(".").generateResponse(req, rsp, null);
      }
    } catch (JSONException e) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      pw.println("Failed to parse form data. Please report this problem as a bug");
      pw.println("JSON=" + req.getSubmittedForm());
      pw.println();
      e.printStackTrace(pw);

      rsp.setStatus(SC_BAD_REQUEST);
      sendError(sw.toString(), req, rsp, true);
    }
  }
  /**
   * Obtiene los numeros de telefono movil de otros bancos que se encuentren registrados en el
   * perfil del cliente y que tengan estatus activo, ademas de las cuentas propias y saldos para
   * iniciar el flujo de transferencias a otros bancos.
   *
   * @param req HttpServletRequest
   * @param resp HttpServletResponse
   * @return ModelAndView
   * @throws Exception la exception
   */
  public ModelAndView getMovilesOtrosBancos(HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    JSONResponseBean response = new JSONResponseBean();
    ClienteBean cliente = (ClienteBean) req.getSession().getAttribute(LITERAL_CLIENTE);

    if (cliente != null) {
      try {
        BitacoraBean bitacora = getBitacoraBean(req, cliente.getClaveCliente());
        JSONObject getAllJSON = getJSONRequestObject(req);
        boolean getAll = false;

        try {
          getAll = getAllJSON.getBoolean("getAll");
        } catch (JSONException e) {
          LOG.info(
              "El JSON no contienen el atributo getAll, se trata transferencia como Operacion Rapida: "
                  .concat(e.getMessage()));
        }

        JSONObject jsonResponse = new JSONObject();
        List<NumeroMovilRegistrado> asociaciones =
            movilTercerosService.getMovilesTercerosActivos(
                cliente,
                SantanderConstantesMovilService.TIPO_CUENTA_MOVIL_INTERBANCARIA,
                SantanderConstantesMovilService.TTMO);
        jsonResponse.put("movilesTerceros", asociaciones);

        if (getAll) {
          List<CuentaBean> cuentas = cuentaService.getCuentasPropiasCheques(cliente);
          JSONArray jSONCuentas = JSONArray.fromObject(cuentas);
          jsonResponse.put("cuentas", jSONCuentas.toString());

          SaldoContainerBean saldoCheques =
              saldoService.getSaldosCuentasChequeras(cliente, bitacora, false);
          JSONObject jSONSaldoCheques = JSONObject.fromObject(saldoCheques);
          jsonResponse.put("saldos", jSONSaldoCheques.toString());
        }

        response.setDto(jsonResponse.toString());
        response.setError(ErrorBean.SUCCESS);
        req.getSession().setAttribute(SALTOSUCCESS, LITERAL_0_01);
      } catch (BusinessException e) {
        response.setError(e.getError());
      }
    } else {
      response.setError(LITERAL_GBL_03);
    }

    return getResponseView(response);
  }
Ejemplo n.º 5
0
  /**
   * Get the market depth as a Depth object.
   *
   * @param currencyPair The queried currency pair.
   * @throws TradeDataNotAvailableException if the depth is not available.
   */
  public Depth getDepth(CurrencyPair currencyPair) throws TradeDataNotAvailableException {

    if (!isSupportedCurrencyPair(currencyPair)) {
      throw new CurrencyNotSupportedException(
          "Currency pair: " + currencyPair.toString() + " is currently not supported on " + _name);
    }

    // Create the URL to fetch the depth.
    String url = _url + "depth_" + currencyPair.getCurrency().toString().toLowerCase() + "_json.js";

    // Do the actual request.
    String requestResult = HttpUtils.httpGet(url);

    if (requestResult != null) { // Request sucessful?

      try {

        // Convert the result to JSON.
        JSONObject requestResultJSON = (JSONObject) JSONObject.fromObject(requestResult);

        // Try to convert the response to a depth object and return it.
        return new HuobiDepth(requestResultJSON, currencyPair, this);

      } catch (JSONException je) {

        LogUtils.getInstance()
            .getLogger()
            .error("Cannot parse " + this._name + " depth return: " + je.toString());

        throw new TradeDataNotAvailableException("cannot parse depth data from " + this._name);
      }
    }

    // Response from server was null.
    throw new TradeDataNotAvailableException(
        this._name + " server did not respond to depth request");
  }
Ejemplo n.º 6
0
  /**
   * Process HTTP request.
   *
   * @param act Action.
   * @param req Http request.
   * @param res Http response.
   */
  private void processRequest(String act, HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("application/json");
    res.setCharacterEncoding("UTF-8");

    GridRestCommand cmd = command(req);

    if (cmd == null) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      return;
    }

    if (!authChecker.apply(req.getHeader("X-Signature"))) {
      res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      return;
    }

    GridRestResponse cmdRes;

    Map<String, Object> params = parameters(req);

    try {
      GridRestRequest cmdReq = createRequest(cmd, params, req);

      if (log.isDebugEnabled()) log.debug("Initialized command request: " + cmdReq);

      cmdRes = hnd.handle(cmdReq);

      if (cmdRes == null)
        throw new IllegalStateException("Received null result from handler: " + hnd);

      byte[] sesTok = cmdRes.sessionTokenBytes();

      if (sesTok != null) cmdRes.setSessionToken(U.byteArray2HexString(sesTok));

      res.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
      res.setStatus(HttpServletResponse.SC_OK);

      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      cmdRes = new GridRestResponse(STATUS_FAILED, e.getMessage());
    } catch (Throwable e) {
      U.error(log, "Failed to process HTTP request [action=" + act + ", req=" + req + ']', e);

      throw e;
    }

    JsonConfig cfg = new GridJettyJsonConfig();

    // Workaround for not needed transformation of string into JSON object.
    if (cmdRes.getResponse() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getClass(), "response", SKIP_STR_VAL_PROC);

    if (cmdRes.getResponse() instanceof GridClientTaskResultBean
        && ((GridClientTaskResultBean) cmdRes.getResponse()).getResult() instanceof String)
      cfg.registerJsonValueProcessor(cmdRes.getResponse().getClass(), "result", SKIP_STR_VAL_PROC);

    JSON json;

    try {
      json = JSONSerializer.toJSON(cmdRes, cfg);
    } catch (JSONException e) {
      U.error(log, "Failed to convert response to JSON: " + cmdRes, e);

      json = JSONSerializer.toJSON(new GridRestResponse(STATUS_FAILED, e.getMessage()), cfg);
    }

    try {
      if (log.isDebugEnabled())
        log.debug("Parsed command response into JSON object: " + json.toString(2));

      res.getWriter().write(json.toString());

      if (log.isDebugEnabled())
        log.debug(
            "Processed HTTP request [action=" + act + ", jsonRes=" + cmdRes + ", req=" + req + ']');
    } catch (IOException e) {
      U.error(log, "Failed to send HTTP response: " + json.toString(2), e);
    }
  }
Ejemplo n.º 7
0
  public String processTxn() {
    String resultHtml = null;
    session = ActionContext.getContext().getSession();
    mockLogin();

    String unique = new String();
    String application_name = (String) session.get("APPLICATION_NAME");
    String transcode = "CNUCNF"; // will be coming form command

    // creating a unique id.
    // unique id = transaction code.
    unique += (String) session.get("NET_ID");
    unique += "_" + System.currentTimeMillis();

    String xml = "<?xml version=\"1.0\"?>";
    xml += "<IDCT>";
    xml += "<TRANS_CODE>" + transcode + "</TRANS_CODE>";
    xml += "<IDCT_ID>" + application_name + "_" + unique + "</IDCT_ID>";
    xml += "<DATETIME>" + new Date().toString() + "</DATETIME>";
    xml += "<NET_ID>" + (String) session.get("NET_ID") + "</NET_ID>";
    xml += "<MESSAGE_VER_NO>1.0</MESSAGE_VER_NO>";
    xml += "<CHANNEL_ID>WEB</CHANNEL_ID>";
    xml += "<MESSAGE_DIGEST>NO_DATA</MESSAGE_DIGEST>";
    xml += "<IDCT_STATUS>NO_DATA</IDCT_STATUS>";
    xml += "<IDCT_ERR_CODE>NO_DATA</IDCT_ERR_CODE>";
    xml += "<IDCT_MESSAGE_TYPE>01</IDCT_MESSAGE_TYPE>";

    try {
      JSONObject jobj1 = JSONObject.fromObject(submitdatatxncode);

      JSONObject txnrec = jobj1.getJSONObject("txnrec");
      JSONObject single = txnrec.getJSONObject("single");
      JSONArray multiple = txnrec.getJSONArray("multiple");

      final JAXBContext jc = JAXBContext.newInstance(Root.class);
      final Root root =
          (Root)
              jc.createUnmarshaller()
                  .unmarshal(
                      new File(
                          "C:/Eclipse/workspace1/FEtranslator1/src/repo/txnmap/nrow_txnmap.xml"));

      for (Txn txn : root.getTxn()) {
        if (txn.getId().equals(transcode)) {
          String strReqSingle = txn.getReq().getSingle();
          if (strReqSingle != null) {
            String[] arSingle = strReqSingle.split(",");
          }
          String strReqMultiple = txn.getReq().getSingle();
          if (strReqMultiple != null) {
            String[] arMultiple = strReqMultiple.split(",");
          }
        }
      }

    } catch (JSONException e) {
      logger.debug("submitdata parsing error", e);
      e.printStackTrace();
    } catch (JAXBException e) {
      logger.debug("submitdata parsing error", e);
      e.printStackTrace();
    }

    inputStream = new StringBufferInputStream(resultHtml);
    return "saveajax";
  }
Ejemplo n.º 8
0
  public void handlRequest(HttpServletRequest request, HttpServletResponse response) {

    printRequest(request);

    String method = request.getParameter(ServiceConstant.METHOD);
    CommonService obj = null;

    try {
      obj = CommonService.createServiceObjectByMethod(method);
    } catch (InstantiationException e1) {
      log.severe(
          "<handlRequest> but exception while create service object for method("
              + method
              + "), exception="
              + e1.toString());
      e1.printStackTrace();
    } catch (IllegalAccessException e1) {
      log.severe(
          "<handlRequest> but exception while create service object for method("
              + method
              + "), exception="
              + e1.toString());
      e1.printStackTrace();
    }

    try {

      if (obj == null) {
        sendResponseByErrorCode(response, ErrorCode.ERROR_PARA_METHOD_NOT_FOUND);
        return;
      }

      obj.setCassandraClient(cassandraClient);
      obj.setMongoClient(mongoClient);
      obj.setRequest(request);

      if (!obj.validateSecurity(request)) {
        sendResponseByErrorCode(response, ErrorCode.ERROR_INVALID_SECURITY);
        return;
      }

      // parse request parameters
      if (!obj.setDataFromRequest(request)) {
        sendResponseByErrorCode(response, obj.resultCode);
        return;
      }

      // print parameters
      obj.printData();

      // handle request
      obj.handleData();
    } catch (HectorException e) {
      obj.resultCode = ErrorCode.ERROR_CASSANDRA;
      log.severe("catch DB exception=" + e.toString());
      e.printStackTrace();
    } catch (JSONException e) {
      obj.resultCode = ErrorCode.ERROR_JSON;
      log.severe("catch JSON exception=" + e.toString());
      e.printStackTrace();
    } catch (Exception e) {
      obj.resultCode = ErrorCode.ERROR_SYSTEM;
      log.severe("catch general exception=" + e.toString());
      e.printStackTrace();
    } finally {
    }

    String responseData = obj.getResponseString();

    // send back response
    sendResponse(response, responseData);
  }