public synchronized void transferProgress(
      TransferEvent transferEvent, byte[] buffer, int length) {
    Resource resource = transferEvent.getResource();
    if (!downloads.containsKey(resource)) {
      downloads.put(resource, new Long(length));
    } else {
      Long complete = (Long) downloads.get(resource);
      complete = new Long(complete.longValue() + length);
      downloads.put(resource, complete);
    }

    StringBuffer buf = new StringBuffer();
    for (Iterator i = downloads.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry entry = (Map.Entry) i.next();
      Long complete = (Long) entry.getValue();
      String status =
          getDownloadStatusForResource(
              complete.longValue(), ((Resource) entry.getKey()).getContentLength());
      buf.append(status);
      if (i.hasNext()) {
        buf.append(" ");
      }
    }

    if (buf.length() > maxLength) {
      maxLength = buf.length();
    }

    out.print(buf.toString() + "\r");
  }
  @Override
  public Map<MaterialCategory, StatValue<Integer, Double>> calculate() {
    List<Material> materialList = manager.getMaterials();
    Map<MaterialCategory, Integer> map = new HashMap<MaterialCategory, Integer>();
    for (MaterialCategory cat : MaterialCategory.values()) {
      map.put(cat, 0);
    }

    for (Material m : materialList) {
      MaterialCategory category = m.getMaterialType().getCategory();
      int number = map.get(category);
      number++;
      map.put(category, number);
    }

    int sizeStock = materialList.size();
    MaterialCategory[] listCategory = MaterialCategory.values();
    Map<MaterialCategory, StatValue<Integer, Double>> numberAndPourcent =
        new HashMap<MaterialCategory, StatValue<Integer, Double>>();
    for (MaterialCategory mc : listCategory) {
      int numberCat = map.get(mc);
      double pourcent = (numberCat * 1.0) / sizeStock;
      numberAndPourcent.put(mc, new StatValue<Integer, Double>(numberCat, pourcent));
    }
    return numberAndPourcent;
  }
Exemple #3
2
  private void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter out = response.getWriter();
    String sPage = request.getParameter("page");
    String sRows = request.getParameter("rows");
    String order = request.getParameter("order");
    String sort = request.getParameter("sort");
    int page = 0;
    int rows = 0;
    if (sPage != null && sRows != null) {
      page = Integer.parseInt(sPage);
      rows = Integer.parseInt(sRows);
    }

    int total = service.count();
    List list = service.get(page, rows, order, sort);
    Map m = new HashMap();
    m.put("total", total);
    m.put("rows", list);

    JSONArray jsonArray = new JSONArray().fromObject(m);
    String json = jsonArray.toString();
    String j = json.substring(1, json.lastIndexOf("]"));

    out.write(j);
  }
Exemple #4
1
  public DialogPanel(boolean canok, boolean cancancel) {
    super(new GridBagLayout());
    actions = new LinkedHashMap<String, Action>();
    keystrokes = new HashMap<KeyStroke, String>();

    if (canok) {
      addButton(
          "ok",
          UIManager.getString("OptionPane.okButtonText"),
          KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              acceptDialog();
            }
          });
      keystrokes.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_MASK), "ok");
    }

    if (cancancel) {
      addButton(
          "cancel",
          UIManager.getString("OptionPane.cancelButtonText"),
          KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              cancelDialog();
            }
          });
      keystrokes.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, InputEvent.CTRL_MASK), "cancel");
    }
  }
  static {
    // general configuration
    TIDY_FEED_CONFIG = new Properties();
    TIDY_FEED_CONFIG.setProperty("force-output", "yes");
    TIDY_FEED_CONFIG.setProperty("indent-attributes", "no");
    TIDY_FEED_CONFIG.setProperty("indent", "no");
    TIDY_FEED_CONFIG.setProperty("quiet", "yes");
    TIDY_FEED_CONFIG.setProperty("trim-empty-elements", "yes");

    // XML specific configuration
    TIDY_XML_CONFIG = new Properties(TIDY_FEED_CONFIG);
    TIDY_XML_CONFIG.setProperty("input-xml", "yes");
    TIDY_XML_CONFIG.setProperty("output-xml", "yes");
    TIDY_XML_CONFIG.setProperty("add-xml-pi", "no");
    TIDY_XML_CONFIG.setProperty("input-encoding", "UTF8");

    // HTML specific configuration
    TIDY_HTML_CONFIG = new Properties(TIDY_FEED_CONFIG);
    TIDY_HTML_CONFIG.setProperty("output-xhtml", "yes");
    TIDY_HTML_CONFIG.setProperty("show-body-only", "yes");
    TIDY_HTML_CONFIG.setProperty("drop-empty-paras", "yes");
    TIDY_HTML_CONFIG.setProperty("enclose-text", "yes");
    TIDY_HTML_CONFIG.setProperty("logical-emphasis", "yes");
    TIDY_HTML_CONFIG.setProperty("input-encoding", "UTF8");

    // default parameters for all instances of this class
    DEFAULT_PARAMS = new HashMap<String, Object>();
    DEFAULT_PARAMS.put(CONTENT_TYPE, "text/html");
    DEFAULT_PARAMS.put(CONTENT_LENGTH, -1); // no limit by default
  }
  /**
   * @功能描述:删除工单
   *
   * @author gel @2015年8月31日
   * @param
   * @version
   * @throws Exception
   */
  @RequestMapping(value = "deleteDataWn", method = RequestMethod.POST)
  @ResponseBody
  public void deleteDataWn(@RequestBody WnVo vo, HttpServletResponse response) throws Exception {
    // 判断vo
    if (vo == null) {
      throw new MbvException("传入参数为空!");
    }
    Map<String, Object> map = new HashMap<String, Object>();

    try {
      List<Integer> deleteIds = vo.getDeleteIds();
      // 根据id 查询数据字典
      List<WnEntity> dataWns = new ArrayList<WnEntity>();
      for (int id : deleteIds) {
        WnEntity d = new WnEntity();
        d.setId((long) id);
        dataWns.add(wnService.selectByPrimaryKey((long) id));
      }
      boolean deleteResult = wnService.deleteDataDirectory(dataWns);

      map.put("result", deleteResult);
      map.put("success", true);
    } catch (MbvException e) {
      throw new MbvException(MbvConstant.MBV_SYS_ERROR_TIP);
    } catch (RuntimeException e) {
      throw new MbvException(MbvConstant.MBV_SYS_ERROR_TIP);
    }

    // 保存成功
    returnSuccess(response, map);
  }
Exemple #7
0
  @Override
  public String execute() throws Exception {

    ActionContext ctx = ActionContext.getContext();

    ServletContext sc = (ServletContext) ctx.get(ServletActionContext.SERVLET_CONTEXT);

    ApplicationContext appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    CourseManagerImpl cmi = (CourseManagerImpl) appContext.getBean("CourseManagerImpl");
    StudentManagerImpl smi = (StudentManagerImpl) appContext.getBean("StuManagerImpl");

    List cmiList = cmi.getCourses();
    List smiList = smi.getStudents();

    Map cmiMap = new HashMap();
    Map smiMap = new HashMap();

    for (int i = 0; i < cmiList.size(); i++) {
      Course course = (Course) cmiList.get(i);
      cmiMap.put(course.getCoursId(), course.getCoursName());
    }

    for (int i = 0; i < smiList.size(); i++) {
      Student student = (Student) smiList.get(i);
      smiMap.put(student.getStuId(), student.getStuName());
    }

    ActionContext actionContext = ActionContext.getContext();
    Map session = actionContext.getSession();
    session.put("cmiMap", cmiMap);
    session.put("smiMap", smiMap);
    return SUCCESS;
  }
  public static void inAppDial(final BaseActivity activity, String dial) {
    if (TextUtils.isEmpty(dial)) {
      return;
    }
    final String phone = StringUtils.phoneFormat(dial);
    if (Constant.noCall.contains(phone)) {
      call(activity, phone);
    } else {
      HttpServer hServer = new HttpServer(Constant.URL.phoneCall, activity.getHandlerContext());
      Map<String, String> headers = new HashMap<String, String>();
      headers.put("sign", User.ACCESSKEY);
      hServer.setHeaders(headers);
      Map<String, String> params = new HashMap<String, String>();
      params.put("accessid", User.ACCESSID);
      params.put("userTel", activity.getAppContext().currentUser().getPhone());
      params.put("oppno", phone);
      hServer.setParams(params);
      hServer.get(
          new HttpRunnable() {

            @Override
            public void run(Response response) throws AppException {
              Map<String, String> info = response.getMapData("serverinfo");
              RecordingContentView.isRefreshData = true;
              BaseContext.getSharedPreferences()
                  .putString(Constant.Preferences.SP_CALL_DIAL, phone);
              call(activity, info.get("serverno"));
              activity.getRecentDaoImpl().insertCallLog(phone);
            }
          });
    }
  }
  @Test
  public void demoMethodNameMappingExpressionSource() {
    Map<String, String> expressionMap = new HashMap<String, String>();
    expressionMap.put("test", "#return");
    MethodNameMappingPublisherMetadataSource metadataSource =
        new MethodNameMappingPublisherMetadataSource(expressionMap);
    Map<String, String> channelMap = new HashMap<String, String>();
    channelMap.put("test", "c");
    metadataSource.setChannelMap(channelMap);

    Map<String, Map<String, String>> headerExpressionMap =
        new HashMap<String, Map<String, String>>();
    Map<String, String> headerExpressions = new HashMap<String, String>();
    headerExpressions.put("bar", "#return");
    headerExpressions.put("name", "'oleg'");
    headerExpressionMap.put("test", headerExpressions);
    metadataSource.setHeaderExpressionMap(headerExpressionMap);

    MessagePublishingInterceptor interceptor = new MessagePublishingInterceptor(metadataSource);
    interceptor.setBeanFactory(beanFactory);
    interceptor.setChannelResolver(channelResolver);
    ProxyFactory pf = new ProxyFactory(new TestBeanImpl());
    pf.addAdvice(interceptor);
    TestBean proxy = (TestBean) pf.getProxy();
    proxy.test();
    Message<?> message = testChannel.receive(0);
    assertNotNull(message);
    assertEquals("foo", message.getPayload());
    assertEquals("foo", message.getHeaders().get("bar"));
    assertEquals("oleg", message.getHeaders().get("name"));
  }
Exemple #10
0
 @Override
 public void mergeLabels(Map<String, String> srcMap, Map<String, String> destMap) {
   if (srcMap == null || destMap == null) {
     return;
   }
   for (Map.Entry<String, String> entry : srcMap.entrySet()) {
     String key = entry.getKey();
     if (key.toLowerCase().startsWith("io.rancher")) {
       key = key.toLowerCase();
     }
     String value = entry.getValue();
     if (key.startsWith("io.rancher.scheduler.affinity")) {
       // merge labels
       String destValue = destMap.get(key);
       if (StringUtils.isEmpty(destValue)) {
         destMap.put(key, value);
       } else if (StringUtils.isEmpty(value)) {
         continue;
       } else if (!destValue.toLowerCase().contains(value.toLowerCase())) {
         destMap.put(key, destValue + "," + value);
       }
     } else {
       // overwrite label value
       destMap.put(key, value);
     }
   }
 }
 /** Constructor */
 Attachment(InputStream contentStream, String contentType) {
   this.body = contentStream;
   metadata = new HashMap<String, Object>();
   metadata.put("content_type", contentType);
   metadata.put("follows", true);
   this.gzipped = false;
 }
 static {
   mColumnMap.put(_ID, "integer primary key autoincrement");
   mColumnMap.put(URL, "text");
   mColumnMap.put(SOURCE_TYPE, "text");
   mColumnMap.put(Content_type, "text");
   mColumnMap.put(Timestamp, "integer");
 }
  public Object put(Object key, Object o) {
    final Object ret;
    if (_map.containsKey(key)) {
      if (Objects.equals(o, _map.get(key))) {
        return o; // nothing changed
      }
      int index = indexOfKey(key);
      ret = _map.put(key, o);
      fireEvent(ListDataEvent.CONTENTS_CHANGED, index, index);
    } else {
      ret = _map.put(key, o);

      // After put, the position can change if not LinkedHashMap
      // bug #1819318 Problem while using SortedSet with Databinding
      // bug #1839634 Problem while using HashSet with Databinding
      if (_map instanceof LinkedHashMap) {
        // bug 1869614 Problem when switching from ListModelList to ListModelMap,
        // java.lang.IndexOutOfBoundsException: 1, interval added index should be _map.size() - 1
        final int i1 = _map.size() - 1;
        fireEvent(ListDataEvent.INTERVAL_ADDED, i1, i1);
      } else if (_map instanceof SortedMap) {
        final int i1 = indexOfKey(key);
        fireEvent(ListDataEvent.INTERVAL_ADDED, i1, i1);
      } else { // bug #1839634, HashMap, not sure the iteration sequence
        // of the HashMap, must resync
        fireEvent(ListDataEvent.CONTENTS_CHANGED, -1, -1);
      }
    }
    return ret;
  }
  public void updateScore(List<Player> players) {
    try {
      if (connection == null || players.size() <= 0) {
        return;
      }

      List<String> playersName = new ArrayList<String>();
      for (Player player : players) {
        playersName.add("'" + player.getName() + "'");
      }
      String arrs = join(playersName, ",");
      String strSql = "SELECT * FROM player WHERE name IN (" + arrs + ")";

      cacheScores.clear();

      Map<String, Object> map;
      Statement sql = connection.createStatement();

      ResultSet result = sql.executeQuery(strSql);
      while (result.next()) {
        map = new HashMap<String, Object>();
        map.put("kills", result.getInt("kills"));
        map.put("deaths", result.getInt("deaths"));
        map.put("mobs", result.getInt("mobs"));
        map.put("prefix", result.getString("prefix"));
        cacheScores.put(result.getString("name"), map);
      }
      result.close();

      sql.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #15
0
 public void testAsCollectionWithMap() {
   Map map = new HashMap();
   map.put("A", "abc");
   map.put("B", "def");
   map.put("C", "xyz");
   assertAsCollection(map, 3);
 }
  /**
   * Encode the case when the <code>var</code> attribute is specified. This will render without any
   * HTML markup and put the current message in the request scope as identified by the <code>var
   * </code> attribute. Note: the iteration is by design completely stateless.
   *
   * @param context The involved faces context.
   * @param component The messages component.
   * @param messages The queued faces messages.
   * @throws IOException When an I/O error occurs.
   */
  protected void encodeMessagesRepeater(
      FacesContext context, OmniMessages component, List<FacesMessage> messages)
      throws IOException {
    String var = component.getVar();
    Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
    Object originalVar = requestMap.get(var);

    try {
      for (FacesMessage message : messages) {
        if (message.isRendered() && !component.isRedisplay()) {
          continue;
        }

        requestMap.put(var, message);

        for (UIComponent child : component.getChildren()) {
          child.encodeAll(context);
        }

        message.rendered();
      }
    } finally {
      if (originalVar != null) {
        requestMap.put(var, originalVar);
      } else {
        requestMap.remove(var);
      }
    }
  }
Exemple #17
0
  /** 获取一周回看分类节目列表 */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void getBTVPrograms() {
    try {
      Assert.notNull(typeId, "分类id不能为空!");
      Map params = new HashMap();
      params.put("typeId", typeId);
      params.put("pageSize", String.valueOf(getPager().getMax()));
      params.put("curPage", String.valueOf(getPager().getPage()));

      String response = HttpUtils.sendPost(BTV_PROGRAMS_URL, params, "utf-8");
      JSONObject jo = JSON.parseObject(response);
      if (null != jo) {
        String ret = jo.getString("ret");
        if (StringUtils.equals("0", ret)) {
          String programList = jo.getString("result");
          List<Map> rows = null;
          if (StringUtils.isNotBlank(programList)) {
            rows = JSON.parseArray(programList, Map.class);
          }
          if (null == rows) {
            rows = new ArrayList<Map>();
          }
          resultMap.put("total", jo.get("totalCount"));
          resultMap.put("rows", rows);
          jsonMap();
        }
      }
    } catch (Exception e) {
      logger.error("调用接口getBTVPrograms失败", e);
      jsonRet("1", e.getMessage());
    }
  }
 /**
  * 根据工单编号查询工单
  *
  * @param request
  * @param response
  * @throws Exception
  */
 @RequestMapping(value = "/queryWnById")
 public void queryWnById(HttpServletRequest request, HttpServletResponse response)
     throws MbvException {
   // 先在客户端验证用户以及它的手机号码
   Map<String, Object> map = new HashMap<String, Object>();
   String id = request.getParameter("id");
   log.info("WnController.queryWnById -> id: " + id);
   try {
     if (StringUtils.isNotEmpty(id)) {
       WnEntity wn = wnService.selectByPrimaryKey(Long.valueOf(id));
       if (wn == null) {
         map.put("status", "ERROR");
         map.put("reason", "查不到数据!");
       } else {
         map.put("success", true);
         map.put("entity", wn);
         map.put("docState", wn.getDocState());
       }
     }
   } catch (MbvException e) {
     throw new MbvException(MbvConstant.MBV_SYS_ERROR_TIP);
   } catch (RuntimeException e) {
     throw new MbvException(MbvConstant.MBV_SYS_ERROR_TIP);
   }
   this.returnSuccess(response, map);
 }
  @Override
  public void configure() {
    try {
      setName("AppWithStreamSizeSchedule");
      setDescription("Sample application");
      ObjectStores.createObjectStore(getConfigurer(), "input", String.class);
      ObjectStores.createObjectStore(getConfigurer(), "output", String.class);
      addWorkflow(new SampleWorkflow());
      addStream(new Stream("stream"));

      Map<String, String> scheduleProperties = Maps.newHashMap();
      scheduleProperties.put("oneKey", "oneValue");
      scheduleProperties.put("anotherKey", "anotherValue");
      scheduleProperties.put("someKey", "someValue");

      scheduleWorkflow(
          Schedules.createDataSchedule("SampleSchedule1", "", Schedules.Source.STREAM, "stream", 1),
          "SampleWorkflow",
          scheduleProperties);
      scheduleWorkflow(
          Schedules.createDataSchedule("SampleSchedule2", "", Schedules.Source.STREAM, "stream", 2),
          "SampleWorkflow",
          scheduleProperties);
    } catch (UnsupportedTypeException e) {
      throw Throwables.propagate(e);
    }
  }
Exemple #20
0
 @RequestMapping("/filme")
 public String setupForm(Map<String, Object> map) {
   Filme filme = new Filme();
   map.put("filme", filme);
   map.put("filmeList", filmeDAO.getAll());
   return "filme";
 }
 private Map<String, String> getTypes() {
   Map<String, String> statuses = new LinkedHashMap<String, String>();
   statuses.put(String.valueOf(SubscribeActor.TYPE_ACTIVE), getText("subscribePersonal.active"));
   statuses.put(String.valueOf(SubscribeActor.TYPE_PASSIVE), getText("subscribePersonal.passive"));
   statuses.put("", getText("bc.status.all"));
   return statuses;
 }
Exemple #22
0
 @RequestMapping(value = "/filme.do", method = RequestMethod.POST)
 public String doActions(
     @ModelAttribute Filme filme,
     BindingResult result,
     @RequestParam String action,
     Map<String, Object> map) {
   Filme filmeResult = new Filme();
   switch (action.toLowerCase()) {
     case "editar":
       filmeDAO.altera(filme);
       filmeResult = filme;
       break;
     case "excluir":
       filmeDAO.remove(filme);
       filmeResult = new Filme();
       break;
     case "buscar":
       Filme filmebuscado = filmeDAO.buscaPorId(filme.getId_filme());
       filmeResult = filmebuscado != null ? filmebuscado : new Filme();
       break;
   }
   map.put("filme", filmeResult);
   map.put("filmeList", filmeDAO.getAll());
   return "filme";
 }
  /**
   * Goes through an _attachments dictionary and replaces any values that are Attachment objects
   * with proper JSON metadata dicts. It registers the attachment bodies with the blob store and
   * sets the metadata 'digest' and 'follows' properties accordingly.
   */
  static Map<String, Object> installAttachmentBodies(
      Map<String, Object> attachments, Database database) {

    Map<String, Object> updatedAttachments = new HashMap<String, Object>();
    for (String name : attachments.keySet()) {
      Object value = attachments.get(name);
      if (value instanceof Attachment) {
        Attachment attachment = (Attachment) value;
        Map<String, Object> metadataMutable = new HashMap<String, Object>();
        metadataMutable.putAll(attachment.getMetadata());
        InputStream body = attachment.getBodyIfNew();
        if (body != null) {
          // Copy attachment body into the database's blob store:
          BlobStoreWriter writer = blobStoreWriterForBody(body, database);
          metadataMutable.put("length", writer.getLength());
          metadataMutable.put("digest", writer.mD5DigestString());
          metadataMutable.put("follows", true);
          database.rememberAttachmentWriter(writer);
        }
        updatedAttachments.put(name, metadataMutable);
      } else if (value instanceof AttachmentInternal) {
        throw new IllegalArgumentException(
            "AttachmentInternal objects not expected here.  Could indicate a bug");
      }
    }
    return updatedAttachments;
  }
  private Map<String, String> parseVariantPropertiesPattern(Element caseEl) throws Exception {
    String variant = DocumentHelper.getAttribute(caseEl, "matchVariant", false);

    Map<String, String> varPropsPattern = new HashMap<String, String>();

    if (variant == null) return varPropsPattern;

    for (String prop : COMMA_SPLITTER.split(variant)) {
      int eqPos = prop.indexOf("=");
      if (eqPos != -1) {
        String propName = prop.substring(0, eqPos);
        String propValue = prop.substring(eqPos + 1);
        if (propName.equals("*")) {
          throw new IndexerConfException(
              String.format(
                  "Error in matchVariant attribute: the character '*' "
                      + "can only be used as wildcard, not as variant dimension name, attribute = %1$s, at: %2$s",
                  variant, LocationAttributes.getLocation(caseEl)));
        }
        varPropsPattern.put(propName, propValue);
      } else {
        varPropsPattern.put(prop, null);
      }
    }

    return varPropsPattern;
  }
Exemple #25
0
  protected Map getChannelMap(ConsoleInput ci) {
    Map channel_map = new HashMap();

    PluginInterface[] pis = ci.azureus_core.getPluginManager().getPluginInterfaces();

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

      LoggerChannel[] logs = pis[i].getLogger().getChannels();

      if (logs.length > 0) {

        if (logs.length == 1) {

          channel_map.put(pis[i].getPluginName(), logs[0]);

        } else {

          for (int j = 0; j < logs.length; j++) {

            channel_map.put(pis[i].getPluginName() + "." + logs[j].getName(), logs[j]);
          }
        }
      }
    }

    return (channel_map);
  }
 static {
   for (TransactionStateDeserialization value :
       EnumSet.allOf(TransactionStateDeserialization.class)) {
     nameToValueMap.put(value.name(), value);
     idToValueMap.put(value.getId(), value);
   }
 }
Exemple #27
0
 private Map<Object, Object> createBooleanOptions() {
   Map<Object, Object> expectedOptions = new LinkedHashMap<Object, Object>();
   expectedOptions.put("", "Please select");
   expectedOptions.put(Boolean.TRUE, "Yes");
   expectedOptions.put(Boolean.FALSE, "No");
   return expectedOptions;
 }
  public static CloudState load(byte[] bytes, Set<String> liveNodes)
      throws KeeperException, InterruptedException {
    if (bytes == null || bytes.length == 0) {
      return new CloudState(liveNodes, Collections.<String, Map<String, Slice>>emptyMap());
    }

    LinkedHashMap<String, Object> stateMap =
        (LinkedHashMap<String, Object>) ZkStateReader.fromJSON(bytes);
    HashMap<String, Map<String, Slice>> state = new HashMap<String, Map<String, Slice>>();

    for (String collectionName : stateMap.keySet()) {
      Map<String, Object> collection = (Map<String, Object>) stateMap.get(collectionName);
      Map<String, Slice> slices = new LinkedHashMap<String, Slice>();
      for (String sliceName : collection.keySet()) {
        Map<String, Map<String, String>> sliceMap =
            (Map<String, Map<String, String>>) collection.get(sliceName);
        Map<String, ZkNodeProps> shards = new LinkedHashMap<String, ZkNodeProps>();
        for (String shardName : sliceMap.keySet()) {
          shards.put(shardName, new ZkNodeProps(sliceMap.get(shardName)));
        }
        Slice slice = new Slice(sliceName, shards);
        slices.put(sliceName, slice);
      }
      state.put(collectionName, slices);
    }
    return new CloudState(liveNodes, state);
  }
Exemple #29
0
    private void store(
        ResourceBundle resources, BibleBook book, Map fullMap, Map shortMap, Map altMap) {
      String osisName = book.getOSIS();

      String fullBook = getString(resources, osisName + FULL_KEY);

      String shortBook = getString(resources, osisName + SHORT_KEY);
      if (shortBook.length() == 0) {
        shortBook = fullBook;
      }

      String altBook = getString(resources, osisName + ALT_KEY);

      BookName bookName =
          new BookName(locale, BibleBook.fromOSIS(osisName), fullBook, shortBook, altBook);
      books.put(book, bookName);

      fullMap.put(bookName.getNormalizedLongName(), bookName);

      shortMap.put(bookName.getNormalizedShortName(), bookName);

      String[] alternates = StringUtil.split(BookName.normalize(altBook, locale), ',');

      for (int j = 0; j < alternates.length; j++) {
        altMap.put(alternates[j], bookName);
      }
    }
 public void processImage(String fileName) throws IOException {
   if (fileName.startsWith("/")) {
     throw new IllegalArgumentException();
   }
   final SourceStringReader sourceStringReader = new SourceStringReader(incoming.get(fileName));
   final ByteArrayOutputStream baos = new ByteArrayOutputStream();
   final FileFormat format = FileFormat.PNG;
   final DiagramDescription desc =
       sourceStringReader.generateDiagramDescription(baos, new FileFormatOption(format));
   final String pngFileName = format.changeName(fileName, 0);
   final String errorFileName = pngFileName.substring(0, pngFileName.length() - 4) + ".err";
   synchronized (this) {
     outgoing.remove(pngFileName);
     outgoing.remove(errorFileName);
     if (desc != null && desc.getDescription() != null) {
       outgoing.put(pngFileName, baos.toByteArray());
       if (desc.getDescription().startsWith("(Error)")) {
         final ByteArrayOutputStream errBaos = new ByteArrayOutputStream();
         sourceStringReader.generateImage(errBaos, new FileFormatOption(FileFormat.ATXT));
         errBaos.close();
         outgoing.put(errorFileName, errBaos.toByteArray());
       }
     }
   }
 }