Пример #1
0
  /**
   * @param xmlFile
   * @param tagName
   * @param tagValue
   * @param path hierarchy path, this will be the parent of the new tag, ex: root/node1/node2
   * @return
   */
  public static XmlTag createTagInFile(
      final XmlFile xmlFile,
      String tagName,
      String tagValue,
      String path,
      Map<String, String> attributes) {
    XmlTag root = xmlFile.getRootTag();

    String[] pathElements = path.split("/");

    if (pathElements.length > 0 && pathElements[0].equals(root.getName())) {
      XmlTag lastExistentParent = root;
      String curPath = pathElements[0];
      pathElements =
          (String[])
              ArrayUtils.remove(
                  pathElements, 0); // ArrayUtils.removeElement(pathElements, pathElements[0]);
      for (String curTagName : pathElements) {
        lastExistentParent = lastExistentParent.findFirstSubTag(curTagName);
        if (lastExistentParent == null) {
          lastExistentParent = createTagInFile(xmlFile, curTagName, "", curPath);
          if (lastExistentParent == null) {
            return null;
          }
        }
        curPath += "/" + curTagName;
      }
      final XmlTag newTag = lastExistentParent.createChildTag(tagName, "", tagValue, false);

      if (attributes != null) {
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
          newTag.setAttribute(entry.getKey(), entry.getValue());
        }
      }

      final XmlTag parent = lastExistentParent;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              new WriteCommandAction.Simple(
                  xmlFile.getProject(), "Create Xml Tag in File", xmlFile) {
                @Override
                protected void run() {

                  //                           newTag = (XmlTag)parent.add(newTag);
                  parent.addAfter(newTag, null);
                }
              }.execute();
            }
          };
      runnable.run();
      // PsiDocumentManager.getInstance(xmlFile.getProject()).commitDocument(document);
      return findSubTag(xmlFile, path + "/" + newTag.getName());

    } else {
      return null;
    }
  }
Пример #2
0
 public static int[] removeZeroFromChord(int[] chord) {
   int[] tempChord = chord;
   while (ArrayUtils.contains(tempChord, ZERO)) {
     int index = ArrayUtils.indexOf(tempChord, ZERO);
     tempChord = ArrayUtils.remove(tempChord, index);
   }
   return tempChord;
 }
Пример #3
0
 private static Sexp intersection(Sexp lhs, Sexp rhs) {
   Sexp intersectionSexp = new Sexp(INTERSECTION).add(lhs);
   if (rhs.first().equals(INTERSECTION)) {
     intersectionSexp.addAll(ArrayUtils.remove(rhs.getValues().toArray(), 0));
   } else {
     intersectionSexp.add(rhs);
   }
   return intersectionSexp;
 }
Пример #4
0
  public Collection getOrCreateCollection(String path) throws XMLDBException {
    path = StringUtils.removeStart(path, "/");
    path = StringUtils.removeEnd(path, "/");
    path = path.replaceAll("[/]+", "/");

    String pathWithURI = uri + path;

    Collection col = DatabaseManager.getCollection(pathWithURI, userName, password);

    if (col != null) {
      return col;
    } else {
      synchronized (syncLock) {
        col = DatabaseManager.getCollection(pathWithURI, userName, password);
        if (col != null) {
          return col;
        }
        String[] paths = path.split("/");

        String[] parentPath = (String[]) ArrayUtils.remove(paths, paths.length - 1);

        this.getOrCreateCollection(StringUtils.join(parentPath, '/'));

        CollectionManagementService mgt = this.getCollectionManagementService();

        col = mgt.createCollection(StringUtils.join(paths, '/'));

        // If we are creating a new root collection, we need to set up the indexing configuration
        // for this collection,
        // which is done by placing a collection.xconf file into the config path structure.
        if (paths.length == 1 && getCollectionRoot().endsWith(paths[0])) {
          log.info("Configuring Indexes for Collection " + paths[0]);
          // Add the index configuration file for our root config
          try {
            String confFilePath = "/collection.xconf";
            String confFileXml =
                IOUtils.toString(this.getClass().getResourceAsStream(confFilePath), "UTF-8");
            Collection configCol = getOrCreateCollection("/system/config/db/" + paths[0]);
            org.xmldb.api.base.Resource r =
                configCol.createResource("collection.xconf", "XMLResource");
            r.setContent(confFileXml);
            configCol.storeResource(r);
            log.info(
                "Wrote index configuration " + r.getParentCollection().getName() + "/" + r.getId());
          } catch (Exception e) {
            log.error(
                "Failure configuring indexes for collection "
                    + paths[0]
                    + " - indexes will not be available!",
                e);
          }
        }
        return col;
      }
    }
  }
Пример #5
0
 @Override
 public T invoke(Object... parameters) {
   if (!this.isValid()) return null;
   boolean needsInstance = this.isStatic ? false : (this.from != null ? false : true);
   Object instance = needsInstance ? parameters[0] : (this.isStatic ? null : this.from);
   if (needsInstance) parameters = ArrayUtils.remove(parameters, 0);
   try {
     return (T) this.method.invoke(instance, parameters);
   } catch (Exception e) {
     return null;
   }
 }
  /**
   * Parses a CSV header line and creates the corresponding resulting schema in the section (i.e.: a
   * set of fields with positions)
   */
  protected List<Field> parseHeaders(List<String[]> csvLines) {
    Section section = sectionInstance.getSection();
    String sectionId = section.getId();

    String headers[] = csvLines.get(0);
    log.trace("Headers for section " + sectionId + ": " + Arrays.toString(headers));

    int nlines = csvLines.size();

    for (int j = 0; j < headers.length; j++) {
      String header = StringUtils.trimToNull(headers[j]);

      if (header == null) {
        // Empty header, let's remove all!
        //
        log.warn(i18n.msg("empty_column", j));

        for (int i = 0; i < nlines; i++) {
          String[] line = csvLines.get(i);
          if (j == line.length)
          // This happens sometime: the header has one extra-tab and the lines are OK
          // we need to recraft the header only in that case
          {
            continue;
          }
          csvLines.set(i, (String[]) ArrayUtils.remove(line, j));
        }
        headers = csvLines.get(0);

        j--; // Restart from this point, which is now the next column
        continue;
      }
      log.trace("Working on header " + j + ":" + header);
      Field field = section.getFieldByHeader(header, false);

      if (field == null) {
        throw new TabValidationException(
            i18n.msg("unexpected_field_in_section_error", header, sectionId));
      }

      // Let's add a new real field on the basis of the header. The new field created gets its id
      // from the
      // original one in the schema, so it will have the "canonical" form, independently on what we
      // found
      // on the input (e.g.: upper case).
      //
      field = field.parseHeader(header, j, false);
      sectionInstance.addField(field);
    }
    return sectionInstance.getFields();
  }
Пример #7
0
  private static Sexp union(Sexp lhs, Sexp... rhs) {
    if (lhs == null) {
      return union(rhs[0], (Sexp[]) ArrayUtils.remove(rhs, 0));
    } else if (ArrayUtils.isEmpty(rhs)) {
      return lhs;
    } else if (lhs.first() != null && lhs.first().equals(UNION)) {
      for (Sexp sexp : rhs) {
        lhs.add(sexp);
      }
      return lhs;
    }

    return new Sexp(UNION).add(lhs).addAll(rhs);
  }
Пример #8
0
 /**
  * Returns the Command-arguments of a command-message.
  *
  * <p>Command-messages are formated as such: <i>/commandName arg1 arg2</i>. These are found in
  * events such as {@link org.bukkit.event.player.PlayerCommandPreprocessEvent}.
  *
  * @param commandMessage The Command-message to parse.
  * @return The command arguments.
  * @see org.bukkit.event.player.PlayerCommandPreprocessEvent
  */
 public static String[] parseCommandArgs(String commandMessage) {
   return (String[]) ArrayUtils.remove(commandMessage.split(" "), 0);
 }
Пример #9
0
  public void parse(Sheet sheet) {
    logger.debug("开始解析Sheet页:" + sheet.getSheetName());
    startSheet(sheet);

    int rowCount = sheet.getPhysicalNumberOfRows();
    logger.debug("行数:" + rowCount);

    // 遇到表头区域的时候记录开始列
    int headerStartCol = 0;

    for (Row r : sheet) {
      HSSFRow row = (HSSFRow) r;
      if (row == null) continue;

      this.rowIndex = row.getRowNum();
      if (rowIndex < startRow) {
        continue;
      }
      // sundl: row.getFirstCellNum()不是很稳定,第一列的空格有时候会是null,有时候又是空字符串,这样导致这个值不可信
      // 目前强制写成1, 后续可以考虑改成自己写找第一个非空列。
      int firstCellNum = row.getFirstCellNum();
      if (firstCellNum == -1) continue;
      else firstCellNum = 1;

      HSSFCell firstCell = row.getCell(firstCellNum);
      String firstcellString = getCellStringValue(firstCell, evaluator);

      if (!firstcellString.isEmpty()) {
        if (aresStart.contains(rowIndex)) {
          endArea();
          logger.debug("Area开始,行号: " + rowIndex);
          startArea(firstcellString);
        } else if (areaTags.indexOf(firstcellString) != -1) {
          endArea();
          logger.debug("Area开始,行号: " + rowIndex);
          startArea(firstcellString);
        }

        if (blockStart.keySet().contains(rowIndex)) {
          endBlock();
          startBlock(firstcellString, blockStart.get(rowIndex));
        } else if (blocks.containsKey(firstcellString)) {
          endBlock();
          startBlock(firstcellString, blocks.get(firstcellString));
          // Text区域第一行暂时不解析
          if (currentBlockType == BlockTypes.TEXT) {
            continue;
          }
        }
      }

      String[] strings = readRowStrings(row, 1, evaluator);
      switch (currentBlockType) {
        case BlockTypes.KEY_VALUE:
          parseKeyValue(row, 1);
          break;
        case BlockTypes.TABLE:
          if (!headerFound) {
            // header按理说不应该存在空字符串,开头应该不会,但结尾可能存在
            while (StringUtils.isEmpty(strings[strings.length - 1])) {
              strings = (String[]) ArrayUtils.remove(strings, strings.length - 1);
            }
            headerStartCol = firstCellNum;
            header(strings);
            headerFound = true;
          } else {
            strings = POIUtils.readRowStrings(row, headerStartCol, evaluator);
            row(strings);
          }
          break;
        case BlockTypes.TEXT:
          text.append(StringUtils.join(strings));
          text.append('\n');
          break;
      }
    }

    endBlock();
    endArea();
    endSheet();
  }
Пример #10
0
  /**
   * 功能:获取除去占比经营数据总收的其它图例Id(一二级别或,三四级别的ID)
   *
   * <p>作者 杨荣忠 2015-1-19 下午05:04:21
   *
   * @param conditionEntity
   * @return
   */
  public static String[] getZhabiDetachId(ConditionEntity conditionEntity, int type) {
    String[] array = ImgTool.getDimensionAllID(conditionEntity, type);

    String[] result_add = (String[]) ArrayUtils.remove(array, 0); // 除去主营图例ID
    return result_add;
  }
Пример #11
0
  /**
   * Instantiates a new user preferences wrapper.
   *
   * @param context The application context.
   */
  @SuppressWarnings("deprecation")
  @SuppressLint("InlinedApi")
  @TargetApi(17)
  public GlobalPrefs(Context context) {
    AppData appData = new AppData(context);
    mPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    // Locale
    mLocaleCode = mPreferences.getString(KEY_LOCALE_OVERRIDE, DEFAULT_LOCALE_OVERRIDE);
    mLocale = TextUtils.isEmpty(mLocaleCode) ? Locale.getDefault() : createLocale(mLocaleCode);
    Locale[] availableLocales = Locale.getAvailableLocales();
    String[] values = context.getResources().getStringArray(R.array.localeOverride_values);
    String[] entries = new String[values.length];
    for (int i = values.length - 1; i > 0; i--) {
      Locale locale = createLocale(values[i]);

      // Get intersection of languages (available on device) and (translated for Mupen)
      if (ArrayUtils.contains(availableLocales, locale)) {
        // Get the name of the language, as written natively
        entries[i] = WordUtils.capitalize(locale.getDisplayName(locale));
      } else {
        // Remove the item from the list
        entries = (String[]) ArrayUtils.remove(entries, i);
        values = (String[]) ArrayUtils.remove(values, i);
      }
    }
    entries[0] = context.getString(R.string.localeOverride_entrySystemDefault);
    mLocaleNames = entries;
    mLocaleCodes = values;

    // Files
    userDataDir = mPreferences.getString("pathGameSaves", "");
    galleryCacheDir = userDataDir + "/GalleryCache";
    coverArtDir = galleryCacheDir + "/CoverArt";
    unzippedRomsDir = galleryCacheDir + "/UnzippedRoms";
    profilesDir = userDataDir + "/Profiles";
    crashLogDir = userDataDir + "/CrashLogs";
    coreUserDataDir = userDataDir + "/CoreConfig/UserData";
    coreUserCacheDir = userDataDir + "/CoreConfig/UserCache";
    hiResTextureDir =
        coreUserDataDir + "/mupen64plus/hires_texture/"; // MUST match what rice assumes natively
    romInfoCache_cfg = galleryCacheDir + "/romInfoCache.cfg";
    controllerProfiles_cfg = profilesDir + "/controller.cfg";
    touchscreenProfiles_cfg = profilesDir + "/touchscreen.cfg";
    emulationProfiles_cfg = profilesDir + "/emulation.cfg";
    customCheats_txt = profilesDir + "/customCheats.txt";

    // Plug-ins
    audioPlugin = new Plugin(mPreferences, appData.libsDir, "audioPlugin");

    // Library prefs
    isRecentShown = mPreferences.getBoolean("showRecentlyPlayed", true);
    isFullNameShown = mPreferences.getBoolean("showFullNames", true);

    // Touchscreen prefs
    isTouchscreenFeedbackEnabled = mPreferences.getBoolean("touchscreenFeedback", false);
    isTouchscreenAnimated = mPreferences.getBoolean("touchscreenAnimation", false);
    touchscreenScale = ((float) mPreferences.getInt("touchscreenScale", 100)) / 100.0f;
    touchscreenTransparency = (255 * mPreferences.getInt("touchscreenTransparency", 100)) / 100;
    touchscreenSkin =
        appData.touchscreenSkinsDir + "/" + mPreferences.getString("touchscreenStyle", "Outline");
    touchscreenAutoHold = getSafeInt(mPreferences, "touchscreenAutoHold", 0);

    // Xperia PLAY touchpad prefs
    isTouchpadEnabled =
        appData.hardwareInfo.isXperiaPlay && mPreferences.getBoolean("touchpadEnabled", true);
    isTouchpadFeedbackEnabled = mPreferences.getBoolean("touchpadFeedback", false);
    touchpadSkin = appData.touchpadSkinsDir + "/Xperia-Play";
    ConfigFile touchpad_cfg = new ConfigFile(appData.touchpadProfiles_cfg);
    ConfigSection section = touchpad_cfg.get(mPreferences.getString("touchpadLayout", ""));
    if (section != null) touchpadProfile = new Profile(true, section);
    else touchpadProfile = null;

    // Video prefs
    displayOrientation = getSafeInt(mPreferences, "displayOrientation", 0);
    displayPosition = getSafeInt(mPreferences, "displayPosition", Gravity.CENTER_VERTICAL);
    int transparencyPercent = mPreferences.getInt("displayActionBarTransparency", 50);
    displayActionBarTransparency = (255 * transparencyPercent) / 100;
    isFpsEnabled = mPreferences.getBoolean("displayFps", false);
    int selectedHardwareType = getSafeInt(mPreferences, "videoHardwareType", -1);
    isPolygonOffsetHackEnabled = selectedHardwareType > -2;
    videoHardwareType =
        selectedHardwareType < 0 ? appData.hardwareInfo.hardwareType : selectedHardwareType;
    switch (videoHardwareType) {
      case HardwareInfo.HARDWARE_TYPE_OMAP:
        videoPolygonOffset = 0.2f;
        break;
      case HardwareInfo.HARDWARE_TYPE_OMAP_2:
        videoPolygonOffset = -1.5f;
        break;
      case HardwareInfo.HARDWARE_TYPE_QUALCOMM:
        videoPolygonOffset = -0.2f;
        break;
      case HardwareInfo.HARDWARE_TYPE_IMAP:
        videoPolygonOffset = -0.001f;
        break;
      case HardwareInfo.HARDWARE_TYPE_TEGRA:
        videoPolygonOffset = -2.0f;
        break;
      case HardwareInfo.HARDWARE_TYPE_UNKNOWN:
        videoPolygonOffset = -1.5f;
        break;
      default:
        videoPolygonOffset =
            SafeMethods.toFloat(mPreferences.getString("videoPolygonOffset", "-1.5"), -1.5f);
        break;
    }
    isImmersiveModeEnabled = mPreferences.getBoolean("displayImmersiveMode", false);

    // Audio prefs
    audioSwapChannels = mPreferences.getBoolean("audioSwapChannels", false);
    audioSDLSecondaryBufferSize = getSafeInt(mPreferences, "audioSDLBufferSize", 2048);
    audioSLESSecondaryBufferSize = getSafeInt(mPreferences, "audioSLESBufferSize", 1024);
    audioSLESSecondaryBufferNbr = getSafeInt(mPreferences, "audioSLESBufferNbr", 2);

    if (audioPlugin.enabled)
      isFramelimiterEnabled = mPreferences.getBoolean("audioSynchronize", true);
    else isFramelimiterEnabled = !mPreferences.getString("audioPlugin", "").equals("nospeedlimit");

    // User interface modes
    String navMode = mPreferences.getString("navigationMode", "auto");
    if (navMode.equals("bigscreen")) isBigScreenMode = true;
    else if (navMode.equals("standard")) isBigScreenMode = false;
    else
      isBigScreenMode =
          AppData.IS_OUYA_HARDWARE
              || appData.isAndroidTv; // TODO: Add other systems as they enter market
    isActionBarAvailable = AppData.IS_HONEYCOMB && !isBigScreenMode;

    // Peripheral share mode
    isControllerShared = mPreferences.getBoolean("inputShareController", false);

    // Determine the key codes that should not be mapped to controls
    boolean volKeysMappable = mPreferences.getBoolean("inputVolumeMappable", false);
    List<Integer> unmappables = new ArrayList<Integer>();
    unmappables.add(KeyEvent.KEYCODE_MENU);
    if (AppData.IS_HONEYCOMB) {
      // Back key is needed to show/hide the action bar in HC+
      unmappables.add(KeyEvent.KEYCODE_BACK);
    }
    if (!volKeysMappable) {
      unmappables.add(KeyEvent.KEYCODE_VOLUME_UP);
      unmappables.add(KeyEvent.KEYCODE_VOLUME_DOWN);
      unmappables.add(KeyEvent.KEYCODE_VOLUME_MUTE);
    }
    unmappableKeyCodes = Collections.unmodifiableList(unmappables);

    // Determine the pixel dimensions of the rendering context and view surface
    {
      // Screen size
      final WindowManager windowManager =
          (WindowManager) context.getSystemService(android.content.Context.WINDOW_SERVICE);
      Display display = windowManager.getDefaultDisplay();
      int stretchWidth;
      int stretchHeight;
      if (display == null) {
        stretchWidth = stretchHeight = 0;
      } else if (AppData.IS_KITKAT && isImmersiveModeEnabled) {
        DisplayMetrics metrics = new DisplayMetrics();
        display.getRealMetrics(metrics);
        stretchWidth = metrics.widthPixels;
        stretchHeight = metrics.heightPixels;
      } else {
        stretchWidth = display.getWidth();
        stretchHeight = display.getHeight();
      }

      float aspect = 0.75f; // TODO: Handle PAL
      boolean isLetterboxed = ((float) stretchHeight / (float) stretchWidth) > aspect;
      int zoomWidth = isLetterboxed ? stretchWidth : Math.round((float) stretchHeight / aspect);
      int zoomHeight = isLetterboxed ? Math.round((float) stretchWidth * aspect) : stretchHeight;
      int cropWidth = isLetterboxed ? Math.round((float) stretchHeight / aspect) : stretchWidth;
      int cropHeight = isLetterboxed ? stretchHeight : Math.round((float) stretchWidth * aspect);

      int hResolution = getSafeInt(mPreferences, "displayResolution", 0);
      String scaling = mPreferences.getString("displayScaling", "zoom");
      if (hResolution == 0) {
        // Native resolution
        if (scaling.equals("stretch")) {
          videoRenderWidth = videoSurfaceWidth = stretchWidth;
          videoRenderHeight = videoSurfaceHeight = stretchHeight;
        } else if (scaling.equals("crop")) {
          videoRenderWidth = videoSurfaceWidth = cropWidth;
          videoRenderHeight = videoSurfaceHeight = cropHeight;
        } else // scaling.equals( "zoom") || scaling.equals( "none" )
        {
          videoRenderWidth = videoSurfaceWidth = zoomWidth;
          videoRenderHeight = videoSurfaceHeight = zoomHeight;
        }
      } else {
        // Non-native resolution
        switch (hResolution) {
          case 720:
            videoRenderWidth = 960;
            videoRenderHeight = 720;
            break;
          case 600:
            videoRenderWidth = 800;
            videoRenderHeight = 600;
            break;
          case 480:
            videoRenderWidth = 640;
            videoRenderHeight = 480;
            break;
          case 360:
            videoRenderWidth = 480;
            videoRenderHeight = 360;
            break;
          case 240:
            videoRenderWidth = 320;
            videoRenderHeight = 240;
            break;
          case 120:
            videoRenderWidth = 160;
            videoRenderHeight = 120;
            break;
          default:
            videoRenderWidth = Math.round((float) hResolution / aspect);
            videoRenderHeight = hResolution;
            break;
        }
        if (scaling.equals("zoom")) {
          videoSurfaceWidth = zoomWidth;
          videoSurfaceHeight = zoomHeight;
        } else if (scaling.equals("crop")) {
          videoSurfaceWidth = cropWidth;
          videoSurfaceHeight = cropHeight;
        } else if (scaling.equals("stretch")) {
          videoSurfaceWidth = stretchWidth;
          videoSurfaceHeight = stretchHeight;
        } else // scaling.equals( "none" )
        {
          videoSurfaceWidth = videoRenderWidth;
          videoSurfaceHeight = videoRenderHeight;
        }
      }
    }
  }
Пример #12
0
  /**
   * @brief 数组工具
   * @details 详细说明
   * @warning 注意事项
   * @date 2014-7-11 上午11:25:18
   */
  @Test
  public void array() {
    // 追加元素到数组尾部
    int[] array1 = {1, 2};
    array1 = ArrayUtils.add(array1, 3); // => [1, 2, 3]

    System.out.println(array1.length); // 3
    System.out.println(array1[2]); // 3

    // 删除指定位置的元素
    int[] array2 = {1, 2, 3};
    array2 = ArrayUtils.remove(array2, 2); // => [1, 2]

    System.out.println(array2.length); // 2

    // 截取部分元素
    int[] array3 = {1, 2, 3, 4};
    array3 = ArrayUtils.subarray(array3, 1, 3); // => [2, 3]

    System.out.println(array3.length); // 2

    // 数组拷贝
    String[] array4 = {"aaa", "bbb", "ccc"};
    String[] copied = (String[]) ArrayUtils.clone(array4); // => {"aaa", "bbb", "ccc"}

    System.out.println(copied.length); // 3

    // 判断是否包含某元素
    String[] array5 = {"aaa", "bbb", "ccc", "bbb"};
    boolean result1 = ArrayUtils.contains(array5, "bbb"); // => true
    System.out.println(result1); // true

    // 判断某元素在数组中出现的位置(从前往后,没有返回-1)
    int result2 = ArrayUtils.indexOf(array5, "bbb"); // => 1
    System.out.println(result2); // 1

    // 判断某元素在数组中出现的位置(从后往前,没有返回-1)
    int result3 = ArrayUtils.lastIndexOf(array5, "bbb"); // => 3
    System.out.println(result3); // 3

    // 数组转Map
    Map<Object, Object> map =
        ArrayUtils.toMap(
            new String[][] {
              {"key1", "value1"},
              {"key2", "value2"}
            });
    System.out.println(map.get("key1")); // "value1"
    System.out.println(map.get("key2")); // "value2"

    // 判断数组是否为空
    Object[] array61 = new Object[0];
    Object[] array62 = null;
    Object[] array63 = new Object[] {"aaa"};

    System.out.println(ArrayUtils.isEmpty(array61)); // true
    System.out.println(ArrayUtils.isEmpty(array62)); // true

    // 判断数组长度是否相等
    Object[] array71 = new Object[] {"aa", "bb", "cc"};
    Object[] array72 = new Object[] {"dd", "ee", "ff"};

    System.out.println(ArrayUtils.isSameLength(array71, array72)); // true

    // 判断数组元素内容是否相等
    Object[] array81 = new Object[] {"aa", "bb", "cc"};
    Object[] array82 = new Object[] {"aa", "bb", "cc"};

    System.out.println(ArrayUtils.isEquals(array81, array82));

    // Integer[] 转化为 int[]
    Integer[] array9 = new Integer[] {1, 2};
    int[] result = ArrayUtils.toPrimitive(array9);

    System.out.println(result.length); // 2
    System.out.println(result[0]); // 1

    // int[] 转化为 Integer[]
    int[] array10 = new int[] {1, 2};
    Integer[] result10 = ArrayUtils.toObject(array10);

    System.out.println(result.length); // 2
    System.out.println(result10[0].intValue()); // 1
  }
Пример #13
0
  public boolean onCommand(
      CommandSender sender, org.bukkit.command.Command cmd, String label, String[] args) {
    boolean help = false;
    if (args.length == 0 || args[0].equals("?") || args[0].equals("help")) {
      this.getCommands(sender, this, cmd);
      help = true;
    }
    if (!help) {
      try {
        int page = Integer.parseInt(args[0]);
        this.getCommands(sender, this, cmd, page);
        help = true;
      } catch (Exception ex) {
      }
    }
    if (help) {
      return true;
    }

    Command command = commands.get(args[0].toLowerCase());
    if (command != null) {
      CommandAccess access = command.getAccess();
      if (!access.hasAccess(sender)) {
        ChatUtils.error(sender, "You do not have access to this command.");
        return true;
      } else {
        try {
          args = (String[]) ArrayUtils.remove(args, 0);
          if (args.length == 0) {
            // if (!command.hasValues()) {
            return command.execute(sender, cmd, args);
            // }
            // this.getCommands(sender, command, cmd);
            // return true;
          } else {
            if (args[0].equals("?")) {
              this.getCommands(sender, command, cmd);
              return true;
            }
            try {
              try {
                return command.execute(sender, cmd, args);
              } catch (Exception ex1) {
                ChatUtils.error(sender, "Exception caught while executing this command.");
                ex1.printStackTrace();
              }
            } catch (Exception ex) {
              int page = Integer.parseInt(args[0]);
              this.getCommands(sender, command, cmd, page);
              return true;
            }
          }
        } catch (Exception ex) {
          ChatUtils.error(sender, "Exception caught while executing this command.");
          ex.printStackTrace();
        }
      }
    } else {
      ChatUtils.error(sender, "Did not recognize '%s' as a command.", args[0]);
      return true;
    }
    return false;
  }