Пример #1
0
 @Override
 public void closeHousing() {
   boolean toCloseWindow = true;
   MCTContentArea centerPane = housingViewManifestation.getContentArea();
   if (centerPane != null) {
     View centerPaneView = centerPane.getHousedViewManifestation();
     AbstractComponent centerComponent = centerPaneView.getManifestedComponent();
     if (!centerComponent.isStale() && centerComponent.isDirty()) {
       toCloseWindow =
           commitOrAbortPendingChanges(
               centerPaneView,
               MessageFormat.format(
                   BUNDLE.getString("centerpane.modified.alert.text"),
                   centerPaneView.getInfo().getViewName(),
                   centerComponent.getDisplayName()));
     }
   }
   View inspectionArea = housingViewManifestation.getInspectionArea();
   if (inspectionArea != null) {
     View inspectorPaneView = inspectionArea.getHousedViewManifestation();
     AbstractComponent inspectorComponent = inspectorPaneView.getManifestedComponent();
     if (!inspectorComponent.isStale() && inspectorComponent.isDirty()) {
       toCloseWindow =
           commitOrAbortPendingChanges(
               inspectionArea,
               MessageFormat.format(
                   BUNDLE.getString("inspectorpane.modified.alert.text"),
                   inspectorPaneView.getInfo().getViewName(),
                   inspectorComponent.getDisplayName()));
     }
   }
   if (toCloseWindow) {
     disposeHousing();
   }
 }
  public Properties getDBPameterProperties(String connectionStr) {
    Properties paramProperties = new Properties();
    if (connectionStr != null) {
      String matchSubStr = connectionStr.substring(0, 8);
      Set<Object> s = PROP.keySet();
      Iterator<Object> it = s.iterator();
      while (it.hasNext()) {
        String id = (String) it.next();
        String value = PROP.getProperty(id);
        if (value.contains(matchSubStr)) {
          paramProperties.setProperty(PluginConstant.DBTYPE_PROPERTY, id);
          MessageFormat mf = new MessageFormat(value);
          Object[] parseResult = mf.parse(connectionStr, new ParsePosition(0));
          if (parseResult != null) {
            if (parseResult[0] != null) {
              paramProperties.setProperty(
                  PluginConstant.HOSTNAME_PROPERTY, (String) parseResult[0]);
            }

            if (parseResult[1] != null) {
              paramProperties.setProperty(PluginConstant.PORT_PROPERTY, (String) parseResult[1]);
            }

            break;
          }
        }
      }
    } else {
      paramProperties.setProperty(PluginConstant.DBTYPE_PROPERTY, "");
      paramProperties.setProperty(PluginConstant.HOSTNAME_PROPERTY, "");
      paramProperties.setProperty(PluginConstant.PORT_PROPERTY, "");
    }

    return paramProperties;
  }
Пример #3
0
  @Override
  public List<FeedUpdater> getFeedUpdaters(Project project) {
    List<FeedUpdater> result = new ArrayList<FeedUpdater>();

    DevInfProjectExt ext = project.getExtension(DevInfProjectExt.class);
    if (ext != null) {
      String ciServer = ext.getCiUrl();
      if (StringUtils.isNotBlank(ciServer)) {
        String projectId = project.getUuid().toString();
        String url = null;
        try {
          url = StringUtils.removeEnd(ciServer, "/") + JENKINS_RSS_ALL; // $NON-NLS-1$
          SyndFeedUpdater feedUpdater =
              new SyndFeedUpdater(new URL(url), projectId, "jenkins", "Jenkins"); // $NON-NLS-1$
          result.add(feedUpdater);
        } catch (MalformedURLException e) {
          LOG.info(
              MessageFormat.format(
                  "{0} is not a valid URL. Fetching Jenkins feed for {1} not possible.",
                  url, project.getName()));
        }
      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              MessageFormat.format(
                  "No CI URL defined. Fetching Jenkins feed for {0} not possible.",
                  project.getName()));
        }
      }
    }
    return result;
  }
Пример #4
0
 public void play(String videoName) {
   try {
     Intent videoPlayerIntent = new Intent(VIDEO_PLAYER_INTENT);
     videoPlayerIntent.putExtra(VIDEO_NAME_PARAMETER, videoName);
     context.startActivity(videoPlayerIntent);
   } catch (ActivityNotFoundException e) {
     Log.logError(MessageFormat.format("Could not play video: {0}. Exception: {1}", videoName, e));
     new AlertDialog.Builder(context)
         .setMessage(R.string.videos_IEC_not_installed_dialog_message)
         .setTitle(R.string.videos_cannot_play_video_dialog_title)
         .setCancelable(true)
         .setNeutralButton(
             android.R.string.ok,
             new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
                 dialog.dismiss();
               }
             })
         .show();
   } catch (Exception e) {
     Log.logError(MessageFormat.format("Could not play video: {0}. Exception: {1}", videoName, e));
     new AlertDialog.Builder(context)
         .setMessage(R.string.videos_unknown_error_dialog_message)
         .setTitle(R.string.videos_cannot_play_video_dialog_title)
         .setCancelable(true)
         .setNeutralButton(
             android.R.string.ok,
             new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
                 dialog.dismiss();
               }
             })
         .show();
   }
 }
Пример #5
0
  /**
   * 获取验证码
   *
   * @throws IOException
   * @throws UnsupportedEncodingException
   */
  public String getCaptcha(String mobile)
      throws ParameterException, UnsupportedEncodingException, IOException {
    if (mobile == null || mobile == "") {
      throw new ParameterException("手机号不能为空!!");
    }
    // 生成验证码
    String base = "0123456789";
    Random rd = new Random();
    String randomCode = "";
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 6; i++) {
      int num = rd.nextInt(base.length());
      sb.append(base.charAt(num));
    }
    randomCode = sb.toString();
    PlayCache.set(Constant.CAPTHCA + mobile, randomCode, 120);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
    String sendTime = sdf.format(new Date());
    String sendTime2 = sdf2.format(new Date());

    MessageFormat mf = new MessageFormat(Constant.SMS_API);
    String[] params = {sendTime2, randomCode, mobile, sendTime};
    // 调用短信平台发送验证码
    return HttpUtils.doGet1(mf.format(params)).getMessage();
  }
Пример #6
0
  public String toLogString() {
    boolean hasVirtualHost = (null != this.getVirtualHost());
    boolean hasClientId = (null != getClientId());

    if (hasClientId && hasVirtualHost) {
      return "["
          + MessageFormat.format(
              CONNECTION_FORMAT,
              getConnectionId(),
              getClientId(),
              getRemoteAddressString(),
              getVirtualHost().getName())
          + "] ";
    } else if (hasClientId) {
      return "["
          + MessageFormat.format(
              USER_FORMAT, getConnectionId(), getClientId(), getRemoteAddressString())
          + "] ";

    } else {
      return "["
          + MessageFormat.format(SOCKET_FORMAT, getConnectionId(), getRemoteAddressString())
          + "] ";
    }
  }
Пример #7
0
    /**
     * Converts timestamp into some string representation.
     *
     * @param aTime time to convert.
     * @return string.
     */
    private String pollTimeToString(long aTime) {
      String timeS;

      if (aTime == -1) {
        timeS = Strings.message("guide.dialog.readinglists.table.latest.never");
      } else {
        TimeRange range = findTimeRange(aTime);
        if (range == TimeRange.TR_FUTURE) {
          timeS = Strings.message("guide.dialog.readinglists.table.latest.never");
        } else if (range == TimeRange.TR_TODAY) {
          DateFormat fmt = DateFormat.getTimeInstance(DateFormat.SHORT);
          timeS =
              MessageFormat.format(
                  Strings.message("guide.dialog.readinglists.table.latest.today.0"),
                  fmt.format(new Date(aTime)));
        } else if (range == TimeRange.TR_YESTERDAY) {
          DateFormat fmt = DateFormat.getTimeInstance(DateFormat.SHORT);
          timeS =
              MessageFormat.format(
                  Strings.message("guide.dialog.readinglists.table.latest.yesterday.0"),
                  fmt.format(new Date(aTime)));
        } else {
          timeS = DATE_FORMAT.format(new Date(aTime));
        }
      }

      return timeS;
    }
Пример #8
0
  /**
   * Set the edge flag reference to the new array. The number of valid items is taken to be the
   * length of the array (there's only one flag per edge). This replaces the existing edge flag
   * array reference with the new reference. If set to null, will clear the use of edge flags.
   *
   * <p>In a live scene graph, can only be called during the data changed callback.
   *
   * @param flags The new array reference to use for edge flag information
   * @throws InvalidWriteTimingException An attempt was made to write outside of the
   *     NodeUpdateListener bounds changed callback method
   */
  public void setEdgeFlags(ByteBuffer flags)
      throws IllegalArgumentException, InvalidWriteTimingException {
    if (isLive() && updateHandler != null && !updateHandler.isDataWritePermitted(this))
      throw new InvalidWriteTimingException(getBoundsWriteTimingMessage());

    if ((flags != null) && (flags.limit() < numCoords)) {
      I18nManager intl_mgr = I18nManager.getManager();
      String msg_pattern = intl_mgr.getString(EDGE_ARRAY_LENGTH_PROP);

      Locale lcl = intl_mgr.getFoundLocale();

      NumberFormat n_fmt = NumberFormat.getNumberInstance(lcl);

      Object[] msg_args = {new Integer(flags.limit()), new Integer(numCoords)};
      Format[] fmts = {n_fmt, n_fmt};
      MessageFormat msg_fmt = new MessageFormat(msg_pattern, lcl);
      msg_fmt.setFormats(fmts);
      String msg = msg_fmt.format(msg_args);

      throw new IllegalArgumentException(msg);
    }

    edgeBuffer = flags;

    if (flags == null) vertexFormat &= EDGE_CLEAR;
    else vertexFormat |= EDGES;
  }
  @Test
  public void testOverriddenBuiltinFormat() {
    final Calendar cal = Calendar.getInstance();
    cal.set(2007, Calendar.JANUARY, 23);
    final Object[] args = new Object[] {cal.getTime()};
    final Locale[] availableLocales = DateFormat.getAvailableLocales();
    final Map<String, ? extends FormatFactory> dateRegistry =
        Collections.singletonMap("date", new OverrideShortDateFormatFactory());

    // check the non-overridden builtins:
    checkBuiltInFormat("1: {0,date}", dateRegistry, args, availableLocales);
    checkBuiltInFormat("2: {0,date,medium}", dateRegistry, args, availableLocales);
    checkBuiltInFormat("3: {0,date,long}", dateRegistry, args, availableLocales);
    checkBuiltInFormat("4: {0,date,full}", dateRegistry, args, availableLocales);
    checkBuiltInFormat("5: {0,date,d MMM yy}", dateRegistry, args, availableLocales);

    // check the overridden format:
    for (int i = -1; i < availableLocales.length; i++) {
      final Locale locale = i < 0 ? null : availableLocales[i];
      final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
      final String pattern = "{0,date,short}";
      final ExtendedMessageFormat dateShort =
          new ExtendedMessageFormat(pattern, locale, dateRegistry);
      assertEquals(
          "overridden date,short format", dateDefault.format(args), dateShort.format(args));
      assertEquals("overridden date,short pattern", pattern, dateShort.toPattern());
    }
  }
Пример #10
0
  private void writeLogEntry(PrintWriter out, LogEntry logEntry) {
    if (logEntry.getEntriesCount() == 0) {
      return;
    }

    String message = logEntry.getMessage().replace(QUOTE_CHARACTER, QUOTE_SPECIAL_CHARACTER);
    message =
        message.replace(ANGLE_OPENING_BRACKET_CHARACTER, ANGLE_OPENING_BRACKET_SPECIAL_CHARACTER);
    message =
        message.replace(ANGLE_CLOSING_BRACKET_CHARACTER, ANGLE_CLOSING_BRACKET_SPECIAL_CHARACTER);

    out.println(
        MessageFormat.format(
            LOGENTRY_START_NODE,
            new String[] {message, Integer.toString(logEntry.getRevision()), logEntry.getDate()}));

    List<PathEntry> pathEntries = logEntry.getPathEntries();
    for (PathEntry pathEntry : pathEntries) {
      out.println(
          MessageFormat.format(
              PATH_NODE, new String[] {pathEntry.getAction(), pathEntry.getPath()}));
    }

    out.println(LOGENTRY_END_NODE);
  }
  /**
   * @tests java.text.MessageFormat#format(java.lang.Object, java.lang.StringBuffer,
   *     java.text.FieldPosition)
   */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "format",
      args = {java.lang.Object.class, java.lang.StringBuffer.class, java.text.FieldPosition.class})
  public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
    // Test for method java.lang.StringBuffer
    // java.text.MessageFormat.format(java.lang.Object,
    // java.lang.StringBuffer, java.text.FieldPosition)
    new Support_MessageFormat(
            "test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition")
        .t_format_with_FieldPosition();

    String pattern =
        "On {4,date} at {3,time}, he ate {2,number, integer} " + "hamburger{2,choice,1#|1<s}.";
    MessageFormat format = new MessageFormat(pattern, Locale.US);

    Object[] objects = new Object[] {"", new Integer(3), 8, ""};

    try {
      format.format(objects, new StringBuffer(), new FieldPosition(DateFormat.Field.AM_PM));
      fail("IllegalArgumentException was not thrown.");
    } catch (IllegalArgumentException iae) {
      // expected
    }
  }
Пример #12
0
 public BusinessException(Status status, Object parameter) {
   super(
       status.getHttpStatusCode(),
       MessageFormat.format(status.getReasonPhrase(), parameter),
       Arrays.asList(MessageFormat.format(status.getReasonPhrase(), parameter)),
       new BusinessException());
 }
Пример #13
0
  // used in ITFocusValidationAware#testGlobalMessageIsIgnored
  public void createGlobalMessageAndCheckFocus() {
    FacesContext context = FacesContext.getCurrentInstance();
    AbstractFocus comp = getComponent();
    FocusRendererBase renderer = getRenderer();

    // form should be focused
    final String expectedFocusCandidates = "form";
    String actualFocusCandidates = renderer.getFocusCandidatesAsString(context, comp);
    if (!expectedFocusCandidates.equals(actualFocusCandidates)) {
      createGlobalMessageAndCheckFocusResult =
          MessageFormat.format(
              "Only form should be focused. Expected focus candidates <{0}>, but have: <{1}>.",
              expectedFocusCandidates, actualFocusCandidates);
      return;
    }

    // create global message
    context.addMessage(null, new FacesMessage("global message"));

    // form should be still focused
    actualFocusCandidates = renderer.getFocusCandidatesAsString(context, comp);
    if (!expectedFocusCandidates.equals(actualFocusCandidates)) {
      createGlobalMessageAndCheckFocusResult =
          MessageFormat.format(
              "Only form should be focused. Expected focus candidates <{0}>, but have: <{1}>.",
              expectedFocusCandidates, actualFocusCandidates);
      return;
    }
    createGlobalMessageAndCheckFocusResult = PASSED;
  }
Пример #14
0
 /**
  * 按照数据库类型,封装SQL
  *
  * @param dbType 数据库类型
  * @param sql
  * @param page
  * @param rows
  * @return
  */
 public static String createPageSql(String dbType, String sql, int page, int rows) {
   int beginNum = (page - 1) * rows;
   String[] sqlParam = new String[3];
   sqlParam[0] = sql;
   sqlParam[1] = beginNum + "";
   sqlParam[2] = rows + "";
   String jdbcType = dbType;
   if (jdbcType == null || "".equals(jdbcType)) {
     throw new RuntimeException(
         "org.jeecgframework.minidao.aop.MiniDaoHandler:(数据库类型:dbType)没有设置,请检查配置文件");
   }
   if (jdbcType.indexOf(DATABSE_TYPE_MYSQL) != -1) {
     sql = MessageFormat.format(MYSQL_SQL, sqlParam);
   } else if (jdbcType.indexOf(DATABSE_TYPE_POSTGRE) != -1) {
     sql = MessageFormat.format(POSTGRE_SQL, sqlParam);
   } else {
     int beginIndex = (page - 1) * rows;
     int endIndex = beginIndex + rows;
     sqlParam[2] = Integer.toString(beginIndex);
     sqlParam[1] = Integer.toString(endIndex);
     if (jdbcType.indexOf(DATABSE_TYPE_ORACLE) != -1) {
       sql = MessageFormat.format(ORACLE_SQL, sqlParam);
     } else if (jdbcType.indexOf(DATABSE_TYPE_SQLSERVER) != -1) {
       sqlParam[0] = sql.substring(getAfterSelectInsertPoint(sql));
       sql = MessageFormat.format(SQLSERVER_SQL, sqlParam);
     }
   }
   return sql;
 }
 /* (non-Javadoc)
  * @see com.code.aon.ui.form.event.ControllerAdapter#beforeBeanUpdated(com.code.aon.ui.form.event.ControllerEvent)
  */
 @Override
 public void beforeBeanUpdated(ControllerEvent event) throws ControllerListenerException {
   UserController uc = (UserController) event.getController();
   User user = (User) uc.getTo();
   UserManager userManager = uc.getUserManager();
   String name = user.getName();
   name = (name.equals(userManager.getUser().getName())) ? userManager.getUser().getName() : name;
   String password = userManager.getPassword();
   if (password == null
       || password.equals("")
       || password.equals(userManager.getUser().getPasswd())) {
     userManager.setChangePassword(false);
   } else {
     userManager.setChangePassword(true);
   }
   userManager.setName(name);
   try {
     userManager.accept(null);
     user.setLogin(userManager.getId());
   } catch (MaximumLoginException e) {
     FacesContext ctx = FacesContext.getCurrentInstance();
     ResourceBundle bundle =
         ResourceBundle.getBundle(IOperation.MESSAGES_FILE, ctx.getViewRoot().getLocale());
     MessageFormat mf = new MessageFormat(bundle.getString(e.getMessage()));
     throw new ControllerListenerException(mf.format(new Object[] {e.getArg()}), e);
   }
 }
Пример #16
0
 /**
  * @param bigg
  * @param input
  * @param output
  * @param parameters
  * @throws IOException
  * @throws XMLStreamException
  */
 public void batchProcess(BiGGDB bigg, File input, File output, Parameters parameters)
     throws IOException, XMLStreamException {
   // We test if non-existing path denotes a file or directory by checking if
   // it contains at least one period in its name. If so, we assume it is a
   // file.
   if (!output.exists()
       && (output.getName().lastIndexOf('.') < 0)
       && !(input.isFile() && input.getName().equals(output.getName()))) {
     logger.info(MessageFormat.format("Creating directory {0}.", output.getAbsolutePath()));
     output.mkdir();
   }
   if (input.isFile()) {
     boolean jsonFile = SBFileFilter.hasFileType(input, SBFileFilter.FileType.JSON_FILES);
     boolean matFile = SBFileFilter.hasFileType(input, SBFileFilter.FileType.MAT_FILES);
     if (SBFileFilter.isSBMLFile(input) || matFile || jsonFile) {
       if (output.isDirectory()) {
         String fName = input.getName();
         if (matFile || jsonFile) {
           fName = FileTools.removeFileExtension(fName) + ".xml";
         }
         output = new File(Utils.ensureSlash(output.getAbsolutePath()) + fName);
       }
       polish(bigg, input, output, parameters);
     }
   } else {
     if (!output.isDirectory()) {
       throw new IOException(
           MessageFormat.format("Cannot write to file {0}.", output.getAbsolutePath()));
     }
     for (File file : input.listFiles()) {
       File target = new File(Utils.ensureSlash(output.getAbsolutePath()) + file.getName());
       batchProcess(bigg, file, target, parameters);
     }
   }
 }
Пример #17
0
 private void editSchedule(int row) {
   log.debug("Edit schedule");
   if (sef != null) {
     sef.dispose();
   }
   Schedule sch = sysList.get(row);
   LocationTrackPair ltp = getLocationTrackPair(row);
   if (ltp == null) {
     log.debug("Need location track pair");
     JOptionPane.showMessageDialog(
         null,
         MessageFormat.format(Bundle.getMessage("AssignSchedule"), new Object[] {sch.getName()}),
         MessageFormat.format(
             Bundle.getMessage("CanNotSchedule"), new Object[] {Bundle.getMessage("Edit")}),
         JOptionPane.ERROR_MESSAGE);
     return;
   }
   // use invokeLater so new window appears on top
   SwingUtilities.invokeLater(
       new Runnable() {
         @Override
         public void run() {
           sef = new ScheduleEditFrame(sch, ltp.getTrack());
         }
       });
 }
Пример #18
0
 /**
  * Computes the default Hadoop configuration path.
  *
  * @param environmentVariables the current environment variables
  * @return the detected configuration path, or {@code null} if the configuration path is not found
  * @since 0.6.0
  */
 public static URL getConfigurationPath(Map<String, String> environmentVariables) {
   if (environmentVariables == null) {
     throw new IllegalArgumentException("environmentVariables must not be null"); // $NON-NLS-1$
   }
   File conf = getConfigurationDirectory(environmentVariables);
   if (conf == null) {
     // show warning only the first time
     if (SAW_HADOOP_CONF_MISSING.compareAndSet(false, true)) {
       LOG.warn("Hadoop configuration path is not found");
     }
     return null;
   }
   if (conf.isDirectory() == false) {
     LOG.warn(
         MessageFormat.format(
             "Failed to load default Hadoop configurations ({0} is not a valid installation path)",
             conf));
     return null;
   }
   try {
     return conf.toURI().toURL();
   } catch (MalformedURLException e) {
     LOG.warn(
         MessageFormat.format(
             "Failed to load default Hadoop configurations ({0} is unrecognized to convert URL)",
             conf),
         e);
     return null;
   }
 }
 public String format(String key, String defaultValue, Object... args) {
   Locale locale = CurrentLocale.isSet() ? CurrentLocale.get() : Locale.getDefault();
   Map<String, String> catalog = _catalogs.get(locale);
   String message = catalog.get(key);
   MessageFormat formatter = new MessageFormat(message, locale);
   return formatter.format(args, new StringBuffer(), null).toString();
 }
Пример #20
0
 private static File getImplicitConfigurationDirectory(Map<String, String> envp) {
   if (LOG.isDebugEnabled()) {
     LOG.debug("Detecting default Hadoop configuration dir from Hadoop installation path");
   }
   File command = findHadoopCommand(envp);
   if (command == null) {
     return null;
   }
   if (LOG.isDebugEnabled()) {
     LOG.debug(MessageFormat.format("Hadoop command: {0}", command));
   }
   File conf;
   conf = getHadoopConfigurationDirectoryByRelative(command);
   if (conf != null) {
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           MessageFormat.format(
               "Found implicit Hadoop confdir (from hadoop command path): {0}", conf));
     }
     return conf;
   }
   conf = getHadoopConfigurationDirectoryByCommand(command, envp);
   if (conf != null) {
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           MessageFormat.format(
               "Found implicit Hadoop confdir (from hadoop command execution): {0}", conf));
     }
     return conf;
   }
   return null;
 }
Пример #21
0
  private static String readSectionName(final StringReader in) throws ConfigInvalidException {
    final StringBuilder name = new StringBuilder();
    for (; ; ) {
      int c = in.read();
      if (c < 0) throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);

      if (']' == c) {
        in.reset();
        break;
      }

      if (' ' == c || '\t' == c) {
        for (; ; ) {
          c = in.read();
          if (c < 0) throw new ConfigInvalidException(JGitText.get().unexpectedEndOfConfigFile);

          if ('"' == c) {
            in.reset();
            break;
          }

          if (' ' == c || '\t' == c) continue; // Skipped...
          throw new ConfigInvalidException(
              MessageFormat.format(JGitText.get().badSectionEntry, name));
        }
        break;
      }

      if (Character.isLetterOrDigit((char) c) || '.' == c || '-' == c) name.append((char) c);
      else
        throw new ConfigInvalidException(
            MessageFormat.format(JGitText.get().badSectionEntry, name));
    }
    return name.toString();
  }
Пример #22
0
 @Override
 public void run() {
   boolean outputFailed = false;
   try {
     InputStream in = input;
     OutputStream out = output;
     byte[] buf = new byte[256];
     while (true) {
       int read = in.read(buf);
       if (read == -1) {
         break;
       }
       if (outputFailed == false) {
         try {
           out.write(buf, 0, read);
         } catch (IOException e) {
           outputFailed = true;
           LOG.warn(MessageFormat.format("Failed to redirect stdout of subprocess", e));
         }
       }
     }
   } catch (IOException e) {
     LOG.warn(MessageFormat.format("Failed to redirect stdio of subprocess", e));
   }
 }
Пример #23
0
  @EventHandler
  public void onPlayerMove(PlayerMoveEvent event) {
    final Player player = event.getPlayer();

    if (player.hasPermission("VoidSpawn.bypass")) {
      return;
    }

    final List<String> enabledWorlds =
        Main.getInstance().getConfig().getStringList("worlds.EnabledWorlds");

    if (!enabledWorlds.contains(player.getLocation().getWorld().getName())) {
      return;
    }

    if (player.getLocation().getBlockY()
            <= Main.getInstance()
                .getConfig()
                .getInt(
                    MessageFormat.format(
                        "worlds.WorldYLimits.{0}", player.getLocation().getWorld().getName()))
        && !PlayerMoveListener.inTPProcess.containsKey(player.getName())) {
      PlayerMoveListener.inTPProcess.put(player.getName(), new TeleportationTask(player));
    } else if (player.getLocation().getBlockY()
            > Main.getInstance()
                .getConfig()
                .getInt(
                    MessageFormat.format(
                        "worlds.WorldYLimits.{0}", player.getLocation().getWorld().getName()))
        && PlayerMoveListener.inTPProcess.containsKey(player.getName())) {
      TeleportationTask.end(player);
    }
  }
Пример #24
0
  protected void testFilesExists(
      HashMap<String, IFileStore> destMap,
      IFileStore sourceRoot,
      IFileStore sourceFile,
      int timeTolerance)
      throws CoreException {
    String relPath = EFSUtils.getRelativePath(sourceRoot, sourceFile, null);
    IFileStore destFile = destMap.get(relPath);
    // System.out.println("Comparing " + relPath);

    assertNotNull(MessageFormat.format("File {0} not found on destination", relPath), destFile);
    IFileInfo f1 = sourceFile.fetchInfo(IExtendedFileStore.DETAILED, null);
    IFileInfo f2 = destFile.fetchInfo(IExtendedFileStore.DETAILED, null);
    if (!f1.isDirectory()) {
      long sourceFileTime = f1.getLastModified();
      long destFileTime = f2.getLastModified();
      long timeDiff = destFileTime - sourceFileTime;

      assertTrue(
          MessageFormat.format(
              "File {0} is {1} seconds newer on destination", relPath, (int) timeDiff / 1000),
          -timeTolerance <= timeDiff && timeDiff <= timeTolerance);
      assertEquals(
          MessageFormat.format("File {0} different sizes", relPath),
          f1.getLength(),
          f2.getLength());
    }
  }
  /**
   * Get dburl which content are replaced by parameter value.(note: for mssql, this method result is
   * wrong, so i deprecated this method)
   *
   * @param dbType
   * @param host
   * @param port
   * @param dbName
   * @param dataSource
   * @param paramString TODO
   * @return
   * @deprecated use {@link #getDBUrl(String dbType, String Version, String host, String username,
   *     String password, String port, String dbName, String dataSource, String paramString)}
   */
  @Deprecated
  public String getDBUrl(
      String dbType,
      String host,
      String port,
      String dbName,
      String dataSource,
      String paramString) {
    String propUrlValue = PROP.getProperty(dbType);
    SupportDBUrlType defaultUrlType = supportDBUrlMap.get(dbType);
    // defaultUrlType = defaultUrlType == null ? SupportDBUrlType.ODBCDEFAULTURL : defaultUrlType;
    defaultUrlType = defaultUrlType == null ? SupportDBUrlType.MYSQLDEFAULTURL : defaultUrlType;
    if (propUrlValue == null) {
      return PluginConstant.EMPTY_STRING;
    }

    String argHost = (host == null) ? PluginConstant.EMPTY_STRING : host;
    String argPort = (port == null) ? PluginConstant.EMPTY_STRING : port;
    String argDBName = (dbName == null) ? PluginConstant.EMPTY_STRING : dbName;
    String argDataSource = (dataSource == null) ? PluginConstant.EMPTY_STRING : dataSource;
    Object[] argsUrl = {argHost, argPort, argDBName, argDataSource};
    if (paramString.equals(PluginConstant.EMPTY_STRING)) {
      return MessageFormat.format(propUrlValue, argsUrl);
    } else {
      return MessageFormat.format(propUrlValue, argsUrl)
          + defaultUrlType.getParamSeprator()
          + paramString;
    }
  }
Пример #26
0
  /** @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context) */
  @SuppressWarnings("unchecked")
  @Override
  public boolean execute(Context context) throws Exception {
    Object operaterTime = context.get("operaterTime");

    if (operaterTime == null) {
      context.put("code", CodeConstants.INVALID_PARAM);
      context.put(
          "message",
          MessageFormat.format(
              CodeResourcesUtil.getProperty(CodeConstants.INVALID_PARAM), "operaterTime为空"));
      return PROCESSING_COMPLETE;
    }
    try {
      DateUtils.parse(operaterTime.toString(), "yyyyMMddHHmmss");
    } catch (Exception e) {
      context.put("code", CodeConstants.INVALID_PARAM);
      context.put(
          "message",
          MessageFormat.format(
              CodeResourcesUtil.getProperty(CodeConstants.INVALID_PARAM), "operaterTime格式错误"));
      return PROCESSING_COMPLETE;
    }

    return CONTINUE_PROCESSING;
  }
Пример #27
0
 public void start() {
   super.start();
   steps.clear();
   MessageFormat mf = new MessageFormat(Strings.get("RecordingX"));
   setStatus(mf.format(new Object[] {toString()}));
   lastStepTime = getLastEventTime();
 }
Пример #28
0
 /**
  * Writes the properties file.
  *
  * @param properties
  * @throws IOException
  */
 private void write(Properties properties) throws IOException {
   // Write a temporary copy of the users file
   File realmFileCopy = new File(propertiesFile.getAbsolutePath() + ".tmp");
   FileWriter writer = new FileWriter(realmFileCopy);
   properties.store(
       writer,
       " Gitblit realm file format:\n   username=password,\\#permission,repository1,repository2...\n   @teamname=!username1,!username2,!username3,repository1,repository2...");
   writer.close();
   // If the write is successful, delete the current file and rename
   // the temporary copy to the original filename.
   if (realmFileCopy.exists() && realmFileCopy.length() > 0) {
     if (propertiesFile.exists()) {
       if (!propertiesFile.delete()) {
         throw new IOException(
             MessageFormat.format("Failed to delete {0}!", propertiesFile.getAbsolutePath()));
       }
     }
     if (!realmFileCopy.renameTo(propertiesFile)) {
       throw new IOException(
           MessageFormat.format(
               "Failed to rename {0} to {1}!",
               realmFileCopy.getAbsolutePath(), propertiesFile.getAbsolutePath()));
     }
   } else {
     throw new IOException(
         MessageFormat.format("Failed to save {0}!", realmFileCopy.getAbsolutePath()));
   }
 }
Пример #29
0
  public void run() {
    String ipdest = "";
    try {

      ipdest = system.in.read(messages.getString("ipdest"));
      int count = 0;
      byte[] data = String.valueOf(count).getBytes();

      simulip.net.DatagramSocket d = new simulip.net.DatagramSocket(this);
      simulip.net.DatagramPacket p = new simulip.net.DatagramPacket(data, 5, ipdest, 54);
      while (true) {
        d.send(p);
        d.receive(p);
        system.out.println(
            MessageFormat.format(messages.getString("ackOf"), new String(p.getData())));
        p.setAddress(p.getAddress());
        p.setPort(p.getPort());
        count++;
        data = String.valueOf(count).getBytes();
        p.setData(data);
      }
    } catch (NetworkAddressFormatException nafe) {
      system.out.println(MessageFormat.format(messages.getString("badlyFormedAddress"), ipdest));
    } catch (Exception e) {
      system.out.println(e.getMessage());
      Logger.getLogger("").log(Level.SEVERE, "UdpEchoSend error", e);
    }
  }
 protected KeepAlive configureKeepAlive(final Http http) {
   int timeoutInSeconds = 60;
   int maxConnections = 256;
   if (http != null) {
     try {
       timeoutInSeconds = Integer.parseInt(http.getTimeoutSeconds());
     } catch (NumberFormatException ex) {
       //                String msg = _rb.getString("pewebcontainer.invalidKeepAliveTimeout");
       String msg = "pewebcontainer.invalidKeepAliveTimeout";
       msg =
           MessageFormat.format(msg, http.getTimeoutSeconds(), Integer.toString(timeoutInSeconds));
       LOGGER.log(Level.WARNING, msg, ex);
     }
     try {
       maxConnections = Integer.parseInt(http.getMaxConnections());
     } catch (NumberFormatException ex) {
       //                String msg =
       // _rb.getString("pewebcontainer.invalidKeepAliveMaxConnections");
       String msg = "pewebcontainer.invalidKeepAliveMaxConnections";
       msg = MessageFormat.format(msg, http.getMaxConnections(), Integer.toString(maxConnections));
       LOGGER.log(Level.WARNING, msg, ex);
     }
   }
   final KeepAlive keepAlive = new KeepAlive();
   keepAlive.setIdleTimeoutInSeconds(timeoutInSeconds);
   keepAlive.setMaxRequestsCount(maxConnections);
   return keepAlive;
 }