// FIXME convert to hbird archiver interface and move this to the archiver.
  private static DBObject buildMongoQuery(Map<String, String> aoData) {
    // Get datatables values
    long startTime = Long.parseLong(aoData.get("startTime"));
    long endTime = Long.parseLong(aoData.get("endTime"));
    String search = aoData.get("sSearch");

    // Build mongo query
    // @formatter:off
    DBObject mongoQuery = new BasicDBObject();
    mongoQuery.put(
        "receivedTime", BasicDBObjectBuilder.start("$gte", startTime).add("$lte", endTime).get());

    if (search != null && (!search.isEmpty())) {
      LOG.trace("Adding search query " + search);
      Pattern match = Pattern.compile(search, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
      // Note, normally you would pass the Pattern object to the Java Mongo driver but when using
      // distributed routing
      // over JMS you can only send objectified primitives. This means we have to create the search
      // string ourselves.
      DBObject matchString = new BasicDBObject("$regex", match.toString()).append("$options", "im");
      mongoQuery.put("name", matchString);
    }

    // @formatter:on

    return mongoQuery;
  }
  public void map(
      Object unused,
      Text line,
      OutputCollector<LongWritable, PostingSongArrayWritable> output,
      Reporter reporter)
      throws IOException {

    StringTokenizer str = new StringTokenizer(line.toString(), " |\t");

    if (nRatings == 0) {
      userId = Long.parseLong(str.nextToken());
      nRatings = Integer.parseInt(str.nextToken());
      songsRatings.clear();
      totalRate = 0;
    } else {
      long songId = Long.parseLong(str.nextToken());
      int rate = Integer.parseInt(str.nextToken());
      songsRatings.add(new PostingSong(songId, rate));
      totalRate += rate;
      nRatings--;
      if (nRatings == 0) {
        nRatings = songsRatings.size();
        songsValue.setArray(songsRatings);
        output.collect(userIdKey, songsValue);
        nRatings = 0;
      }
    }
  }
예제 #3
0
파일: CPUStat.java 프로젝트: camry-wu/tools
  /**
   * thread cpu statistic.
   *
   * @param args
   */
  public void statThread(final String[] args) {
    long pid = 1;
    long tid = 1;
    long period = 2000;
    String outputFile = null;

    if (args.length > 0) {
      pid = Long.parseLong(args[0]);
    }
    if (args.length > 1) {
      tid = Long.parseLong(args[1]);
    }
    if (args.length > 2) {
      period = Long.parseLong(args[2]);
    }
    if (args.length > 3) {
      outputFile = args[3];
    }

    ThreadStatTask task = new ThreadStatTask(pid, tid, outputFile);

    Runtime.getRuntime().addShutdownHook(new ShutdownHook(task));

    Timer timer = new Timer();
    timer.schedule(task, 100, period);
  }
예제 #4
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Expires", "-1");
    PrintWriter out = response.getWriter();
    try {
      Long langId = Long.parseLong(request.getParameter("langId"));
      Long dataId = Long.parseLong(request.getParameter("dataId"));
      long type = dataId; // type of value (like 4096)
      if ((type & 0xC000) != 0xC000) {
        dataId = (type & 0xFFF); // remove type to get an index 4096&0xFFF -> 0
      } else {
        dataId = (type & 0xFFFF);
      }

      DataDao dataDao = DbImplDecider.use(DaoType.MYSQL).getDao(DataDao.class);
      Data translate = dataDao.getById(dataId, langId);
      out.print("<html>");
      out.print("<message>");
      if (translate.getId() != null) {
        out.print(translate.getUnicodeLabel());
      } else {
        out.print("Translation does not exist");
      }
      out.println("</message>");
      out.print("</html>");
    } catch (Exception ex) {
      out.print("<message>");
      out.print(
          "Error occur during execution the query. \n"
              + "Perhaps translation for this data type does not exist .");
      out.println("</message>");
    }
  }
예제 #5
0
 private void setComparableValue(String s) throws Exception {
   if (NULL.equalsIgnoreCase(s) && !IS_NULL.equalsIgnoreCase(this.type))
     throw new BadComparisonException(
         "Use condition type=\"isNull\" for comparisons to null values");
   try {
     if (propertyClass == null || propertyClass.length() < 1) {
       targetValue = s;
     } else {
       Class c = Class.forName(propertyClass);
       if ("today".equalsIgnoreCase(s)
           && (c.equals(java.sql.Date.class)
               || c.equals(java.sql.Timestamp.class)
               || c.equals(java.sql.Date.class))) targetValue = s;
       else if (c.equals(java.sql.Date.class)) targetValue = javaUtilDateFormatter.parse(s);
       else if (c.equals(java.sql.Timestamp.class))
         targetValue = new java.sql.Date(Long.parseLong(s));
       else if (c.equals(java.util.Date.class)) targetValue = java.sql.Timestamp.valueOf(s);
       else if (c.equals(Boolean.class)) targetValue = Boolean.valueOf(s);
       else if (c.equals(Double.class)) targetValue = Double.parseDouble(s);
       else if (c.equals(Float.class)) targetValue = Float.parseFloat(s);
       else if (c.equals(Long.class)) targetValue = Long.parseLong(s);
       else if (c.equals(Integer.class)) targetValue = Integer.parseInt(s);
       else targetValue = s;
     }
   } catch (Exception e) {
     logger.debug(
         "Error setting condition target value to " + s + " which is a " + propertyClass, e);
     throw e;
   }
 }
  @Bean
  public RedeliveryPolicy defaultRedeliveryPolicy() {
    final RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
    redeliveryPolicy.setInitialRedeliveryDelay(
        Long.parseLong(
            this.environment.getRequiredProperty(
                PROPERTY_NAME_JMS_DEFAULT_INITIAL_REDELIVERY_DELAY)));
    redeliveryPolicy.setMaximumRedeliveries(
        Integer.parseInt(
            this.environment.getRequiredProperty(PROPERTY_NAME_JMS_DEFAULT_MAXIMUM_REDELIVERIES)));
    redeliveryPolicy.setMaximumRedeliveryDelay(
        Long.parseLong(
            this.environment.getRequiredProperty(
                PROPERTY_NAME_JMS_DEFAULT_MAXIMUM_REDELIVERY_DELAY)));
    redeliveryPolicy.setRedeliveryDelay(
        Long.parseLong(
            this.environment.getRequiredProperty(PROPERTY_NAME_JMS_DEFAULT_REDELIVERY_DELAY)));
    redeliveryPolicy.setBackOffMultiplier(
        Double.parseDouble(
            this.environment.getRequiredProperty(PROPERTY_NAME_JMS_DEFAULT_BACK_OFF_MULTIPLIER)));
    redeliveryPolicy.setUseExponentialBackOff(
        Boolean.parseBoolean(
            this.environment.getRequiredProperty(
                PROPERTY_NAME_JMS_DEFAULT_USE_EXPONENTIAL_BACK_OFF)));

    return redeliveryPolicy;
  }
예제 #7
0
  // This only exists to support demarshalling of maps using Jackson. The Jackson payload doesn't
  // contain our
  // EMBEDDED_JSON or any type information, so we have to convert the key (which is always a String)
  // to it's actual
  // type. We only need to support primitive wrapper types and enums as key types. Other types
  // require a custom
  // Key(De)Serializer in Jackson anyway which would be unknown to Errai.
  private Object convertKey(final String toType, final String key, final MarshallingSession ctx) {
    if (key == null) return null;

    Marshaller<?> keyMarshaller = ctx.getMarshallerInstance(toType);
    if (toType.equals(Integer.class.getName())) {
      return Integer.parseInt(key);
    } else if (toType.equals(Long.class.getName())) {
      return Long.parseLong(key);
    } else if (toType.equals(Float.class.getName())) {
      return Float.parseFloat(key);
    } else if (toType.equals(Double.class.getName())) {
      return Double.parseDouble(key);
    } else if (toType.equals(Short.class.getName())) {
      return Short.parseShort(key);
    } else if (toType.equals(Boolean.class.getName())) {
      return Boolean.parseBoolean(key);
    } else if (toType.equals(Date.class.getName())) {
      return new Date(Long.parseLong(key));
    } else if (toType.equals(Character.class.getName())) {
      return new Character(key.charAt(0));
    } else if (toType.equals(String.class.getName())) {
      return key;
    } else if (keyMarshaller != null) {
      EJArray eja = ParserFactory.get().parse("[\"" + key + "\"]").isArray();
      if (eja != null && eja.size() == 1) {
        return keyMarshaller.demarshall(eja.get(0), ctx);
      }
    }
    return key;
  }
예제 #8
0
 /** * Used with the new JRuby/Mongrel/Rest interface */
 public static StreamElement fromREST(
     DataField[] outputFormat, String[] fieldNames, String[] fieldValues, String timestamp) {
   Serializable[] values = new Serializable[outputFormat.length];
   for (int i = 0; i < fieldNames.length; i++) {
     switch (findIndexInDataField(outputFormat, (String) fieldNames[i])) {
       case DataTypes.DOUBLE:
         values[i] = Double.parseDouble(fieldValues[i]);
         break;
       case DataTypes.BIGINT:
         //        case DataTypes.TIME :
         values[i] = Long.parseLong((String) fieldValues[i]);
         break;
       case DataTypes.TINYINT:
         values[i] = Byte.parseByte((String) fieldValues[i]);
         break;
       case DataTypes.SMALLINT:
       case DataTypes.INTEGER:
         values[i] = Integer.parseInt(fieldValues[i]);
         break;
       case DataTypes.CHAR:
       case DataTypes.VARCHAR:
         values[i] = new String(Base64.decodeBase64(fieldValues[i].getBytes()));
         break;
       case DataTypes.BINARY:
         values[i] = (byte[]) Base64.decodeBase64(fieldValues[i].getBytes());
         break;
       case -1:
       default:
         logger.error(
             "The field name doesn't exit in the output structure : FieldName : "
                 + (String) fieldNames[i]);
     }
   }
   return new StreamElement(outputFormat, values, Long.parseLong(timestamp));
 }
예제 #9
0
    @Override
    protected void onSuccess(TokenInfo tokenInfo) {
      super.onSuccess(tokenInfo);

      if (tokenInfo != null
          && account.getUser().getIdstr().equalsIgnoreCase(AppContext.getUser().getIdstr())) {
        long validSecond =
            Long.parseLong(tokenInfo.getCreate_at()) + Long.parseLong(tokenInfo.getExpire_in());
        if (System.currentTimeMillis() > validSecond * 1000) {
          new AlertDialogWrapper.Builder(MainActivity.this)
              .setTitle(R.string.remind)
              .setMessage(R.string.account_expired)
              .setNegativeButton(R.string.no, null)
              .setPositiveButton(
                  R.string.yes,
                  new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      LoginFragment.launch(
                          MainActivity.this, account.getAccount(), account.getPassword(), 2000);
                    }
                  })
              .show();
        }
      }
    }
  public void produceCpuEvents(NodePojo node)
      throws ExecutionException, InterruptedException, IOException {
    ChartPrettyRandomGenerator genUser = cpuUserGenerator.get(node.getIpAddress());
    if (genUser == null) {
      genUser = new ChartPrettyRandomGenerator(true, 80, 20);
      cpuUserGenerator.put(node.getIpAddress(), genUser);
    }
    ChartPrettyRandomGenerator genSys = cpuSysGenerator.get(node.getIpAddress());
    if (genSys == null) {
      genSys = new ChartPrettyRandomGenerator(true, 80, 20);
      cpuSysGenerator.put(node.getIpAddress(), genSys);
    }
    List<SamplePojo> samples = new ArrayList<SamplePojo>();

    long userCpu = Long.parseLong(genUser.getNextValue());
    long systemCpu = Long.parseLong(genSys.getNextValue());
    long idleCpu;

    if (userCpu + systemCpu > 100) {
      systemCpu = 100 - userCpu;
      idleCpu = 0;
    } else {
      idleCpu = 100 - (userCpu + systemCpu);
    }

    samples.add(new SamplePojo("User", Long.toString(userCpu)));
    samples.add(new SamplePojo("Sys", Long.toString(systemCpu)));
    samples.add(new SamplePojo("Idle", Long.toString(idleCpu)));

    listener.publishEvent(
        new EventPojo(node.getIpAddress(), symTime, TopLevelConst.CPU_LINE_CHART_DATA, samples));
  }
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String[] str;
    str = in.readLine().split(" ");
    int N = Integer.parseInt(str[0]);

    long[] A = new long[N];
    long[] B = new long[N];
    long[] C = new long[N];
    long[] D = new long[N];
    for (int i = 0; i < N; i++) {
      str = in.readLine().split(" ");
      A[i] = Long.parseLong(str[0]);
      B[i] = Long.parseLong(str[1]);
      C[i] = Long.parseLong(str[2]);
      D[i] = Long.parseLong(str[3]);
    }

    long[] CD = new long[N * N];
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        CD[i * N + j] = C[i] + D[j];
      }
    }
    Arrays.sort(CD);
    long count = 0;
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < N; j++) {
        long sum = A[i] + B[j];
        count += upperbound(CD, -sum) - lowerbound(CD, -sum) + 1;
      }
    }
    System.out.println(count);
  }
예제 #12
0
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    Long viewer = Long.parseLong(request.getParameter("viewer"));
    Long owner = Long.parseLong(request.getParameter("owner"));

    Activity activity = new Activity();
    Person utilPerson = new Person();
    Utils util = new Utils();
    String result = utilPerson.addFriend(viewer, owner, "tutor");

    if (result.equalsIgnoreCase("Done!")) {
      out.println("ok");
      activity.createActivity(
          util.getPersonName(viewer),
          ActivityVerb.FOLLOW.toString(),
          util.getPersonName(owner),
          "public");
    } else {
      out.println("not ok");
    }
  }
예제 #13
0
 public static long communityStringToLong(String str) {
   String[] parts = str.split(":");
   long high = Long.parseLong(parts[0]);
   long low = Long.parseLong(parts[1]);
   long result = low + (high << 16);
   return result;
 }
 private void parseExpiration(XMLExtendedStreamReader reader, ModelNode expiration)
     throws XMLStreamException {
   for (int i = 0; i < reader.getAttributeCount(); i++) {
     String value = reader.getAttributeValue(i);
     Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
     switch (attribute) {
       case MAX_IDLE:
         {
           expiration.get(ModelKeys.MAX_IDLE).set(Long.parseLong(value));
           break;
         }
       case LIFESPAN:
         {
           expiration.get(ModelKeys.LIFESPAN).set(Long.parseLong(value));
           break;
         }
       case INTERVAL:
         {
           expiration.get(ModelKeys.INTERVAL).set(Long.parseLong(value));
           break;
         }
       default:
         {
           throw ParseUtils.unexpectedAttribute(reader, i);
         }
     }
   }
   ParseUtils.requireNoContent(reader);
 }
 private void parseStateTransfer(XMLExtendedStreamReader reader, ModelNode stateTransfer)
     throws XMLStreamException {
   for (int i = 0; i < reader.getAttributeCount(); i++) {
     String value = reader.getAttributeValue(i);
     Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
     switch (attribute) {
       case ENABLED:
         {
           stateTransfer.get(ModelKeys.ENABLED).set(Boolean.parseBoolean(value));
           break;
         }
       case TIMEOUT:
         {
           stateTransfer.get(ModelKeys.TIMEOUT).set(Long.parseLong(value));
           break;
         }
       case FLUSH_TIMEOUT:
         {
           stateTransfer.get(ModelKeys.FLUSH_TIMEOUT).set(Long.parseLong(value));
           break;
         }
       default:
         {
           throw ParseUtils.unexpectedAttribute(reader, i);
         }
     }
   }
   ParseUtils.requireNoContent(reader);
 }
 private void parseClusteredCacheAttribute(
     XMLExtendedStreamReader reader, int index, Attribute attribute, String value, ModelNode cache)
     throws XMLStreamException {
   switch (attribute) {
     case MODE:
       {
         cache.get(ModelKeys.MODE).set(value);
         break;
       }
     case QUEUE_SIZE:
       {
         cache.get(ModelKeys.QUEUE_SIZE).set(Integer.parseInt(value));
         break;
       }
     case QUEUE_FLUSH_INTERVAL:
       {
         cache.get(ModelKeys.QUEUE_FLUSH_INTERVAL).set(Long.parseLong(value));
         break;
       }
     case REMOTE_TIMEOUT:
       {
         cache.get(ModelKeys.REMOTE_TIMEOUT).set(Long.parseLong(value));
         break;
       }
     default:
       {
         this.parseCacheAttribute(reader, index, attribute, value, cache);
       }
   }
 }
예제 #17
0
  public static void main(String[] args) throws Exception {
    FastScanner sc = new FastScanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    int n = sc.nextInt();
    int u = 1;
    while (u <= n) {
      String s = sc.next();
      TreeSet<Long> set = new TreeSet<Long>();
      set.add(Long.parseLong(s));
      for (int i = 0; i < s.length(); i++) {
        for (int j = i + 1; j < s.length(); j++) {
          String next =
              s.substring(0, i)
                  + s.charAt(j)
                  + s.substring(i + 1, j)
                  + s.charAt(i)
                  + s.substring(j + 1);
          if (next.charAt(0) != '0') {
            set.add(Long.parseLong(next));
          }
        }
      }
      min = set.first();
      max = set.last();

      out.println("Case #" + u + ": " + min + " " + max);
      u++;
    }

    out.close();
  }
예제 #18
0
  public static Network initParamFromFile(Network n, String fileName) throws Exception {
    n = LtWeightInitiator.initParam(n, 0.0);

    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String tmpLine = null;
    while (true) {
      tmpLine = br.readLine();
      if (tmpLine == null) break;
      String[] tmp = tmpLine.split("\t");
      Long from = Long.parseLong(tmp[0]);
      Long to = Long.parseLong(tmp[1]);
      double value = Double.parseDouble(tmp[2]);
      Long rid = n.findEdge(from, to);
      if (rid == null) continue;
      Relation r = n.getRelation(rid);
      r.setLtWeight(value);
    }
    br.close();

    /*Collection<LinkUnit> linkWeights = IOUtility.readLinkValue( fileName );
    for( LinkUnit linkunit : linkWeights ){
    	Integer from = linkunit.getFrom();
    	Integer to = linkunit.getTo();
    	double value = linkunit.getValue();
    	Integer rid = n.findEdge( from , to );
    	Relation r = n.getRelation( rid );
    	r.setLtWeight( value );
    }
    */
    return n;
  }
예제 #19
0
  @Check("isAdmin")
  public static void edit(String idSession) {
    Session sessions = Session.getSessionById(Long.parseLong(idSession));
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    String dateDebut = sdf.format(sessions.dateDepart);
    String dateFin = sdf.format(sessions.dateFin);

    List<ProduitType> listProduitTypes = Arrays.asList(ProduitType.values());

    Circuit tempCircuit = sessions.circuit;

    sessions.circuit = null;
    sessions.save();

    sessions = Session.getSessionById(Long.parseLong(idSession));
    sessions.circuit = tempCircuit;

    boolean isAvailableCircuit =
        Circuit.isAvailableCircuitByAgence(sessions.dateDepart, sessions.dateFin, sessions.agence);

    Agence agence = sessions.agence;
    render(
        "Sessions/add.html",
        sessions,
        dateDebut,
        dateFin,
        isAvailableCircuit,
        listProduitTypes,
        agence);
  }
예제 #20
0
 // 审核
 public String auditTechReport() {
   String id = ((String[]) formMap.get("id"))[0] + "";
   String workflowId = ((String[]) formMap.get("workflowId"))[0] + ""; // 存放workflowid
   String ifBackFlag = ((String[]) formMap.get("ifBackFlag"))[0] + "";
   String checkContent = ((String[]) formMap.get("checkContent"))[0] + "";
   if (ifBackFlag.equals("1")) {
     TechReptDef instance = techReptDefService.get(Long.parseLong(id));
     // 更新审核人
     List<ReptTechDtl> reptTechDtls = instance.getReptTechDtl();
     for (int i = 0; i < reptTechDtls.size(); i++) {
       ReptTechDtl rtd = reptTechDtls.get(i);
       rtd.setGovernor(getCurUser().getName());
     }
     techReptDefService.save(instance);
     if (checkContent == null) {
       checkContent = "批准审核";
     }
     workFlowService.endTaskInstance(
         Long.parseLong(workflowId), getCurUser().getName(), checkContent);
   } else {
     if (checkContent == null) {
       checkContent = "驳回审核";
     }
     workFlowService.endTaskInstance(Long.parseLong(workflowId), "驳回", getCurUser(), checkContent);
   }
   return "backToTop";
 }
예제 #21
0
 public static void loadProp() {
   FileInputStream attestationPropertyFile = null;
   try {
     String configPath = "/etc/oat-appraiser/";
     attestationPropertyFile = new FileInputStream(configPath + PROPERTIES_NAME);
     attestationProperties.load(attestationPropertyFile);
     timeout = Long.parseLong(attestationProperties.getProperty("default_attest_timeout"));
     checkAttestInterval =
         Long.parseLong(attestationProperties.getProperty("check_attest_interval", "1000"));
     portalAddress = attestationProperties.getProperty("portal_address");
     defaultExpirationTime =
         Long.parseLong(attestationProperties.getProperty("default_expiration_time", "7"));
     if (portalAddress == null) {
       try {
         portalAddress = java.net.InetAddress.getLocalHost().getHostName();
       } catch (java.net.UnknownHostException e) {
         portalAddress = "localhost";
       }
     }
     attestationPropertyFile.close();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (attestationPropertyFile != null) attestationPropertyFile.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
예제 #22
0
        @Override
        public void onClick(DialogInterface dialog, int which) {
          switch (which) {
            case CONTEXT_MENU_MARK:
              DeckTask.launchDeckTask(
                  DeckTask.TASK_TYPE_MARK_CARD,
                  mUpdateCardHandler,
                  new DeckTask.TaskData(
                      mCol.getSched(),
                      mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id"))),
                      0));
              return;

            case CONTEXT_MENU_SUSPEND:
              DeckTask.launchDeckTask(
                  DeckTask.TASK_TYPE_DISMISS_NOTE,
                  mSuspendCardHandler,
                  new DeckTask.TaskData(
                      mCol.getSched(),
                      mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id"))),
                      1));
              return;

            case CONTEXT_MENU_DELETE:
              Resources res = getResources();
              StyledDialog.Builder builder = new StyledDialog.Builder(CardBrowser.this);
              builder.setTitle(res.getString(R.string.delete_card_title));
              builder.setIcon(android.R.drawable.ic_dialog_alert);
              builder.setMessage(
                  res.getString(
                      R.string.delete_card_message, mCards.get(mPositionInCardsList).get("sfld")));
              builder.setPositiveButton(
                  res.getString(R.string.yes),
                  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      Card card =
                          mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id")));
                      deleteNote(card);
                      DeckTask.launchDeckTask(
                          DeckTask.TASK_TYPE_DISMISS_NOTE,
                          mDeleteNoteHandler,
                          new DeckTask.TaskData(mCol.getSched(), card, 3));
                    }
                  });
              builder.setNegativeButton(res.getString(R.string.no), null);
              builder.create().show();
              return;

            case CONTEXT_MENU_DETAILS:
              Card tempCard =
                  mCol.getCard(Long.parseLong(mCards.get(mPositionInCardsList).get("id")));
              Themes.htmlOkDialog(
                      CardBrowser.this,
                      getResources().getString(R.string.card_browser_card_details),
                      tempCard.getCardDetails(CardBrowser.this))
                  .show();
              return;
          }
        }
예제 #23
0
  /** Loads stats from /proc/[pid]/stat and /proc/[pid]/statm files */
  public static ProcessStatus getProcStats(String pid) {

    // using a space as the delimeter.
    String data;

    // get the /proc/[pid]/stat as a string and them split into string array
    // using a space as the delimeter.
    try {
      data = FileReadUtil.readFirstLine(String.format(STAT_FILE, pid));
      String[] procStatData = data.split(SPACE_VALUE);
      long startTimeSecs =
          UnsignedLong.valueOf(procStatData[STAT_STARTTIME])
              .dividedBy(UnsignedLong.fromLongBits(HZ))
              .longValue();
      long currTimeSecs = new Date().getTime() / 1000;
      long upTimeSecs = currTimeSecs - (getBootTime() + startTimeSecs);
      return new ProcessStatus(
          upTimeSecs,
          Long.parseLong(procStatData[STAT_NUM_THREADS]),
          startTimeSecs,
          Integer.parseInt(procStatData[STAT_PID]),
          Long.parseLong(procStatData[STAT_RSS]) * getPageSize(),
          Long.parseLong(procStatData[STAT_VSIZE]));
    } catch (Exception e) {
      _log.error("Error occurred while getting service stats from /stats file: {}", e);
    }

    return null;
  }
예제 #24
0
 public static int compareVersion(String curVer, String serVer) {
   if (curVer.equals(serVer) || serVer == null) {
     return 0;
   }
   String[] version1Array = curVer.split("\\.");
   String[] version2Array = serVer.split("\\.");
   int index = 0;
   int minLen = Math.min(version1Array.length, version2Array.length);
   long diff = 0;
   while (index < minLen
       && (diff =
               Long.parseLong(getStringNum(version1Array[index]))
                   - Long.parseLong(getStringNum(version2Array[index])))
           == 0) {
     index++;
   }
   if (diff == 0) {
     for (int i = index; i < version1Array.length; i++) {
       if (i >= 4 || Integer.parseInt(version1Array[i]) > 0) {
         // 没有新版本
         return 1;
       }
     }
     for (int i = index; i < version2Array.length; i++) {
       if (Integer.parseInt(version2Array[i]) > 0) {
         // 有新版本更新
         return -1;
       }
     }
     return 0;
   } else {
     return diff > 0 ? 1 : -1;
   }
 }
 @Bean
 public RedeliveryPolicy osgpResponsesRedeliveryPolicy() {
   final RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
   redeliveryPolicy.setInitialRedeliveryDelay(
       Long.parseLong(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_INITIAL_REDELIVERY_DELAY)));
   redeliveryPolicy.setMaximumRedeliveries(
       Integer.parseInt(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_MAXIMUM_REDELIVERIES)));
   redeliveryPolicy.setMaximumRedeliveryDelay(
       Long.parseLong(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_MAXIMUM_REDELIVERY_DELAY)));
   redeliveryPolicy.setRedeliveryDelay(
       Long.parseLong(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_REDELIVERY_DELAY)));
   redeliveryPolicy.setDestination(this.dlmsRequestsQueue());
   redeliveryPolicy.setBackOffMultiplier(
       Double.parseDouble(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_BACK_OFF_MULTIPLIER)));
   redeliveryPolicy.setUseExponentialBackOff(
       Boolean.parseBoolean(
           this.environment.getRequiredProperty(
               PROPERTY_NAME_JMS_OSGP_RESPONSES_USE_EXPONENTIAL_BACK_OFF)));
   return redeliveryPolicy;
 }
  @Override
  public void connect(MessageContext messageContext) throws ConnectException {
    if (log.isDebugEnabled()) {
      log.info("executing twitter get user time line");
    }

    try {

      String screenName =
          (TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME) != null
                  && !TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME).isEmpty())
              ? TwitterUtils.lookupTemplateParamater(messageContext, SCREEN_NAME)
              : null;

      String userID =
          (TwitterUtils.lookupTemplateParamater(messageContext, USER_ID) != null
                  && !TwitterUtils.lookupTemplateParamater(messageContext, USER_ID).isEmpty())
              ? TwitterUtils.lookupTemplateParamater(messageContext, USER_ID)
              : null;

      String count =
          (TwitterUtils.lookupTemplateParamater(messageContext, COUNT) != null
                  && !TwitterUtils.lookupTemplateParamater(messageContext, COUNT).isEmpty())
              ? TwitterUtils.lookupTemplateParamater(messageContext, COUNT)
              : null;

      Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();

      List<User> results = null;

      if (screenName != null && !screenName.isEmpty()) {
        if (count != null && !count.isEmpty()) {
          results = twitter.getFollowersList(screenName, Long.parseLong(count));
        } else {
          results = twitter.getFollowersList(screenName, -1);
        }
      } else if (userID != null && !userID.isEmpty()) {
        if (count != null && !count.isEmpty()) {
          results = twitter.getFollowersList(Long.parseLong(userID), Long.parseLong(count));
        } else {
          results = twitter.getFollowersList(Long.parseLong(userID), -1);
        }
      }

      if (log.isDebugEnabled()) {
        log.error("Retrived results : " + results.toString());
      }

      OMElement element = this.performSearchMessages(results);

      super.preparePayload(messageContext, element);

    } catch (TwitterException te) {
      log.error("Failed to search twitter : " + te.getMessage(), te);
      TwitterUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
      log.error("Failed to search generic: " + te.getMessage(), te);
      TwitterUtils.storeErrorResponseStatus(messageContext, te);
    }
  }
 private void botaoInserirActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_botaoInserirActionPerformed
   try {
     String[] opcoes = {"sim", "não"};
     String rg = JOptionPane.showInputDialog("Digite seu RG");
     controllerCliente = new ClienteControllerUI();
     if (controllerCliente.clienteExiste(Long.parseLong(rg))) {
       int op =
           JOptionPane.showOptionDialog(
               this,
               "Deseja alugar este livro?",
               "Cliente encontrado!",
               JOptionPane.YES_NO_OPTION,
               JOptionPane.QUESTION_MESSAGE,
               null,
               opcoes,
               opcoes[0]);
       if (op == 0) {
         JOptionPane.showMessageDialog(this, "Processando Dados...");
         controller.salvarAluguel(Long.parseLong(rg));
       } else {
         JOptionPane.showMessageDialog(this, "Livro não pode ser alugado!");
       }
     } else {
       JOptionPane.showMessageDialog(this, "Cliente não encontrado!");
     }
   } catch (Exception e) {
     JOptionPane.showMessageDialog(this, "Campo inválido!");
   }
 } // GEN-LAST:event_botaoInserirActionPerformed
 public void asignarTramite() {
   try {
     long lonTraId =
         Long.parseLong(
             FacesContext.getCurrentInstance()
                 .getExternalContext()
                 .getRequestParameterMap()
                 .get("idTramite"));
     String[] strIds = strRolUsuarioDepartamento.split("-");
     SeguimientoEntidad objAux =
         new SeguimientoEntidad(
             new TramiteEntidad(lonTraId),
             new TrabajoEntidad(
                 new RolUsuarioEntidad(
                     new UsuarioEntidad(Long.parseLong(strIds[1])),
                     new RolEntidad(Long.parseLong(strIds[0]))),
                 new DepartamentoEntidad(Long.parseLong(strIds[2]))),
             null,
             new Timestamp(datPlazo.getTime()));
     if (SeguimientoModelo.insertarSeguimiento(objAux) > 0) {
       if (TramiteModelo.actualizarTramiteAsignacio(new TramiteEntidad(lonTraId)) > 0) {
         Util.addSuccessMessage("Se asignó correctamente el seguimiento del trámite");
         RequestContext.getCurrentInstance().execute("{PF('diaAsignacionTramite').hide()}");
         RequestContext.getCurrentInstance().update("frmAsignacionTramite");
         cargarTramite();
       } else {
         Util.addErrorMessage("No se pudo asignar el seguimiento del trámite");
       }
     }
   } catch (Exception e) {
     Util.addErrorMessage(e.getMessage());
   }
 }
예제 #29
0
  public void transferMoney() throws InsufficientFundsException, NonExistingBankAccountException {
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter origin account number: ");
    long originAccountNumber = Long.parseLong(scanner.nextLine());
    System.out.println("Enter destination account number: ");
    long destinationAccountNumber = Long.parseLong(scanner.nextLine());
    System.out.println("Enter amount of money you want to transfer: ");
    double money = Double.parseDouble(scanner.nextLine());

    scanner.close();

    if (bank.get(originAccountNumber) == null || bank.get(destinationAccountNumber) == null) {
      throw new NonExistingBankAccountException("Bank account doesn't exist!");
    }
    bank.get(originAccountNumber).transfer(bank.get(destinationAccountNumber), money);
    bank.get(originAccountNumber)
        .getHistory()
        .add(
            String.format(
                "Transfered %d to bank account with number %d", money, destinationAccountNumber));
    bank.get(destinationAccountNumber)
        .getHistory()
        .add(
            String.format(
                "Received %d from bank account with number %d", money, originAccountNumber));
  }
예제 #30
0
  public NagiosRange(String s) {
    Pattern pattern = Pattern.compile("([@~:]?)(-?\\d*)(:?)(-?\\d*)");
    Matcher matcher = pattern.matcher(s);
    if (!matcher.matches()) throw new IllegalArgumentException();
    String prefix = matcher.group(1);
    String first = matcher.group(2);
    String colon = matcher.group(3);
    String second = matcher.group(4);

    negate = "@".equals(prefix);

    if ("~".equals(prefix)) {
      min = Long.MIN_VALUE;
      max = Long.parseLong(second);
    } else {
      if (":".equals(colon)) {
        if (second.length() > 0) {
          min = Long.parseLong(first);
          max = Long.parseLong(second);
        } else {
          min = Long.parseLong(first);
          max = Long.MAX_VALUE;
        }
      } else {
        min = 0;
        max = Long.parseLong(first);
      }
    }
  }