示例#1
1
 private String getDate(String timeStampStr, String format) {
   DateFormat formatter = new SimpleDateFormat(format);
   long timeStamp = Long.parseLong(timeStampStr);
   Calendar calendar = Calendar.getInstance();
   calendar.setTimeInMillis(timeStamp);
   return formatter.format(calendar.getTime());
 }
示例#2
0
 /**
  * Create a default filename given the current date selection. If custom dates are selected, use
  * those dates; otherwise, use year and week numbers.
  *
  * @return The default filename.
  */
 private String getDefaultFilename() {
   if (yearCB.getSelectedIndex() == 0 || weekCB.getSelectedIndex() == 0)
     return "timesheet-"
         + dateFormat.format(fromDate.getDate()).replaceAll("/", "")
         + "-"
         + dateFormat.format(toDate.getDate()).replaceAll("/", "")
         + ".txt";
   return "timesheet-" + yearCB.getSelectedItem() + "wk" + weekCB.getSelectedItem() + ".txt";
 }
示例#3
0
  /** Write [DATE] Buy [SYMBOL] [NUMBER]sh @[PRICE] = [VALUE] --> [NUMBER]sh held * */
  public void orderBought(
      TradeOrder order, Date date, StockPosition position, TradingAccount account) {
    double profitOrLoss =
        (order.shares * (order.getExecutedPrice() - position.getCostBasis())
            - account.getTradeFees(order.shares));

    double percent = profitOrLoss / (position.getCostBasis() * order.shares);

    this.writer.println(
        DATE_FORMAT.format(date)
            + " "
            + (position.getShares() != 0 ? "Buy " : "Cover ")
            + order.symbol
            + " "
            + order.shares
            + "sh "
            + "@"
            + DOLLAR_FORMAT.format(order.getExecutedPrice())
            + " = "
            + DOLLAR_FORMAT.format(order.getExecutedValue())
            + " --> "
            + position.getShares()
            + "sh "
            + (position.getShares() <= 0
                ? "left, "
                    + DOLLAR_FORMAT.format(profitOrLoss)
                    + (profitOrLoss > 0
                        ? " (" + PERCENT_FORMAT.format(percent) + " profit)"
                        : profitOrLoss < 0
                            ? " (" + PERCENT_FORMAT.format(percent) + "loss)"
                            : " (even)")
                : "long"));

    this.lastTraceDate = date;
  }
    private Object getValueWithoutWebEditorsFormat(int row, int column) {
      Object r = original.getValueAt(row, column);

      if (r instanceof Boolean) {
        if (((Boolean) r).booleanValue()) return XavaResources.getString(locale, "yes");
        return XavaResources.getString(locale, "no");
      }
      if (withValidValues) {
        MetaProperty p = getMetaProperty(column);
        if (p.hasValidValues()) {
          return p.getValidValueLabel(locale, original.getValueAt(row, column));
        }
      }

      if (r instanceof java.util.Date) {
        MetaProperty p =
            getMetaProperty(column); // In order to use the type declared by the developer
        // and not the one returned by JDBC or the JPA engine
        if (java.sql.Time.class.isAssignableFrom(p.getType())) {
          return DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(r);
        }
        if (java.sql.Timestamp.class.isAssignableFrom(p.getType())) {
          DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
          return dateFormat.format(r);
        }
        return DateFormat.getDateInstance(DateFormat.SHORT, locale).format(r);
      }

      if (r instanceof BigDecimal) {
        return formatBigDecimal(r, locale);
      }

      return r;
    }
  @Override
  public synchronized String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(dateFormat.format(new Date(record.getMillis())));
    sb.append(' ');
    sb.append(record.getLevel().getLocalizedName());
    sb.append(": ");
    sb.append(formatMessage(record));
    sb.append(LINE_SEPARATOR);

    if (record.getThrown() != null) {
      try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.toString());
      } catch (Exception e) {
        // ignore
      }
    }

    return sb.toString();
  }
示例#6
0
 /** Write initial cash balance. * */
 public void initialized(Date date, TradingAccount account) {
   writer.println(
       DATE_FORMAT.format(date)
           + ": "
           + "cash="
           + DOLLAR_FORMAT.format(account.getCurrentCashBalance()));
   this.lastTraceDate = date;
 }
示例#7
0
  /** Typical main method ("main program") declaration */
  public static void main(String[] av) {

    Locale l1 = new Locale("en", "US"), l2 = new Locale("es", "ES");

    // Create a Date object for May 5, 1986
    Calendar c = Calendar.getInstance();
    c.set(1986, 04, 05); // May 5, 1986
    Date d1 = c.getTime();

    // Create a Date object for today.
    Date d2 = new Date(); // today

    DateFormat df_us = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l1),
        df_sp = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l2);
    System.out.println("Date d1 for US is " + df_us.format(d1));
    System.out.println("Date d1 for Spain is " + df_sp.format(d1));
    System.out.println("Date d2 is " + df_us.format(d2));
  }
示例#8
0
 /**
  * @bug 4139940 Couldn't reproduce this bug -- probably was fixed earlier.
  *     <p>ORIGINAL BUG REPORT: -- basically, hungarian for monday shouldn't have an \u00f4 (o
  *     circumflex)in it instead it should be an o with 2 inclined (right) lines over it..
  *     <p>You may wonder -- why do all this -- why not just add a line to LocaleData? Well, I
  *     could see by inspection that the locale file had the right character in it, so I wanted to
  *     check the rest of the pipeline -- a very remote possibility, but I wanted to be sure. The
  *     other possibility is that something is wrong with the font mapping subsystem, but we can't
  *     test that here.
  */
 public void Test4139940() {
   Locale mylocale = new Locale("hu", "", "");
   Date mydate = new Date(98, 3, 13); // A Monday
   DateFormat df_full = new SimpleDateFormat("EEEE", mylocale);
   String str = df_full.format(mydate);
   // Make sure that o circumflex (\u00F4) is NOT there, and
   // o double acute (\u0151) IS.
   if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0)
     errln("Fail: Monday in Hungarian is wrong");
 }
示例#9
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
示例#10
0
 // 将从SQL数据库中选择出来的日期性字段格式化为本地日期描述
 public String FormatDate(String DateStr) {
   if (DateStr.equals(null) || DateStr.equals("")) {
     return "    -  -  ";
   } else {
     try {
       DateFormat df = DateFormat.getDateInstance();
       Date d = df.parse(DateStr);
       df = DateFormat.getDateInstance(DateFormat.FULL);
       return df.format(d);
     } catch (ParseException e) {
       System.err.println("bean_ElearnTools.FormatDate error: " + e.getMessage());
       return DateStr;
     }
   }
 }
示例#11
0
 /**
  * If writing every day, or shares traded on date,<br>
  * Write [DATE]: cash=[CASHVALUE], stocks=[STOCKVALUE], total=[TOTALVALUE]*
  */
 public void ordersCompleted(Date date, TradingAccount account) {
   // report new balances only if they changed (buy or sell occurred on date)
   if (!this.daysTradedOnly || this.lastTraceDate.equals(date)) {
     double cashBalance = account.getCurrentCashBalance();
     double stockValue = account.getCurrentStockValue();
     double total = cashBalance + stockValue;
     this.writer.println(
         DATE_FORMAT.format(date)
             + ": "
             + "cash="
             + DOLLAR_FORMAT.format(cashBalance)
             + ", "
             + "stocks="
             + DOLLAR_FORMAT.format(stockValue)
             + ", "
             + "total="
             + DOLLAR_FORMAT.format(total));
   }
 }
示例#12
0
 public void sendResponseHeaders(int rCode, long contentLen) throws IOException {
   if (sentHeaders) {
     throw new IOException("headers already sent");
   }
   this.rcode = rCode;
   String statusLine = "HTTP/1.1 " + rCode + Code.msg(rCode) + "\r\n";
   OutputStream tmpout = new BufferedOutputStream(ros);
   PlaceholderOutputStream o = getPlaceholderResponseBody();
   tmpout.write(bytes(statusLine, 0), 0, statusLine.length());
   boolean noContentToSend = false; // assume there is content
   rspHdrs.set("Date", df.format(new Date()));
   if (contentLen == 0) {
     if (http10) {
       o.setWrappedStream(new UndefLengthOutputStream(this, ros));
       close = true;
     } else {
       rspHdrs.set("Transfer-encoding", "chunked");
       o.setWrappedStream(new ChunkedOutputStream(this, ros));
     }
   } else {
     if (contentLen == -1) {
       noContentToSend = true;
       contentLen = 0;
     }
     /* content len might already be set, eg to implement HEAD resp */
     if (rspHdrs.getFirst("Content-length") == null) {
       rspHdrs.set("Content-length", Long.toString(contentLen));
     }
     o.setWrappedStream(new FixedLengthOutputStream(this, ros, contentLen));
   }
   write(rspHdrs, tmpout);
   this.rspContentLen = contentLen;
   tmpout.flush();
   tmpout = null;
   sentHeaders = true;
   if (noContentToSend) {
     WriteFinishedEvent e = new WriteFinishedEvent(this);
     server.addEvent(e);
     closed = true;
   }
   server.logReply(rCode, req.requestLine(), null);
 }
示例#13
0
  public static void main(String args[]) {
    Date now = new Date();
    DateFormat df = DateFormat.getDateInstance();
    String component = "Component : " + args[0];
    String date = "Date : " + df.format(now);
    ;
    String version = "Version : " + args[1];

    try {
      FileWriter fstream = new FileWriter("packInfo.txt");
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(component);
      out.newLine();
      out.write(date);
      out.newLine();
      out.write(version);
      out.close();
    } catch (Exception e) {
      System.err.println("Error in opening a file");
    }
  }
示例#14
0
  /**
   * Creates an NotifyRequest for the specified file. If the specified file is null, a
   * IllegalArgumentException is thrown.
   */
  public NotifyRequest(File file, String command, String parameters) {
    if (file == null) {
      throw new IllegalArgumentException("File must not be null!");
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append("Notify "); // NOI18N
    buffer.append(file.getName());
    buffer.append('\n');
    buffer.append(command);
    buffer.append('\t');
    buffer.append(DATE_FORMAT.format(new Date()));
    buffer.append('\t');
    buffer.append(HOST_NAME);
    buffer.append('\t');
    buffer.append(file.getParent());
    buffer.append('\t');
    buffer.append(parameters);
    buffer.append('\n');
    this.request = buffer.toString();
  }
示例#15
0
  synchronized Result formatSummary() {
    Result result = new Result();
    ProxyClient proxyClient = vmPanel.getProxyClient();
    if (proxyClient.isDead()) {
      return null;
    }

    buf = new StringBuilder();
    append("<table cellpadding=1>");

    try {
      RuntimeMXBean rmBean = proxyClient.getRuntimeMXBean();
      CompilationMXBean cmpMBean = proxyClient.getCompilationMXBean();
      ThreadMXBean tmBean = proxyClient.getThreadMXBean();
      MemoryMXBean memoryBean = proxyClient.getMemoryMXBean();
      ClassLoadingMXBean clMBean = proxyClient.getClassLoadingMXBean();
      OperatingSystemMXBean osMBean = proxyClient.getOperatingSystemMXBean();
      com.sun.management.OperatingSystemMXBean sunOSMBean =
          proxyClient.getSunOperatingSystemMXBean();

      append("<tr><td colspan=4>");
      append("<center><b>" + Messages.SUMMARY_TAB_TAB_NAME + "</b></center>");
      String dateTime = headerDateTimeFormat.format(System.currentTimeMillis());
      append("<center>" + dateTime + "</center>");

      append(newDivider);

      { // VM info
        append(newLeftTable);
        append(Messages.CONNECTION_NAME, vmPanel.getDisplayName());
        append(
            Messages.VIRTUAL_MACHINE,
            Resources.format(
                Messages.SUMMARY_TAB_VM_VERSION, rmBean.getVmName(), rmBean.getVmVersion()));
        append(Messages.VENDOR, rmBean.getVmVendor());
        append(Messages.NAME, rmBean.getName());
        append(endTable);

        append(newRightTable);
        result.upTime = rmBean.getUptime();
        append(Messages.UPTIME, formatTime(result.upTime));
        if (sunOSMBean != null) {
          result.processCpuTime = sunOSMBean.getProcessCpuTime();
          append(Messages.PROCESS_CPU_TIME, formatNanoTime(result.processCpuTime));
        }

        if (cmpMBean != null) {
          append(Messages.JIT_COMPILER, cmpMBean.getName());
          append(
              Messages.TOTAL_COMPILE_TIME,
              cmpMBean.isCompilationTimeMonitoringSupported()
                  ? formatTime(cmpMBean.getTotalCompilationTime())
                  : Messages.UNAVAILABLE);
        } else {
          append(Messages.JIT_COMPILER, Messages.UNAVAILABLE);
        }
        append(endTable);
      }

      append(newDivider);

      { // Threads and Classes
        append(newLeftTable);
        int tlCount = tmBean.getThreadCount();
        int tdCount = tmBean.getDaemonThreadCount();
        int tpCount = tmBean.getPeakThreadCount();
        long ttCount = tmBean.getTotalStartedThreadCount();
        String[] strings1 =
            formatLongs(
                tlCount, tpCount,
                tdCount, ttCount);
        append(Messages.LIVE_THREADS, strings1[0]);
        append(Messages.PEAK, strings1[1]);
        append(Messages.DAEMON_THREADS, strings1[2]);
        append(Messages.TOTAL_THREADS_STARTED, strings1[3]);
        append(endTable);

        append(newRightTable);
        long clCount = clMBean.getLoadedClassCount();
        long cuCount = clMBean.getUnloadedClassCount();
        long ctCount = clMBean.getTotalLoadedClassCount();
        String[] strings2 = formatLongs(clCount, cuCount, ctCount);
        append(Messages.CURRENT_CLASSES_LOADED, strings2[0]);
        append(Messages.TOTAL_CLASSES_LOADED, strings2[2]);
        append(Messages.TOTAL_CLASSES_UNLOADED, strings2[1]);
        append(null, "");
        append(endTable);
      }

      append(newDivider);

      { // Memory
        MemoryUsage u = memoryBean.getHeapMemoryUsage();

        append(newLeftTable);
        String[] strings1 = formatKByteStrings(u.getUsed(), u.getMax());
        append(Messages.CURRENT_HEAP_SIZE, strings1[0]);
        append(Messages.MAXIMUM_HEAP_SIZE, strings1[1]);
        append(endTable);

        append(newRightTable);
        String[] strings2 = formatKByteStrings(u.getCommitted());
        append(Messages.COMMITTED_MEMORY, strings2[0]);
        append(
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_LABEL,
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_VALUE,
            memoryBean.getObjectPendingFinalizationCount());
        append(endTable);

        append(newTable);
        Collection<GarbageCollectorMXBean> garbageCollectors =
            proxyClient.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {
          String gcName = garbageCollectorMBean.getName();
          long gcCount = garbageCollectorMBean.getCollectionCount();
          long gcTime = garbageCollectorMBean.getCollectionTime();

          append(
              Messages.GARBAGE_COLLECTOR,
              Resources.format(
                  Messages.GC_INFO,
                  gcName,
                  gcCount,
                  (gcTime >= 0) ? formatTime(gcTime) : Messages.UNAVAILABLE),
              4);
        }
        append(endTable);
      }

      append(newDivider);

      { // Operating System info
        append(newLeftTable);
        String osName = osMBean.getName();
        String osVersion = osMBean.getVersion();
        String osArch = osMBean.getArch();
        result.nCPUs = osMBean.getAvailableProcessors();
        append(Messages.OPERATING_SYSTEM, osName + " " + osVersion);
        append(Messages.ARCHITECTURE, osArch);
        append(Messages.NUMBER_OF_PROCESSORS, result.nCPUs + "");

        if (pathSeparator == null) {
          // Must use separator of remote OS, not File.pathSeparator
          // from this local VM. In the future, consider using
          // RuntimeMXBean to get the remote system property.
          pathSeparator = osName.startsWith("Windows ") ? ";" : ":";
        }

        if (sunOSMBean != null) {
          String[] kbStrings1 = formatKByteStrings(sunOSMBean.getCommittedVirtualMemorySize());

          String[] kbStrings2 =
              formatKByteStrings(
                  sunOSMBean.getTotalPhysicalMemorySize(),
                  sunOSMBean.getFreePhysicalMemorySize(),
                  sunOSMBean.getTotalSwapSpaceSize(),
                  sunOSMBean.getFreeSwapSpaceSize());

          append(Messages.COMMITTED_VIRTUAL_MEMORY, kbStrings1[0]);
          append(endTable);

          append(newRightTable);
          append(Messages.TOTAL_PHYSICAL_MEMORY, kbStrings2[0]);
          append(Messages.FREE_PHYSICAL_MEMORY, kbStrings2[1]);
          append(Messages.TOTAL_SWAP_SPACE, kbStrings2[2]);
          append(Messages.FREE_SWAP_SPACE, kbStrings2[3]);
        }

        append(endTable);
      }

      append(newDivider);

      { // VM arguments and paths
        append(newTable);
        String args = "";
        java.util.List<String> inputArguments = rmBean.getInputArguments();
        for (String arg : inputArguments) {
          args += arg + " ";
        }
        append(Messages.VM_ARGUMENTS, args, 4);
        append(Messages.CLASS_PATH, rmBean.getClassPath(), 4);
        append(Messages.LIBRARY_PATH, rmBean.getLibraryPath(), 4);
        append(
            Messages.BOOT_CLASS_PATH,
            rmBean.isBootClassPathSupported() ? rmBean.getBootClassPath() : Messages.UNAVAILABLE,
            4);
        append(endTable);
      }
    } catch (IOException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    } catch (UndeclaredThrowableException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    }

    append("</table>");

    result.timeStamp = System.currentTimeMillis();
    result.summary = buf.toString();

    return result;
  }
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (!path.equals(request.getRequestURI())) {
      return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/plain");

    PrintWriter out = null;
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

      out = response.getWriter();

      Map<String, Endpoint> endpointMap = tracker.getEndpointMap();
      Map<String, Long> expirationMap = tracker.getExpirationMap();

      out.println("Active sessions:");
      out.println();

      for (Map.Entry<String, Endpoint> ep : endpointMap.entrySet()) {
        String key = ep.getKey();
        out.print(ep.getKey());
        out.print(" => ");
        out.print(ep.getValue());

        Long expiration = expirationMap.get(key);
        if (expiration == null) {
          out.println(" (expiration unknown)");
        } else {
          out.print(" (expires ");
          out.print(df.format(new Date(expiration)));
          out.println(")");
        }
      }

      out.println();
      out.println("Events:");
      out.println();

      for (EndpointEvent event : tracker.getEvents()) {
        out.print(df.format(new Date(event.getTimestamp())));
        out.print(" ");
        out.print(event.getStatus().name());
        out.print(" ");
        out.print(event.getConnectionId());
        out.print(" ");
        out.print(event.getDetails());
        out.println();
      }
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (Throwable ignored) {
      }
    }
    baseRequest.setHandled(true);
  }
  private void processRequest(PDU pdu) throws DBException, IOException {
    // Process the request and add to SMS_RECEIVE_QUEUE
    if (pdu.getCommandId() == Data.DELIVER_SM) {

      dsm = (DeliverSM) pdu;
      this.userId = dsm.getSourceAddr().getAddress();
      this.serviceId = dsm.getDestAddr().getAddress();
      this.info = dsm.getShortMessage();

      ByteBuffer da = null;

      try {
        da = dsm.getDestSubaddress();

        String te = Convert.hexToString(da.getHexDump().substring(2));

        //				this.RequestID = te;
        Gateway.util.log(this.getClass().getName(), "getDestSubaddress:" + te);
      } catch (ValueNotSetException ex) {

      }
      short destport = 0;
      try {
        destport = dsm.getDestinationPort();

        Gateway.util.log(this.getClass().getName(), "getDestinationPort:" + destport);
      } catch (ValueNotSetException e) {
        // TODO Auto-generated catch block
        // Tim Dport o day
        // ByteBuffer otaData =new
        // ByteBuffer(info.getBytes(Data.ENC_ISO8859_1));
        ByteBuffer otaData = new ByteBuffer();
        otaData = dsm.getShortMessagebuff();
        try {

          byte udhlength = otaData.removeByte();
          byte udhele1 = otaData.removeByte();
          byte udhele2 = otaData.removeByte();

          short sdport = otaData.removeShort();

          short ssport = otaData.removeShort();

          String newmsg = otaData.removeString(otaData.length(), Data.ENC_ISO8859_1);

          if (udhlength == 6 && udhele1 == 5) {
            destport = sdport;
            this.info = newmsg;
            Gateway.util.log(
                this.getClass().getName(), "getDestinationPort:" + destport + "@info=" + newmsg);
          }

        } catch (NotEnoughDataInByteBufferException e1) {
          // TODO Auto-generated catch block

        }
      }

      this.Dport = Short.toString(destport);

      if (this.info == null) {
        this.info = "null";
      }
      this.userId = removePlusSign(this.userId);
      this.serviceId = rebuildServiceId(this.serviceId);
      this.operator = Preference.mobileOperator;
      // Added on 22//2003 : VinaPhone gui ban tin DeliverReport voi
      // truong esm_class != 0x4. ==> He thong xem nhu ban tin thuong
      // sai format va gui thong bao -- report -- thong bao --> LOOP./
      // To pass over this, set:

      if (dsm.getEsmClass() == 0x4 || info.startsWith("id:")) { // DeliverReport
        // (not
        // processed)!
        Gateway.util.log(this.getClass().getName(), "It can be DeliverReport (not processed)!");
        return; // not processed
      }

      // Normal message (request):
      // Neu mobile o che do tieng viet
      // --> Loai bo space (ky tu 00) giua cac ky tu
      this.info = StringTool.removeChar(this.info, '\00');

      String newserviceid = this.serviceId;

      newserviceid = newserviceid.substring(newserviceid.length() - 4);

      // DANND add
      DateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSSS");
      java.util.Date date = new java.util.Date();
      String datetime = dateFormat.format(date);
      this.RequestID = Preference.prefix_requestid + datetime + threadId;

      dbTools.add2SMSReceiveQueueR(
          this.userId,
          this.serviceId,
          this.operator,
          this.commandCode,
          this.info,
          this.RequestID,
          this.Dport);
    }
  }
示例#18
0
 public static String getDate() {
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   // get current date time with Date()
   Date date = new Date();
   return dateFormat.format(date);
 }
示例#19
0
 public static String getDateTime() {
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   Date date = new Date();
   return dateFormat.format(date);
 }
示例#20
0
  /**
   * The constructor for this class has a bunch of arguments: The frame argument is required for all
   * printing in Java. The jobname appears left justified at the top of each printed page. The font
   * size is specified in points, as on-screen font sizes are. The margins are specified in inches
   * (or fractions of inches).
   */
  public HardcopyWriter(
      Frame frame,
      String jobname,
      int fontsize,
      double leftmargin,
      double rightmargin,
      double topmargin,
      double bottommargin)
      throws HardcopyWriter.PrintCanceledException {
    // Get the PrintJob object with which we'll do all the printing.
    // The call is synchronized on the static printprops object, which
    // means that only one print dialog can be popped up at a time.
    // If the user clicks Cancel in the print dialog, throw an exception.
    Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame
    synchronized (printprops) {
      job = toolkit.getPrintJob(frame, jobname, printprops);
    }
    if (job == null) throw new PrintCanceledException("User cancelled print request");

    pagesize = job.getPageDimension(); // query the page size
    pagedpi = job.getPageResolution(); // query the page resolution

    // Bug Workaround:
    // On windows, getPageDimension() and getPageResolution don't work, so
    // we've got to fake them.
    if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) {
      // Use screen dpi, which is what the PrintJob tries to emulate, anyway
      pagedpi = toolkit.getScreenResolution();
      System.out.println(pagedpi);
      // Assume a 8.5" x 11" page size.  A4 paper users have to change this.
      pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi);
      System.out.println(pagesize);
      // We also have to adjust the fontsize.  It is specified in points,
      // (1 point = 1/72 of an inch) but Windows measures it in pixels.
      fontsize = fontsize * pagedpi / 72;
      System.out.println(fontsize);
      System.out.flush();
    }

    // Compute coordinates of the upper-left corner of the page.
    // I.e. the coordinates of (leftmargin, topmargin).  Also compute
    // the width and height inside of the margins.
    x0 = (int) (leftmargin * pagedpi);
    y0 = (int) (topmargin * pagedpi);
    width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi);
    height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi);

    // Get body font and font size
    font = new Font("Monospaced", Font.PLAIN, fontsize);
    metrics = toolkit.getFontMetrics(font);
    lineheight = metrics.getHeight();
    lineascent = metrics.getAscent();
    charwidth = metrics.charWidth('0'); // Assumes a monospaced font!

    // Now compute columns and lines will fit inside the margins
    chars_per_line = width / charwidth;
    lines_per_page = height / lineheight;

    // Get header font information
    // And compute baseline of page header: 1/8" above the top margin
    headerfont = new Font("SansSerif", Font.ITALIC, fontsize);
    headermetrics = toolkit.getFontMetrics(headerfont);
    headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent();

    // Compute the date/time string to display in the page header
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
    df.setTimeZone(TimeZone.getDefault());
    time = df.format(new Date());

    this.jobname = jobname; // save name
    this.fontsize = fontsize; // save font size
  }
示例#21
0
  public String what(String key, boolean oneliner) throws Exception {
    byte[] sha;

    Matcher m = SHA_P.matcher(key);
    if (m.matches()) {
      sha = Hex.toByteArray(key);
    } else {
      m = URL_P.matcher(key);
      if (m.matches()) {
        URL url = new URL(key);
        sha = SHA1.digest(url.openStream()).digest();
      } else {
        File jarfile = new File(key);
        if (!jarfile.exists()) {
          reporter.error("File does not exist: %s", jarfile.getCanonicalPath());
        }
        sha = SHA1.digest(jarfile).digest();
      }
    }
    reporter.trace("sha %s", Hex.toHexString(sha));
    Revision revision = library.getRevision(sha);
    if (revision == null) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    Justif justif = new Justif(120, 20, 70, 20, 75);
    DateFormat dateFormat = DateFormat.getDateInstance();

    try {
      if (oneliner) {
        f.format("%20s %s%n", Hex.toHexString(revision._id), createCoord(revision));
      } else {
        f.format("Artifact: %s%n", revision.artifactId);
        if (revision.organization != null && revision.organization.name != null) {
          f.format(" (%s)", revision.organization.name);
        }
        f.format("%n");
        f.format("Coordinates\t0: %s%n", createCoord(revision));
        f.format("Created\t0: %s%n", dateFormat.format(new Date(revision.created)));
        f.format("Size\t0: %d%n", revision.size);
        f.format("Sha\t0: %s%n", Hex.toHexString(revision._id));
        f.format("URL\t0: %s%n", createJpmLink(revision));
        f.format("%n");
        f.format("%s%n", revision.description);
        f.format("%n");
        f.format("Dependencies\t0:%n");
        boolean flag = false;
        Iterable<RevisionRef> closure = library.getClosure(revision._id, true);
        for (RevisionRef dep : closure) {
          f.format(
              " - %s \t2- %s \t3- %s%n",
              dep.name, createCoord(dep), dateFormat.format(new Date(dep.created)));
          flag = true;
        }
        if (!flag) {
          f.format("     None%n");
        }
        f.format("%n");
      }
      f.flush();
      justif.wrap(sb);
      return sb.toString();
    } finally {
      f.close();
    }
  }