コード例 #1
0
  /**
   * 商品コードから商品数を取得します(前方一致).
   *
   * @return 商品数
   * @throws Exception
   */
  @Execute(validator = false)
  public String getProductByCodeLike() throws Exception {
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    try {

      List<Product> productList =
          productService.findProductByCodeLike(commonProductForm.productCode);
      if (productList == null || productList.size() == 0) {
        map.put(Param.PRODUCT_COUNT, String.valueOf("0"));
        ResponseUtil.write(JSON.encode(map), "text/javascript");
      } else {

        if (productList.size() == 1) {
          Product product = productList.get(0);
          BeanMap bmap = super.createBeanMapWithNullToEmpty(product);
          bmap.put(Param.PRODUCT_COUNT, String.valueOf(productList.size()));
          ResponseUtil.write(JSON.encode(bmap), "text/javascript");
        } else {
          map.put(Param.PRODUCT_COUNT, String.valueOf(productList.size()));
          ResponseUtil.write(JSON.encode(map), "text/javascript");
        }
      }

    } catch (ServiceException e) {
      super.errorLog(e);
      throw e;
    }

    return null;
  }
コード例 #2
0
  /**
   * 閾値判定の定義を新規に追加する。
   *
   * @param mulResGraphDefinition 閾値判定の定義のJSONデータ
   * @return 追加した閾値判定の定義
   */
  @RequestMapping(value = "/add", method = RequestMethod.POST)
  @ResponseBody
  public ResponseDto add(
      @RequestParam(value = "mulResGraphDefinition") final String mulResGraphDefinition) {
    ResponseDto responseDto = new ResponseDto();
    MultipleResourceGraphDefinitionDto multipleResourceGraphDefinitionDto =
        JSON.decode(mulResGraphDefinition, MultipleResourceGraphDefinitionDto.class);

    String multipleResourceGraphName =
        multipleResourceGraphDefinitionDto.getMultipleResourceGraphName();
    boolean hasSameMulResGraphName =
        this.multipleResourceGraphService_.hasSamemultipleResourceGraphName(
            multipleResourceGraphName);
    if (hasSameMulResGraphName) {
      String errorMessage = MessageUtil.getMessage("WEWD0131", multipleResourceGraphName);
      responseDto.setResult(ResponseConstants.RESULT_FAIL);
      responseDto.setMessage(errorMessage);
      return responseDto;
    }

    MultipleResourceGraphInfo multipleResourceGraphInfo =
        this.multipleResourceGraphService_.convertMultipleResourceGraphInfo(
            multipleResourceGraphDefinitionDto);

    // DBに追加する
    MultipleResourceGraphDefinitionDto addedDefinitionDto =
        this.multipleResourceGraphService_.insertMultipleResourceGraphInfo(
            multipleResourceGraphInfo);

    responseDto.setData(addedDefinitionDto);
    responseDto.setResult(ResponseConstants.RESULT_SUCCESS);
    return responseDto;
  }
コード例 #3
0
  /**
   * 顧客コードから顧客と請求先情報を取得します( 完全一致版).<br>
   * 顧客コードが完全に一致しない場合は値が返りません.
   *
   * @return 納入先情報(1件)
   * @throws Exception
   */
  @Execute(validator = false, urlPattern = "getCustomerAndBillInfosByCustomerCode/{customerCode}")
  public String getCustomerAndBillInfosByCustomerCode() throws Exception {

    // 顧客コードを指定しない場合は検索しません
    if (!StringUtil.hasLength(commonDeliveryForm.customerCode)) {
      ResponseUtil.write("", "text/javascript");
      return null;
    }

    List<DeliveryAndPre> deliveryList;
    try {
      deliveryList =
          deliveryService.searchDeliveryByCompleteCustomerCode(commonDeliveryForm.customerCode);

    } catch (ServiceException e) {
      super.errorLog(e);
      throw e;
    }

    // 納入先コードを指定した検索なので複数はかえらない
    if (deliveryList.size() == 1) {

      BeanMap map = super.createBeanMapWithNullToEmpty(deliveryList.get(0));
      ResponseUtil.write(JSON.encode(map), "text/javascript");

    } else {
      ResponseUtil.write("", "text/javascript");
    }
    return null;
  }
コード例 #4
0
  @Test
  public void testCreateSignedRequestConfig() throws ParseException {
    Date now = DateUtil.now();

    String method = "POST";
    URI uri = URI.create("http://api.tuppari.com/test?a=v1&b=v2");
    String operation = "CreateApplication";
    Map<String, Object> body = new LinkedHashMap<String, Object>();
    body.put("applicationName", "example1");
    String accessKeyId = "accessKeyId";
    String accessSecretKey = "accessSecretKey";

    Map<String, Object> config =
        SignUtil.createSignedRequestConfig(
            method, uri, operation, body, accessKeyId, accessSecretKey);

    assertThat((URI) config.get("uri"), is(uri));
    assertThat((String) config.get("body"), is(JSON.encode(body)));

    Map<String, String> headers = (Map<String, String>) config.get("headers");
    assertThat(headers.get("Host"), is("api.tuppari.com"));
    assertThat(headers.get("Content-Type"), is("application/json"));
    assertThat(headers.get("X-Tuppari-Date"), is("Thu, 01 Jan 1970 00:00:00 GMT"));
    assertThat(headers.get("X-Tuppari-Operation"), is("CreateApplication"));
    assertThat(
        headers.get("Authorization"),
        is(
            "HMAC-SHA256 Credential=accessKeyId,SignedHeaders=content-type;host;x-tuppari-date;x-tuppari-operation,Signature=f35767c9fdba4ba5d5bbbf1c622fceed0dbaeb210303bb56b419c6a51bcf1e5d"));
  }
コード例 #5
0
  /**
   * レートIDからレートマスタの情報を取得します.
   *
   * @return レートマスタ情報
   * @throws Exception
   */
  @Execute(validator = false, urlPattern = "getRateInfosByRateId/{rateId}")
  public String getRateInfosByRateId() throws Exception {

    if (!StringUtil.hasLength(commonRateForm.rateId)) {
      ResponseUtil.write("", "text/javascript");
      return null;
    }

    try {

      Rate rate = rateService.findById(commonRateForm.rateId);

      if (rate != null) {

        BeanMap map =
            Beans.createAndCopy(BeanMap.class, rate)
                .dateConverter(Constants.FORMAT.TIMESTAMP, "creDatetm", "updDatetm")
                .execute();

        BeanMap bmap = super.createBeanMapWithNullToEmpty(map);
        ResponseUtil.write(JSON.encode(bmap), "text/javascript");

      } else {
        ResponseUtil.write("", "text/javascript");
      }

    } catch (ServiceException e) {
      super.errorLog(e);
      throw e;
    }

    return null;
  }
コード例 #6
0
ファイル: RedmineApiTest.java プロジェクト: akikinyan/testapp
  /**
   * チケットの作成
   *
   * @return 成功または失敗を返す (true:成功, false:失敗)
   */
  public static Boolean createTicket() {
    // チケットの取得
    RedmineManager mgr = RedmineManagerFactory.createWithApiKey(redmineHost, apiAccessKey);
    try {

      // チケットを作成する
      Issue ticket = IssueFactory.create(null);

      // プロジェクトの指定
      int intProjectKey = mgr.getProjectManager().getProjectByKey(projectKey).getId();
      Project project = ProjectFactory.create(intProjectKey);
      ticket.setProject(project);

      // チケット内容の設定
      ticket.setSubject("デプロイ成功.");
      ticket.setDescription("デプロイを実行しました。" + StringUtil.getTimestamp());

      // トラッカー指定
      Tracker tracker = TrackerFactory.create(3, "Support");
      ticket.setTracker(tracker);

      // 開始日
      ticket.setStartDate(Calendar.getInstance().getTime());

      // 期日
      ticket.setDueDate(Calendar.getInstance().getTime());

      // ステータス (new)
      ticket.setStatusId(1);

      // 開始日
      ticket.setStartDate(Calendar.getInstance().getTime());

      // 期日
      ticket.setDueDate(Calendar.getInstance().getTime());

      // 進捗率
      ticket.setDoneRatio(100);

      // 担当者 (カレントユーザ)
      User assignee = mgr.getUserManager().getCurrentUser();
      ticket.setAssignee(assignee);

      // チケットの登録処理
      IssueManager issueMgr = mgr.getIssueManager();
      Issue newIssue = issueMgr.createIssue(ticket);
      issueMgr.update(newIssue);

      // 処理結果
      System.out.println(JSON.encode(newIssue, true));
      System.out.println("success.");

      return true;

    } catch (Exception e) {
      System.out.println(e.getStackTrace());
      return false;
    }
  }
コード例 #7
0
ファイル: QiitaExecutor.java プロジェクト: jabaraster/qiita4j
 <T extends QiitaResponse> T putBody(String apiPath, String body, Class<T> responseType)
     throws IOException, QiitaException {
   HttpPut request = new HttpPut(createUrl(apiPath, token));
   setBody(request, body);
   HttpResponse response = execute(request);
   verifyStatusCode(response, SC_OK);
   try (InputStream in = response.getEntity().getContent()) {
     return JSON.decode(in, responseType);
   }
 }
コード例 #8
0
ファイル: QiitaExecutor.java プロジェクト: jabaraster/qiita4j
 <T extends QiitaResponse> T getContent(
     String apiPath, Map<String, String> params, Class<T> responseType)
     throws IOException, QiitaException {
   HttpGet request = new HttpGet(createQuery(createUrl(apiPath, token), params));
   HttpResponse response = execute(request);
   verifyStatusCode(response, SC_OK);
   try (InputStream in = response.getEntity().getContent()) {
     T res = JSON.decode(in, responseType);
     return res;
   }
 }
コード例 #9
0
 /**
  * 出力するJSONのインタフェースを整形する
  *
  * @param jtmap_json
  * @return
  */
 @SuppressWarnings("unchecked")
 protected String jsonFormatter(String jtmap_json) {
   Integer id = 1;
   ArrayList<LinkedHashMap<String, String>> formatted_pojo_array =
       new ArrayList<LinkedHashMap<String, String>>();
   LinkedHashMap<String, ArrayList<ArrayList<LinkedHashMap<String, String>>>> jtmap_pojo =
       (LinkedHashMap<String, ArrayList<ArrayList<LinkedHashMap<String, String>>>>)
           JSON.decode(jtmap_json);
   for (ArrayList<LinkedHashMap<String, String>> addrs : jtmap_pojo.get("result_select")) {
     for (LinkedHashMap<String, String> addr : addrs) {
       LinkedHashMap<String, String> formatted_pojo_hash = new LinkedHashMap<String, String>();
       formatted_pojo_hash.put("id", (id++).toString());
       formatted_pojo_hash.put("addr", addr.get("text"));
       formatted_pojo_hash.put("lng", addr.get("lng"));
       formatted_pojo_hash.put("lat", addr.get("lat"));
       formatted_pojo_array.add(formatted_pojo_hash);
     }
   }
   return JSON.encode(formatted_pojo_array);
 }
コード例 #10
0
ファイル: QiitaExecutor.java プロジェクト: jabaraster/qiita4j
 public <T extends QiitaResponse> PageableResponse<T> getPageableContents(
     URI uri, Class<T> responseType) throws IOException, QiitaException {
   HttpGet request = new HttpGet(uri);
   HttpResponse response = execute(request);
   verifyStatusCode(response, SC_OK);
   String[] linkHeaderValues = getHeaderValues(response.getHeaders("Link"));
   try (InputStream in = response.getEntity().getContent()) {
     @SuppressWarnings("unchecked")
     T[] contents = JSON.decode(in, (Class<T[]>) Array.newInstance(responseType, 0).getClass());
     return new PageableResponse<>(this, responseType, contents, linkHeaderValues);
   }
 }
コード例 #11
0
ファイル: QiitaExecutor.java プロジェクト: jabaraster/qiita4j
 private static void verifyStatusCode(HttpResponse response, int expectedStatusCode)
     throws IOException, QiitaException {
   int statusCode = response.getStatusLine().getStatusCode();
   if (statusCode == SC_BAD_REQUEST || statusCode == SC_FORBIDDEN || statusCode == SC_NOT_FOUND) {
     try (InputStream in = response.getEntity().getContent()) {
       Error res = JSON.decode(in, Error.class);
       throw new QiitaException(res.getError());
     }
   }
   if (statusCode != expectedStatusCode) {
     throw new IllegalArgumentException("unexpected status code:" + statusCode);
   }
 }
コード例 #12
0
ファイル: RedmineApiTest.java プロジェクト: akikinyan/testapp
 /**
  * チケットの取得
  *
  * @return チケットの総数を返す
  */
 public static int getAllTickets() {
   // チケットの取得
   RedmineManager mgr = RedmineManagerFactory.createWithApiKey(redmineHost, apiAccessKey);
   int cnt = 0;
   try {
     List<Issue> issues = mgr.getIssueManager().getIssues(projectKey, queryId);
     for (Issue issue : issues) {
       cnt += 1;
       System.out.println(JSON.encode(issue, true));
     }
   } catch (Exception e) {
     System.out.println(e.getStackTrace());
   }
   return cnt;
 }
コード例 #13
0
  protected void fetchHandlebars(String handlebarsName) throws MojoExecutionException {
    String downloadUrl = null;
    URLConnection conn = null;
    try {
      conn = handlebarsDownloadsUri.toURL().openConnection();
      List<GitHubDownloadDto> githubDownloadDtoList =
          JSON.decode(
              conn.getInputStream(),
              (new ArrayList<GitHubDownloadDto>() {}).getClass().getGenericSuperclass());
      for (GitHubDownloadDto githubDownloadDto : githubDownloadDtoList) {
        if (StringUtils.equals(githubDownloadDto.getName(), handlebarsName)) {
          downloadUrl = githubDownloadDto.getHtmlUrl();
        }
      }
    } catch (Exception e) {
      throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
      if (conn != null) {
        ((HttpURLConnection) conn).disconnect();
      }
    }

    conn = null;
    try {
      if (!cacheDir.exists()) {
        FileUtils.forceMkdir(cacheDir);
      }
      conn = new URL(downloadUrl).openConnection();
      if (((HttpURLConnection) conn).getResponseCode() == 302) {
        String location = conn.getHeaderField("Location");
        ((HttpURLConnection) conn).disconnect();
        conn = new URL(location).openConnection();
      }
      LOG.info("Fetch handlebars.js from GitHub (" + conn.getURL() + ")");
      IOUtils.copy(conn.getInputStream(), new FileOutputStream(new File(cacheDir, handlebarsName)));
    } catch (Exception e) {
      throw new MojoExecutionException("Failure fetch handlebars.", e);
    } finally {
      if (conn != null) {
        ((HttpURLConnection) conn).disconnect();
      }
    }
  }
コード例 #14
0
  @Override
  protected void get() throws Exception {
    List<SpellCard> spellCards = SpellCardService.findAllNew(100);

    List<SpellCardInfo> spellCardInfo = new ArrayList<SpellCardInfo>();
    for (SpellCard spellCard : spellCards) {
      SpellCardInfo info = SpellCardInfo.createFrom(spellCard);

      // dummy info
      info.setPageViewPoint(Double.valueOf(Math.floor(Math.random() * 1000)).intValue());
      info.setFavoritePoint(Double.valueOf(Math.floor(Math.random() * 1000)).intValue());

      spellCardInfo.add(info);
    }

    String json = JSON.encode(spellCardInfo);
    Date lastModified = spellCards.isEmpty() ? new Date() : spellCards.get(0).getCreatedAt();
    returnAsJson(json, lastModified);
  }
コード例 #15
0
  /**
   * 閾値判定の定義を編集する。
   *
   * @param mulResGraphDefinition 閾値判定の定義のJSONデータ
   * @return 編集後の閾値判定の定義
   */
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @ResponseBody
  public ResponseDto edit(
      @RequestParam(value = "mulResGraphDefinition") final String mulResGraphDefinition) {
    ResponseDto responseDto = new ResponseDto();
    MultipleResourceGraphDefinitionDto multipleResourceGraphDefinitionDto =
        JSON.decode(mulResGraphDefinition, MultipleResourceGraphDefinitionDto.class);

    MultipleResourceGraphInfo multipleResourceGraphInfo =
        this.multipleResourceGraphService_.convertMultipleResourceGraphInfo(
            multipleResourceGraphDefinitionDto);

    // DBに登録されている定義を更新する
    MultipleResourceGraphDefinitionDto updatedDefinitionDto =
        this.multipleResourceGraphService_.updatemultipleResourceGraphInfo(
            multipleResourceGraphInfo);
    responseDto.setResult(ResponseConstants.RESULT_SUCCESS);
    responseDto.setData(updatedDefinitionDto);

    return responseDto;
  }
コード例 #16
0
  public FeedsResponse retrieveFeeds(URI uri) {
    FeedsResponse response = null;
    CloseableHttpClient httpClient = null;

    try {
      httpClient = HttpClients.createDefault();
      HttpGet httpget = new HttpGet(uri);
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String json = httpClient.execute(httpget, responseHandler);
      response = JSON.decode(json, FeedsResponse.class);
    } catch (Throwable e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (httpClient != null) httpClient.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }

    return response;
  }
コード例 #17
0
  /**
   * 顧客コードから納入先リストを返します.<br>
   * 顧客コードが完全に一致しない場合は値が返りません.<br>
   * 返す値は、納入先コードと納入先名のリスト、かつ、作成日の昇順で、請求先は除外しています.<br>
   * mapの内容は key = "value" + No name = 納入先コード、納入先名の順番です.
   *
   * @return 納入先リスト情報
   * @throws Exception
   */
  @Execute(validator = false)
  public String getDeliveryListByCustomerCodeSortedByCreDate() throws Exception {

    // 顧客コードを指定しない場合は検索しません
    if (!StringUtil.hasLength(commonDeliveryForm.customerCode)) {
      ResponseUtil.write("", "text/javascript");
      return null;
    }

    List<DeliveryAndPre> deliveryList;
    try {
      deliveryList =
          deliveryService.searchDeliveryByCompleteCustomerCodeSortedByCreDate(
              commonDeliveryForm.customerCode);

      // 納入先コードと納入先名を返す
      int i = 0;
      String key;
      Map<String, Object> param = new HashMap<String, Object>();
      for (DeliveryAndPre dap : deliveryList) {
        key = "value" + Integer.toString(i);
        param.put(key, dap.deliveryCode);
        key = "name" + Integer.toString(i);
        param.put(key, dap.deliveryName);
        i++;
      }
      if (deliveryList.size() != 0) {
        BeanMap map = super.createBeanMapWithNullToEmpty(param);
        ResponseUtil.write(JSON.encode(map), "text/javascript");
      } else {
        ResponseUtil.write("", "text/javascript");
      }
    } catch (ServiceException e) {
      super.errorLog(e);
      throw e;
    }

    return null;
  }
コード例 #18
0
  /**
   * 全通貨記号を取得します.
   *
   * @return 全通貨記号
   * @throws Exception
   */
  @Execute(validator = false)
  public String getAllRateSign() throws Exception {
    try {
      List<Rate> rateList = rateService.findAllRate();
      Map<String, Object> rateMap = new HashMap<String, Object>();
      for (Rate rate : rateList) {

        rateMap.put(Integer.toString(rate.rateId), rate.sign);
      }

      if (rateList.size() != 0) {
        BeanMap map = super.createBeanMapWithNullToEmpty(rateMap);
        ResponseUtil.write(JSON.encode(map), "text/javascript");
      } else {
        ResponseUtil.write("", "text/javascript");
      }
    } catch (ServiceException e) {
      super.errorLog(e);
      throw e;
    }
    return null;
  }
コード例 #19
0
  /**
   * Load profiles from specified directory. This method must be called once before language
   * detection.
   *
   * @param profileDirectory profile directory path
   * @throws LangDetectException Can't open profiles(error code = {@link ErrorCode#FileLoadError})
   *     or profile's format is wrong (error code = {@link ErrorCode#FormatError})
   * @throws IOException
   */
  public static void loadProfiles(String... langs) throws LangDetectException {

    for (int i = 0; i < langs.length; i++) {

      InputStream is =
          LangProfile.class.getClassLoader().getResourceAsStream("profiles/" + langs[i]);

      try {
        LangProfile profile = JSON.decode(is, LangProfile.class);
        addProfile(profile, langs.length);
      } catch (JSONException e) {
        throw new LangDetectException(
            ErrorCode.FormatError, "profile format error in for: " + langs[i]);
      } catch (IOException e) {
        throw new LangDetectException(
            ErrorCode.FormatError, "profile format error in for: " + langs[i]);
      } finally {
        try {
          if (is != null) is.close();
        } catch (IOException e) {
        }
      }
    }
  }
コード例 #20
0
  /**
   * 商品コードから商品情報を取得します.
   *
   * @return 商品情報
   * @throws Exception
   */
  @Execute(validator = false)
  public String getProductInfos() throws Exception {
    ProductJoin product;
    int movableQuantity;
    try {

      product = productService.findById(commonProductForm.productCode);
      this.stockInfoDto =
          this.productStockService.calcStockQuantityByProductCode(commonProductForm.productCode);

      if (product != null && !StringUtil.hasLength(commonProductForm.rackCode)) {
        commonProductForm.rackCode = product.rackCode;
      }

      int unclosedQuantity =
          eadService.countUnclosedQuantityByProductCode(
              commonProductForm.productCode, commonProductForm.rackCode);
      int closedQuantity =
          productStockService.countClosedQuantityByProductCode(
              commonProductForm.productCode, commonProductForm.rackCode);
      movableQuantity = unclosedQuantity + closedQuantity;
    } catch (ServiceException e) {
      super.errorLog(e);
      throw e;
    }
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

    if (product != null) {
      map.put(Param.SUPPLIER_CODE, (product.supplierCode == null ? "" : product.supplierCode));
      map.put(Param.PRODUCT_NAME, (product.productName == null ? "" : product.productName));
      map.put(Param.SUPPLIER_PCODE, (product.supplierPcode == null ? "" : product.supplierPcode));
      map.put(Param.PO_LOT, (product.poLot == null ? "" : product.poLot.toString()));
      map.put(Param.MAX_PO_NUM, (product.maxPoNum == null ? "" : product.maxPoNum.toString()));
      map.put(
          Param.MAX_STOCK_NUM, (product.maxStockNum == null ? "" : product.maxStockNum.toString()));
      map.put(
          Param.DISCARD_DATE,
          (product.discardDate == null ? "" : DF_YMD.format(product.discardDate)));
      map.put(
          Param.SUPPLIER_PRICE_YEN,
          (product.supplierPriceYen == null ? "" : product.supplierPriceYen.toString()));
      map.put(
          Param.SUPPLIER_PRICE_DOL,
          (product.supplierPriceDol == null ? "" : product.supplierPriceDol.toString()));
      map.put(Param.RACK_CODE, (product.rackCode == null ? "" : product.rackCode));

      map.put(
          Param.RETAIL_PRICE, (product.retailPrice == null ? "" : product.retailPrice.toString()));

      map.put(Param.RO_MAX_NUM, (product.roMaxNum == null ? "" : product.roMaxNum.toString()));

      map.put(
          Param.SET_TYPE_CATEGORY,
          (product.setTypeCategory == null ? "" : product.setTypeCategory));

      map.put(Param.DISCARDED, (product.discarded == null ? "" : product.discarded));

      map.put(Param.TAX_CATEGORY, (product.taxCategory == null ? "" : product.taxCategory));

      map.put(Param.REMARKS, (product.remarks == null ? "" : product.remarks));

      map.put(Param.EAD_REMARKS, (product.eadRemarks == null ? "" : product.eadRemarks));

      map.put(Param.UNIT_CATEGORY, (product.unitCategory == null ? "" : product.unitCategory));

      map.put(
          Param.UNIT_CATEGORY_NAME,
          (product.unitCategoryName == null ? "" : product.unitCategoryName));

      map.put(Param.ONLINE_PCODE, (product.onlinePcode == null ? "" : product.onlinePcode));

      map.put(
          Param.PACK_QUANTITY,
          (product.packQuantity == null ? "" : product.packQuantity.toString()));

      map.put(Param.LENGTH, (product.length == null ? "" : product.length.toString()));

      map.put(Param.SO_RATE, (product.soRate == null ? "" : product.soRate.toString()));

      map.put(
          Param.STOCK_CTL_CATEGORY,
          (product.stockCtlCategory == null ? "" : product.stockCtlCategory));
    } else {
      ResponseUtil.write("", "text/javascript");
      return null;
    }

    map.put(
        ShowStockInfoDialogAction.Param.PRODUCT_CODE,
        (stockInfoDto.productCode == null ? "" : stockInfoDto.productCode));
    map.put(
        ShowStockInfoDialogAction.Param.CURRENT_TOTAL_QUANTITY,
        (String.valueOf(stockInfoDto.currentTotalQuantity)));
    map.put(
        ShowStockInfoDialogAction.Param.RORDER_REST_QUANTITY,
        (String.valueOf(stockInfoDto.rorderRestQuantity)));
    map.put(
        ShowStockInfoDialogAction.Param.PORDER_REST_QUANTITY,
        (String.valueOf(stockInfoDto.porderRestQuantity)));
    map.put(
        ShowStockInfoDialogAction.Param.ENTRUST_REST_QUANTITY,
        (String.valueOf(stockInfoDto.entrustRestQuantity)));
    map.put(
        ShowStockInfoDialogAction.Param.POSSIBLE_DROW_QUANTITY,
        (String.valueOf(stockInfoDto.possibleDrawQuantity)));
    map.put(
        ShowStockInfoDialogAction.Param.HOLDING_STOCK_QUANTITY,
        (String.valueOf(stockInfoDto.holdingStockQuantity)));

    if (StringUtil.hasLength(commonProductForm.rackCode)) {
      map.put(Param.MOVABLE_QUANTITY, String.valueOf(movableQuantity));
    } else {
      map.put(Param.MOVABLE_QUANTITY, "");
    }

    ResponseUtil.write(JSON.encode(map), "text/javascript");

    return null;
  }
コード例 #21
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // 文字化けのおまじない
    response.setContentType("application/json; charset=UTF-8");

    String battleClickJson = (String) request.getParameter("battleClickBean");
    System.out.println(battleClickJson);

    // デバッグ用にプレイヤとゲームを勝手に入力
    // request.getSession().setAttribute("playerID", 1);
    // request.getSession().setAttribute("gameID", 1);
    // ここまで

    BattleClickBean battleClickBean = JSON.decode(battleClickJson, BattleClickBean.class);
    System.out.println(battleClickBean.getTurnTotalTime());

    // セッションからゲームIDを取得
    GAMEID gameID = new GAMEID((int) request.getSession().getAttribute("GAMEID"));
    // セッションからクリックしたプレイヤーを取得
    ClickPlayerID clickPlayerID =
        new ClickPlayerID((int) request.getSession().getAttribute("PLAYERID"));
    // マス情報を取得
    MASSID massID = new MASSID(battleClickBean.getClickObjectNumber());
    System.out.println(massID);
    // クリックしたものが何かを判別(マス or アイテム or スキル)
    ClickObjectTypeEnum objectType = battleClickBean.getClickObjectType();
    // GAMEID gameID = new GAMEID(battleClickBean.getGameObjectNumber())
    // ---------------------------------------------------------------------------
    Connection con = null;
    try {
      // objectTypeに応じたクリック時処理へ、@return = ClickResultBean
      con = Dao.getConnection();

      ClickResultBean clickResultBean =
          objectType.clickAction(
              massID, gameID, battleClickBean.getTurnTotalTime(), clickPlayerID, con);

      MASSLIST massList = clickResultBean.getMASSLIST();
      List<Mass> list = massList.get();

      MassStateBean massStateBean = new MassStateBean();

      for (Mass ms : list) {
        int massId = ms.getMASSID().get();
        // String url = MassTypeEnum.MASSTYPE0.url;
        String url = ms.getMassState().url;
        MassUpdateBean massUpdateBean = new MassUpdateBean(massId, url);

        // デバック用--------------------------------------------------
        System.out.println(massUpdateBean.getMassNumber());
        System.out.println(massUpdateBean.getUrl());

        massStateBean.addMassUpdateBean(massUpdateBean);
      }

      //			Boolean isFinish = clickResultBean.getISFINISH().get();
      //			if (isFinish) {
      //				String massClickBean = JSON.encode(massStateBean);
      //
      //				System.out.println(massClickBean);
      //				PrintWriter out = response.getWriter();
      //				out.println(massClickBean);
      //
      //			} else {
      massStateBean.setIsFinished(clickResultBean.getISFINISH().get());

      PLAYERID playerID = new PLAYERID((int) request.getSession().getAttribute("PLAYERID"));
      ChangeTurnPlayerService ctps = new ChangeTurnPlayerService(con);
      massStateBean.setIsMyTurn(
          ctps.checkTurnPlayer(
                  new GAMEID((int) request.getSession().getAttribute("GAMEID")), playerID)
              .getIsMyTurn());

      // クイズをbeanに追加
      if (clickResultBean.getQuiz() != null) {
        QuizBean qbean = new QuizBean();
        qbean.setDescription(clickResultBean.getQuiz().getDESCRIPTION().get());
        qbean.setAnswer(clickResultBean.getQuiz().getANSWER());

        massStateBean.setQuizBean(qbean);
      }

      // アイテムをbeanに追加
      if (clickResultBean.getItem() != null) {
        ItemBean ibean = new ItemBean();
        ibean.setItemEnum(clickResultBean.getItem().getITEMENUM());

        ibean.setItemName(clickResultBean.getItem().getITEMNAME().get());
        massStateBean.setItemBean(ibean);
      }

      // プレイヤのアイテム、スキル情報をbeanに追加
      if (clickResultBean.getMyPlayer() != null) {
        Player myPlayer = clickResultBean.getMyPlayer();

        PlayerBean pbean = new PlayerBean();
        pbean.setCoolTime(myPlayer.getCOOLTIME().get());
        // set itemURL

        if (myPlayer.getITEMID().get() != 0)
          pbean.setItemURL(ItemEnum.getItemEnum(myPlayer.getITEMID().get()).getItemURL());

        massStateBean.setMyPlayerBean(pbean);
      }
      if (clickResultBean.getEnemyPlayer() != null) {
        Player enemyPlayer = clickResultBean.getEnemyPlayer();
        PlayerBean pbean = new PlayerBean();
        pbean.setCoolTime(enemyPlayer.getCOOLTIME().get());
        // set itemURL

        if (enemyPlayer.getITEMID().get() != 0)
          pbean.setItemURL(ItemEnum.getItemEnum(enemyPlayer.getITEMID().get()).getItemURL());

        massStateBean.setEnemyPlayerBean(pbean);
      }

      String massClickBean = JSON.encode(massStateBean);

      System.out.println(massClickBean);
      PrintWriter out = response.getWriter();
      out.println(massClickBean);

      return;
      //			}

      // int winPlayerId =
      // clickResultBean.getWinPlayerID().get();//勝ったプレイヤーID
      // int losePlayerId =
      // clickResultBean.getLosePlayerID().get();//負けたプレイヤーID
      //
      // Player player = new Player();
      // int playerId = player.getPLAYERID().get();//
      //
      // if (playerId == winPlayerId) {
      // // 勝側のサーブレットに勝ったプレイヤーIDを渡す
      // request.getSession().setAttribute("winPlayerID", winPlayerId);
      // RequestDispatcher disp =
      // request.getRequestDispatcher("/WinPlayerServlet");
      // disp.forward(request, response);
      // } else if (playerId == losePlayerId) {
      // // 負側のサーブレットに負けたプレイヤーIDを渡す
      // request.getSession().setAttribute("losePlayerID", losePlayerId);
      // RequestDispatcher disp =
      // request.getRequestDispatcher("/LosePlayerServlet");
      // disp.forward(request, response);
      // }

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      try {
        if (con != null && con.isClosed()) {
          throw new RuntimeException("すでにコネクションが閉じています。ロールバックができません。");
        }
        if (con != null) con.rollback();
      } catch (SQLException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
      }
      throw new RuntimeException(e);
    } catch (SQLException e) {
      e.printStackTrace();
      try {
        if (con != null && con.isClosed()) {
          throw new RuntimeException("すでにコネクションが閉じています。ロールバックができません。");
        }
        if (con != null) con.rollback();
      } catch (SQLException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
      }
      throw new RuntimeException(e);
    } catch (Throwable e) {
      e.printStackTrace();
      throw e;
    } finally {
      try {
        con.close();
      } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
      }
    }
  }
コード例 #22
0
ファイル: JSONWrapper.java プロジェクト: hoge1e3/soyText
 public void setPrettyPrint(boolean p) {
   json.setPrettyPrint(p);
 }
コード例 #23
0
ファイル: JSONWrapper.java プロジェクト: hoge1e3/soyText
 /*private Scriptable newObject() {
 	return (Scriptable)objFactory.construct(org.mozilla.javascript.Context.getCurrentContext(), null, new Object[0]);
 }
 private Scriptable newArray() {
 	return (Scriptable)aryFactory.construct(org.mozilla.javascript.Context.getCurrentContext(), null, new Object[0]);
 }*/
 public String format(Object s) {
   return json.format(s);
 }
コード例 #24
0
ファイル: At2Dot.java プロジェクト: hoge1e3/soyText
  public static void main(String[] args) throws Exception {
    SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    // String fm=/*"Sun "+*/"Apr 15 16:11:21 JST 2012";
    // fmt="MMM dd HH:mm:ss z yyyy";
    // System.out.println(df.format( new Date()));

    Common.parseArgs(args);
    SFile sFile = getNewestBackupFile(Common.workspace.getBackupDir(Common.dbid));

    // SFile sFile = new SFile(args[0]);
    System.out.println("sFile=" + sFile);
    // String src=sFile.text();
    SFile newFile = sFile.parent().rel("dot_" + sFile.name());
    Map m = (Map) JSON.decode(sFile.inputStream());
    List docs = (List) m.get("DocumentRecord");
    Map<String, String> ids = new HashMap<String, String>();
    Map<Long, Date> lu2Date = new HashMap<Long, Date>();
    List logs = (List) m.get("LogRecord");
    if (logs != null) {
      for (Object l : logs) {
        Map log = (Map) l;
        long id = Long.parseLong(log.get("id") + "");
        Date d = df.parse(log.get("date") + "");
        // d.to
        lu2Date.put(id, d);
        // System.out.println(id+"-"+d);
      }
    }
    // System.exit(1);
    int ser = 0;
    for (Object s : docs) {
      Map doc = (Map) s;
      String id = doc.get("id") + "";
      String newId = id.replace("@", ".");
      ids.put(id, newId);
      if (Common.dbid.equals(SDB.dbIdPart(newId))) {
        int se = SDB.serialPart(newId);
        if (se > ser) ser = se;
      }
      // System.out.println(newId);
      doc.put("id", newId);

      String scope = doc.get("scope") + "";
      if (scope.compareTo("null") != 0) {
        doc.put("scope", scope.replaceAll("@", "."));
      }
      String con = doc.get("constructor") + "";
      if (con.compareTo("null") != 0) {
        doc.put("constructor", con.replaceAll("@", "."));
      }

      convertDate(lu2Date, doc, "lastUpdate");
      convertDate(lu2Date, doc, "lastAccessed");
      String content = doc.get("content") + "";
      //                   byId\("[^"]+@[^"]+"\)
      //                  (byId\("[^"]+)@([^"]+"\))
      //                  (byId\\(\"[^\"]+)@([^\"]+\"\\))
      content = content.replaceAll(idPat, "$1.$2");
      doc.put("content", content);

      doc.put("version", MD5.crypt(content));

      String sum = doc.get("summary") + "";
      int i = 0;
      Matcher ma = around.matcher(content);
      while (true) {
        if (ma.find(i)) {
          String group = ma.group();
          if (group.matches(".*@[a-z\\.]+\\.(com|jp).*")
              || group.contains("アドレス")
              || group.contains("ac.jp/soytext2/exec/")) {

          } else {
            System.out.println(id + ":" + sum + ": " + group);
          }
          i = ma.end();
        } else break;
      }
    }
    for (Object s : docs) {
      Map doc = (Map) s;
      String sum = doc.get("summary") + "";
      if (ids.get(sum) != null) {
        doc.put("summary", ids.get(sum));
      }
    }
    m.remove("IndexRecord");
    m.remove("LogRecord");
    m.put("IdSerialRecord", new Object[] {Maps.create("serial", ser).p("id", 0)});
    /*int idc=ids.size();
    int c=0;
    for (String oldId:ids.keySet()) {
    	String newId=ids.get(oldId);
    	oldId=oldId.replaceAll("\\.", "\\\\$0");
    	newId=newId.replaceAll("\\.", "\\\\$0");
    	System.out.println("["+c+"/"+idc+"]"+"s/"+oldId+"/"+newId+"/g");
    	src=src.replaceAll(oldId, newId);
    }*/
    JSON j = new JSON();
    j.setPrettyPrint(true);
    j.format(m, newFile.outputStream());
    // newFile.text(j.format(m));
    /*for (String s:newFile.lines()) {
    	if (s.indexOf('@')>=0) {
    		System.out.println(s);
    	}
    }*/
  }
コード例 #25
0
ファイル: ResponseRejoin.java プロジェクト: ukiuni/irc4j
 @Override
 public void onResponseSecure(OutputStream out) throws Throwable {
   WebWorkerClientConnection clientConnection = getAccessConnection();
   if (null != clientConnection) {
     write(out, 200, "{\"status\":\"aleady join\"}", "application/json; charset=utf-8", "UTF-8");
     return;
   }
   String channelNames = getRequest().getParameter("channelNames");
   if (null == channelNames || null == getNickName()) {
     write(
         out,
         400,
         "{\"status\":\"wrong channelName\"}",
         "application/json; charset=utf-8",
         "UTF-8");
     return;
   }
   User user = Database.getInstance().loadUser(getNickName());
   if (null == user) {
     clientConnection = new WebWorkerClientConnection(ircServer);
     clientConnection.setNickName(getNickName());
     clientConnection.getUser().setHostName("webIF");
     clientConnection.getUser().setName(getNickName());
     clientConnection.getUser().setRealName(getNickName());
   } else {
     if (user.getId() != getUserId()) {
       write(
           out, 403, "{\"status\":\"wrong UserId\"}", "application/json; charset=utf-8", "UTF-8");
       return;
     }
     clientConnection = new WebWorkerClientConnection(ircServer);
     clientConnection.setNickName(getNickName());
     clientConnection.getUser().setHostName("webIF");
     clientConnection.getUser().setRealName(user.getRealName());
     clientConnection.getUser().setCreatedAt(user.getCreatedAt());
     clientConnection.getUser().setDescription(user.getDescription());
     clientConnection.getUser().setEmail(user.getEmail());
     clientConnection.getUser().setIconImage(user.getIconImage());
     clientConnection.getUser().setName(user.getName());
     clientConnection.getUser().setId(user.getId());
     clientConnection.getUser().setNickName(user.getNickName());
     clientConnection.getUser().setPasswordHashed(user.getPasswordHashed());
     clientConnection.getUser().setNotify(user.isNotify());
     clientConnection.getUser().setNotificationKeyword(user.getNotificationKeyword());
     clientConnection.getUser().setRealName(user.getRealName());
     clientConnection.getUser().setUpdatedAt(user.getUpdatedAt());
   }
   ircServer.putConnection(clientConnection);
   String[] channelNameArray = channelNames.split(",");
   for (String channelName : channelNameArray) {
     if (channelName.startsWith("#")) {
       if (Channel.wrongName(channelName)) {
         write(
             out,
             400,
             "{\"status\":\"wrong channelName\"}",
             "application/json; charset=utf-8",
             "UTF-8");
         return;
       }
       // TODO password
       ircServer.joinToChannel(clientConnection, channelName);
     }
   }
   Map<String, Object> returnMap = new HashMap<String, Object>();
   try {
     long maxMessageId = Long.parseLong(getRequest().getParameter("maxMessageId"));
     Map<String, List<Message>> messageMap = new HashMap<String, List<Message>>();
     for (String channelName : channelNameArray) {
       messageMap.put(
           channelName,
           Database.getInstance()
               .loadMessageNewerThan(channelName, maxMessageId, Integer.MAX_VALUE));
     }
     returnMap.put("messages", messageMap);
   } catch (Exception e) {
   }
   returnMap.put("status", "rejoined");
   write(out, 200, JSON.encode(returnMap), "application/json; charset=utf-8", "UTF-8");
 }
コード例 #26
0
ファイル: JSONWrapper.java プロジェクト: hoge1e3/soyText
 public Object parse(String source) {
   Object r = json.parse(source);
   return postparse(r, DocumentLoader.curJsSesssion());
 }