Beispiel #1
0
  /**
   * Reads in external transaction file that the user chooses to import.
   *
   * @param splitFile - file that user chooses to upload.
   * @return - arraylist containing the user's imported holdings. Created by: Kimberly Sookoo.
   */
  public static ArrayList<Transaction> readTransactionImports(ArrayList<String[]> splitFile) {

    ArrayList<Transaction> allTransactions = new ArrayList<>();

    for (String[] line : splitFile) {
      Date date = null;
      try {
        date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(line[2]);
      } catch (ParseException e) {
        e.printStackTrace();
      }
      double amount = Double.parseDouble(line[1]);
      // (double amount, String dateMade, String type, String cashAccountName) {

      String cashAccountName = line[0];
      String type = line[3];
      Transaction trans;
      if (type.equals("Withdrawal")) {
        trans = new Withdrawal(amount, date);
        trans.setCashAccountName(cashAccountName);
      } else { // if(stringType.equals("Deposit")){
        trans = new Deposit(amount, date);
        trans.setCashAccountName(cashAccountName);
      }

      allTransactions.add(trans);
    }

    return allTransactions;
  }
  // Load stored ToDoItems
  private void loadItems() {
    BufferedReader reader = null;
    try {
      FileInputStream fis = openFileInput(FILE_NAME);
      reader = new BufferedReader(new InputStreamReader(fis));

      String title = null;
      String priority = null;
      String status = null;
      Date date = null;

      while (null != (title = reader.readLine())) {
        priority = reader.readLine();
        status = reader.readLine();
        date = ToDoItem.FORMAT.parse(reader.readLine());
        mAdapter.add(new ToDoItem(title, Priority.valueOf(priority), Status.valueOf(status), date));
      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    } finally {
      if (null != reader) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  public Date transformarJulianaAGregoriadeLong(Long valor) {
    String j = valor.toString();
    Date date = new Date();
    String primerValor = "";
    if (j.length() == 5) {
      try {
        date = new SimpleDateFormat("yyD").parse(j);
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      primerValor = j.substring(0, 1);
      if (primerValor.equals("1")) {
        String anno = j.substring(1, 3);
        date.setYear(Integer.valueOf("20" + anno) - 1900);
        String s = j.substring(3);
        Date fecha = new Date();
        try {
          fecha = new SimpleDateFormat("D").parse(s);
        } catch (ParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        fecha.setYear(date.getYear());
        return fecha;
      }
    }

    return date;
  }
  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);

    if (localName.equals("item")) {
      stories.add(story);
      story = null;
      largestImgWidth = 0;
    }
    if (story != null) {
      if (localName.equals("title")) {
        story.setTitle(xmlInnerText.toString().trim());
      } else if (localName.equals("description")) {
        story.setDescription(xmlInnerText.toString().trim());
      } else if (localName.equals("link")) {
        story.setLink(xmlInnerText.toString().trim());
      } else if (localName.equals("pubDate")) {
        SimpleDateFormat dtSourceFormat = story.getSourceDateFormater();
        SimpleDateFormat dtTargetFormat = story.getTargetDateFormater();

        try {
          story.setPubDate(dtSourceFormat.parse(xmlInnerText.toString().trim()));
        } catch (ParseException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        Log.d("Exam01", "Parsed date : " + dtTargetFormat.format(story.getPubDate()));
      }
      xmlInnerText.setLength(0);
    }
  }
 public Date getCellDateValue(HSSFRow row, int index) throws ClearingException {
   HSSFCell cell = row.getCell(index);
   Date date = new Date();
   if (cell == null) {
     return null;
   }
   int cellType = cell.getCellType();
   if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
     NumberFormat integerInstance = NumberFormat.getInstance();
     integerInstance.setGroupingUsed(false);
     String cellStr = integerInstance.format(cell.getNumericCellValue());
     try {
       date = new SimpleDateFormat("yyyyMMdd").parse(cellStr);
     } catch (ParseException e) {
       throw new ClearingException("日期格式化错误");
     }
     return date;
   } else if (cellType == HSSFCell.CELL_TYPE_STRING) {
     try {
       date = new SimpleDateFormat("yyyyMMdd").parse(cell.getRichStringCellValue().getString());
     } catch (ParseException e) {
       e.printStackTrace();
     }
     return date;
   } else {
     return null;
   }
 }
 @Override
 public int Add() { // 增加资产
   Class_ManageDao cm = new Class_ManageDaoImpl();
   Scanner input = new Scanner(System.in);
   // 向资产表中添加数据
   System.out.println("请输入要增加的资产name");
   String name = input.next();
   System.out.println("请输入要增加的资产mainclass");
   String mainclass = input.next();
   System.out.println("请输入要增加的资产model");
   String model = input.next();
   System.out.println("请输入要增加的资产value");
   int value = input.nextInt();
   System.out.println("请输入要增加的资产date");
   String date = input.next();
   System.out.println("请输入要增加的资产status");
   int status = input.nextInt();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   try {
     Date Occ_Date = sdf.parse(date);
   } catch (ParseException e) {
     e.printStackTrace();
   }
   String sql =
       "insert into Fixed_Assets (Assets_name,MainClass,Model,Value,Buy_date,Status) values (?,?,?,?,?,?)";
   Object[] param = {name, mainclass, model, value, date, status};
   int result = this.exceuteUpdate(sql, param);
   // 检查类表中是否有该大类,没有则添加
   // 有该大类时,函数返回true,否则返回false
   if (!cm.getByClassName(mainclass)) {
     cm.Add(mainclass);
   }
   return result;
 }
  public void testParse1() {

    // Example header from JWE spec
    // {"alg":"RSA-OAEP","enc":"A256GCM"}
    String s = "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ";

    JWEHeader h = null;

    try {
      h = JWEHeader.parse(new Base64URL(s));

    } catch (ParseException e) {

      fail(e.getMessage());
    }

    assertNotNull(h);

    assertEquals(JWEAlgorithm.RSA_OAEP, h.getAlgorithm());
    assertEquals(EncryptionMethod.A256GCM, h.getEncryptionMethod());

    assertNull(h.getType());
    assertNull(h.getContentType());

    assertTrue(h.getIncludedParameters().contains("alg"));
    assertTrue(h.getIncludedParameters().contains("enc"));
    assertEquals(2, h.getIncludedParameters().size());
  }
  public static List<PernottamentoEntity> searchByCityDate(
      String city, String checkInDateStr, String checkOutDateStr) {

    List<PernottamentoEntity> pernottamentoList;
    java.util.Date checkInDate, checkOutDate;

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdfSQL = new SimpleDateFormat("yyyy/MM/dd");
    try {
      checkInDate = sdf.parse(checkInDateStr);
      checkInDateStr = sdfSQL.format(checkInDate);

      checkOutDate = sdf.parse(checkOutDateStr);
      checkOutDateStr = sdfSQL.format(checkOutDate);
    } catch (ParseException e) {
      e.printStackTrace();
    }

    String query =
        "where città like '"
            + city
            + "' AND "
            + "data_inizio < '"
            + checkOutDateStr
            + " 00:00:00' AND "
            + "data_finale > '"
            + checkInDateStr
            + " 00:00:00'";
    DAO dao = PernottamentoDaoHibernate.instance();
    DBManager.initHibernate();
    pernottamentoList = (List<PernottamentoEntity>) dao.getByCriteria(query);
    DBManager.shutdown();

    return pernottamentoList;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder;

    if (convertView == null) {
      LayoutInflater inflater = activity.getLayoutInflater();
      convertView = inflater.inflate(R.layout.view_list_transaction_history, parent, false);

      holder = new ViewHolder(convertView);
      convertView.setTag(holder);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    modelTransaction = getItem(position);

    holder.txtName.setText(modelTransaction.getRecipient_name());
    holder.txtStatus.setText(
        modelTransaction.getTransfer_status() == 0 ? "Processing" : "Accepted");

    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
      Date newFormat = sdf.parse(modelTransaction.getTransfer_datecreated());
      sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
      holder.txtDate.setText(sdf.format(newFormat).toUpperCase());
    } catch (ParseException e) {
      e.printStackTrace();
    }

    return convertView;
  }
Beispiel #10
0
  /**
   * converts this GDay into a local java Date.
   *
   * @return a local date representing this Date.
   */
  public java.util.Date toDate() {

    java.util.Date date = null;
    SimpleDateFormat df = new SimpleDateFormat(DAY_FORMAT);
    // Set the time zone
    if (isUTC()) {
      SimpleTimeZone timeZone = new SimpleTimeZone(0, "UTC");
      int offset = 0;
      offset = (int) ((this.getZoneMinute() + this.getZoneHour() * 60) * 60 * 1000);
      offset = isZoneNegative() ? -offset : offset;
      timeZone.setRawOffset(offset);
      timeZone.setID(timeZone.getAvailableIDs(offset)[0]);
      df.setTimeZone(timeZone);
    }

    try {
      date = df.parse(this.toString());
    } catch (ParseException e) {
      // this can't happen since toString() should return the proper
      // string format
      e.printStackTrace();
      return null;
    }
    return date;
  } // toDate()
Beispiel #11
0
 /** @param data - Date data in a format yyyy-mm-dd */
 public DateData(String data) {
   try {
     this.data = (Date) formatter.parse(data);
   } catch (ParseException e) {
     e.printStackTrace();
   }
 }
Beispiel #12
0
  /**
   * @author 斩飞
   * @param req
   * @param resp
   * @throws ServletException
   * @throws IOException 2011-5-6 - 下午01:18:22
   */
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String action = req.getParameter("action");
    String appName = req.getParameter("appName");
    String collectTime = req.getParameter("time");
    Date date = null;
    String reStr = "";
    boolean state = validateQueryParam(action, appName, collectTime, resp);
    if (state) {
      try {
        date = DateUtil.getDateYMDFormat().parse(collectTime);
      } catch (ParseException e) {
        logger.error("获取依赖我的应用json信息出错!" + e.getMessage());
        reStr = "<font style='color:red'>注意:请传入正确的日期参数,格式为yyyy-MM-dd!</font>";
        flushDataToBrowser(resp, reStr);
        return;
      }

      if ("medep".equals(action)) { // 我依赖的
        reStr = getMeDependentAppInfos(appName, date);

      } else if ("depme".equals(action)) { // 依赖我的
        reStr = getDependentMeAppInfos(appName, date);
      }
      flushDataToBrowser(resp, reStr);
    }
  }
  private ArrayList getLocalViaHeaders() throws IOException {
    /*
     * We can't keep a cached copy because the callers
     * of this method change the viaHeaders.  In particular
     * a branch may be added which causes INVITES to fail.
     */
    if (viaHeaders != null) {
      return viaHeaders;
    }

    ListeningPoint lp = sipProvider.getListeningPoint();
    viaHeaders = new ArrayList();

    try {
      String addr = lp.getIPAddress();

      ViaHeader viaHeader =
          headerFactory.createViaHeader(addr, lp.getPort(), lp.getTransport(), null);

      viaHeader.setRPort();

      viaHeaders.add(viaHeader);
      return viaHeaders;
    } catch (ParseException e) {
      throw new IOException(
          "A ParseException occurred while creating Via Headers! " + e.getMessage());
    } catch (InvalidArgumentException e) {
      throw new IOException(
          "Unable to create a via header for port " + lp.getPort() + " " + e.getMessage());
    }
  }
  private FromHeader getFromHeader() throws IOException {

    if (fromHeader != null) {
      return fromHeader;
    }

    try {
      SipURI fromURI =
          (SipURI)
              addressFactory.createURI("sip:" + proxyCredentials.getUserName() + "@" + registrar);

      fromURI.setTransportParam(sipProvider.getListeningPoint().getTransport());

      fromURI.setPort(sipProvider.getListeningPoint().getPort());

      Address fromAddress = addressFactory.createAddress(fromURI);

      fromAddress.setDisplayName(proxyCredentials.getUserDisplay());

      fromHeader = headerFactory.createFromHeader(fromAddress, Integer.toString(hashCode()));

    } catch (ParseException e) {
      throw new IOException(
          "A ParseException occurred while creating From Header! " + e.getMessage());
    }

    return fromHeader;
  }
Beispiel #15
0
  /**
   * Runs a sample agent with a default configuration defined by <code>SampleAgentConfig.properties
   * </code>. A sample command line is:
   *
   * <pre>
   * -c SampleAgent.cfg -bc SampleAgent.bc udp:127.0.0.1/4700 tcp:127.0.0.1/4700
   * </pre>
   *
   * @param args the command line arguments defining at least the listen addresses. The format is
   *     <code>-c[s{=SampleAgent.cfg}] -bc[s{=SampleAgent.bc}]
   *    +ts[s] +cfg[s] #address[s<(udp|tcp):.*[/[0-9]+]?>] ..</code>. For the format description see
   *     {@link ArgumentParser}.
   */
  public static void main(String[] args) {
    ArgumentParser parser =
        new ArgumentParser(
            "-c[s{=SampleAgent.cfg}] -bc[s{=SampleAgent.bc}] " + "+ts[s] +cfg[s]",
            "#address[s<(udp|tcp):.*[/[0-9]+]?>] ..");
    Map commandLineParameters = null;
    try {
      args = new String[1];
      args[0] = "udp:127.0.0.1/4700";
      commandLineParameters = parser.parse(args);
      SampleAgent sampleAgent = new SampleAgent(commandLineParameters);
      // Add all available security protocols (e.g.
      // SHA,MD5,DES,AES,3DES,..)
      SecurityProtocols.getInstance().addDefaultProtocols();
      // configure system group:
      // Set system description:
      // sampleAgent.agent.getSysDescr().setValue("My system
      // description".getBytes());
      // Set system OID (= OID of the AGENT-CAPABILITIES statement
      // describing
      // the implemented MIB objects of this agent:
      // sampleAgent.agent.getSysOID().setValue("1.3.1.6.1.4.1....");
      // Set the system services
      // sampleAgent.agent.getSysServices().setValue(72);
      sampleAgent.run();

    } catch (ParseException ex) {
      System.err.println(ex.getMessage());
    }
  }
Beispiel #16
0
        @Override
        public void onClick(View v) {
          // TODO Auto-generated method stub
          Log.d(TAG, "add......");

          mDate = mEdtDate.getText().toString();
          mItem = mEdtItem.getText().toString();
          try {
            mDateStamp = toDateStamp(mDate);
          } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          String costS = mEdtCost.getText().toString();
          if (!costS.matches("")) {
            mCost = Integer.parseInt(costS);
            Items it = new Items();
            it.setDate(mDate);
            it.setItem(mItem);
            it.setCost(mCost);
            it.setDateStamp(mDateStamp);
            ItemsHelper.addItems(getContentResolver(), it);
            //			money_items.add(0, it);				//********************************************
            money_items = ItemsHelper.listItems(MainActivity.this);
            itemadapter = new ItemAdapter2(MainActivity.this, money_items);
            money_list.setAdapter(itemadapter);
            itemadapter.notifyDataSetChanged();
            resetForm();
          } else {
            Toast.makeText(getApplicationContext(), "Cost 為必填欄位", Toast.LENGTH_SHORT).show();
          }
        }
  @Override
  public void onBindViewHolder(ViewHolder viewHolder, int position) {
    // MyListItem myListItem = MyListItem.fromCursor(cursor);
    try {
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
      viewHolder.seperator.setText(messages.get(position)[1]);
      if (!updatedT
          && parseDate(messages.get(position)[1])
              .equals(parseDate(dateFormat.format(new Date())))) {
        viewHolder.seperator.setVisibility(View.VISIBLE);
        viewHolder.seperator.setText("TODAY");
        updatedT = true;
      } else if (!updatedY
          && parseDate(messages.get(position)[1]).equals(parseDate(getYesterdayDateString()))) {
        viewHolder.seperator.setVisibility(View.VISIBLE);
        viewHolder.seperator.setText("YESTERDAY");
        updatedY = true;
      } else {
        if (lastDate != null && !lastDate.equals(messages.get(position)[1])) {
          viewHolder.seperator.setVisibility(View.VISIBLE);
          viewHolder.seperator.setText(messages.get(position)[1]);
        }
      }

    } catch (java.text.ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    viewHolder.messageSender.setText(
        messages.get(position)[2] + " (time:" + messages.get(position)[1] + ")");
    viewHolder.messageReciever.setText(
        messages.get(position)[5] + " (time:" + messages.get(position)[4] + ")");

    lastDate = messages.get(position)[1];
  }
Beispiel #18
0
  private Event castJSONObjToEvent(JSONObject jsonObj) {
    Event event = new Event();
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);

    try {
      String startTime = jsonObj.get("startTime").toString();
      String endTime = jsonObj.get("endTime").toString();

      event.setName(jsonObj.getString("name"));
      event.setDescription(jsonObj.getString("description"));
      event.setCategory(getCategory(jsonObj));
      event.setStatus(getStatus(jsonObj));
      event.setLocation(jsonObj.getString("location"));

      if (event.getCategory().equals(GenericEvent.Category.FLOATING)) {
        // doesn't set start time and end time
      } else {
        event.setStartTime(df.parse(startTime));
        event.setEndTime(df.parse(endTime));
      }

    } catch (JSONException e2) {
      e2.printStackTrace();
    } catch (ParseException e1) {
      e1.printStackTrace();
    }

    return event;
  }
    @Override
    public void mouseClicked(java.awt.event.MouseEvent e) {
      if (e.getClickCount() == 2) {
        int linha = table.getSelectedRow();
        Evento evento = new Evento();
        evento.setId((int) table.getValueAt(linha, 0));
        evento.setNome((String) table.getValueAt(linha, 1));
        try {
          Moeda moeda = new Moeda((String) table.getValueAt(linha, 2));
          evento.setValor(moeda.getValor());
        } catch (ParseException ex) {
          ex.printStackTrace();
        }

        evento.setDataEvento(
            AppDate.formatarDataInternacional((String) table.getValueAt(linha, 3)));
        eventos.add(evento);

        String nomeEvento, dataEvento, precoEvento;
        nomeEvento = (String) table.getValueAt(linha, 1);
        precoEvento = (String) table.getValueAt(linha, 2);
        dataEvento = (String) table.getValueAt(linha, 3);
        atualizarValor(precoEvento);

        adicionarProdutoVendaList(nomeEvento, precoEvento, dataEvento);
      }
    }
Beispiel #20
0
  private JSONObject castEventToJSONObj(Event event) {
    JSONObject jsonObj = new JSONObject();

    DateFormat dfDeadline = new SimpleDateFormat("yyyy-M-dd");
    Date deadLine = null;

    try {
      deadLine = dfDeadline.parse("1970-01-01");
    } catch (ParseException e) {
      e.printStackTrace();
    }

    try {
      jsonObj.put("name", event.getName());
      jsonObj.put("description", event.getDescription());
      jsonObj.put("category", event.getCategory());
      jsonObj.put("status", event.getStatus());
      jsonObj.put("location", event.getLocation());

      if (event.getCategory().equals(GenericEvent.Category.DEADLINE)) {
        jsonObj.put("startTime", deadLine);
        jsonObj.put("endTime", event.getEndTime());
      } else {
        jsonObj.put("startTime", event.getStartTime());
        jsonObj.put("endTime", event.getEndTime());
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }

    return jsonObj;
  }
  public void testParse2() {

    // Example header from JWE spec
    // {"alg":"RSA1_5","enc":"A128CBC+HS256"}
    String s = "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDK0hTMjU2In0";

    JWEHeader h = null;

    try {
      h = JWEHeader.parse(new Base64URL(s));

    } catch (ParseException e) {

      fail(e.getMessage());
    }

    assertNotNull(h);

    assertEquals(JWEAlgorithm.RSA1_5, h.getAlgorithm());
    assertEquals(EncryptionMethod.A128CBC_HS256, h.getEncryptionMethod());

    assertNull(h.getType());
    assertNull(h.getContentType());

    assertTrue(h.getIncludedParameters().contains("alg"));
    assertTrue(h.getIncludedParameters().contains("enc"));
    assertEquals(2, h.getIncludedParameters().size());
  }
Beispiel #22
0
  public void query(String tableName, List<IGame> games) {
    Cursor c = queryTheCursor2(tableName);
    while (c.moveToNext()) {
      IGame game;
      int _id = c.getInt(c.getColumnIndex("_id"));
      String guest = c.getString(c.getColumnIndex("guest"));
      String host = c.getString(c.getColumnIndex("host"));
      int type = c.getInt(c.getColumnIndex("type"));
      String chanls = c.getString(c.getColumnIndex("chanls"));
      Boolean isEvent = (c.getInt(c.getColumnIndex("evented")) != 0);
      Long eventId = c.getLong(c.getColumnIndex("eventid"));
      String originalString = c.getString(c.getColumnIndex("dt"));
      Date dt;
      try {
        Date tmpDt = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US).parse(originalString);
        dt = tmpDt;

        if (tableName.equals("azhibogame"))
          game = new AzhiboGame(_id, guest, host, dt, type, chanls, isEvent, eventId);
        else game = new SinaGame(_id, guest, host, dt, type, chanls, isEvent, eventId);
        games.add(game);
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    c.close();
  }
  private boolean isAllValuesAcceptable() {
    boolean retValue = true;

    try {
      setNumericalValues();
    } catch (ParseException e) {
      showErrorMessage(
          Locale.getString("ERROR_PARSING_NUMBER", e.getMessage()),
          Locale.getString("INVALID_GP_ERROR"));
      retValue = false;
    }

    if (!isAllValuesPositive()) {
      showErrorMessage(
          Locale.getString("NO_POSITIVE_VALUES_ERROR"), Locale.getString("INVALID_GP_ERROR"));
      retValue = false;
    }

    if (!isTotalOK()) {
      // Messages inside the isTotalOK method
      retValue = false;
    }

    return retValue;
  }
Beispiel #24
0
  public List<IGame> query(List<IGame> games) {
    Cursor c = queryTheCursor();
    while (c.moveToNext()) {
      SinaGame game = new SinaGame();
      game._id = c.getInt(c.getColumnIndex("_id"));
      game.guest = c.getString(c.getColumnIndex("guest"));
      game.host = c.getString(c.getColumnIndex("host"));
      game.type = c.getInt(c.getColumnIndex("type"));
      game.chanls = c.getString(c.getColumnIndex("chanls"));
      game.isEvent = (c.getInt(c.getColumnIndex("evented")) != 0);
      game.eventId = c.getLong(c.getColumnIndex("eventid"));

      String originalString = c.getString(c.getColumnIndex("dt"));
      Date date;
      try {
        date = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US).parse(originalString);
        game.dt = date;
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      games.add(game);
    }
    c.close();
    return games;
  }
Beispiel #25
0
  public void parseStatusXml(String statusXml) {
    try {
      Document statusDoc = SubmissionUtils.emptyDocument();
      SubmissionUtils.transform(new StringReader(statusXml), statusDoc);

      if (statusDoc.getDocumentElement().getTagName().equals("error")) {
        String runName = statusDoc.getElementsByTagName("RunName").item(0).getTextContent();
        String runDirRegex = "(\\d{6})_([A-z0-9]+)_(\\d+)_[A-z0-9_]*";
        Matcher m = Pattern.compile(runDirRegex).matcher(runName);
        if (m.matches()) {
          setStartDate(new SimpleDateFormat("yyMMdd").parse(m.group(1)));
          setInstrumentName(m.group(2));
        }
        setRunName(runName);
        setHealth(HealthType.Unknown);
      } else {
        String runStarted = statusDoc.getElementsByTagName("RunStarted").item(0).getTextContent();
        setStartDate(new SimpleDateFormat("EEEE, MMMMM dd, yyyy h:mm aaa").parse(runStarted));
        setInstrumentName(
            statusDoc.getElementsByTagName("InstrumentName").item(0).getTextContent());
        setRunName(statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
        setHealth(HealthType.Unknown);
      }
      setXml(statusXml);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
  /**
   * Read location information from image.
   *
   * @param imagePath : image absolute path
   * @return : loation information
   */
  public Location readGeoTagImage(String imagePath) {
    Location loc = new Location("");
    try {
      ExifInterface exif = new ExifInterface(imagePath);
      float[] latlong = new float[2];
      if (exif.getLatLong(latlong)) {
        loc.setLatitude(latlong[0]);
        loc.setLongitude(latlong[1]);
      }
      String date = exif.getAttribute(ExifInterface.TAG_DATETIME);
      SimpleDateFormat fmt_Exif = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
      try {
        loc.setTime(fmt_Exif.parse(date).getTime());
      } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
    return loc;
  }
 @Override
 public final int compare(String[] o1, String[] o2) {
   String t1 = o1[this.index];
   String t2 = o2[this.index];
   if (StringUtils.isEmpty(t1) && StringUtils.isEmpty(t2)) {
     return 0;
   }
   if (StringUtils.isEmpty(t1)) {
     return 1;
   }
   if (StringUtils.isEmpty(t2)) {
     return -1;
   }
   if (StringUtils.isNumeric(t1) && StringUtils.isNumeric(t2)) {
     // 数値文字列の場合
     Long o1l = Long.valueOf(t1);
     Long o2l = Long.valueOf(t2);
     return this.compareTo(o1l, o2l, this.order);
   } else if (t1.matches("(?:\\d+日)?(?:\\d+時間)?(?:\\d+分)?(?:\\d+秒)?")) {
     try {
       // 時刻文字列の場合
       // SimpleDateFormatは24時間超えるような時刻でも正しく?パースしてくれる
       Date o1date = DateUtils.parseDate(t1, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分");
       Date o2date = DateUtils.parseDate(t2, "ss秒", "mm分ss秒", "HH時間mm分", "dd日HH時間mm分");
       return this.compareTo(o1date, o2date, this.order);
     } catch (ParseException e) {
       e.printStackTrace();
     }
   }
   // 文字列の場合
   return this.compareTo(t1, t2, this.order);
 }
  @AfterViews
  public void setPreferences() {

    SharedPreferences preferences =
        getActivity().getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);

    accessToken = preferences.getString("access_token", "").replace("\"", "");
    if (getArguments() != null) {
      Todo todo = (Todo) getArguments().getSerializable(NEW_INSTANCE_TODO_KEY);
      concernedMembers.addAll(todo.members);
      currentTodoId = todo.id;
      todoInput.setText(todo.text);
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      format.setTimeZone(TimeZone.getTimeZone("UTC"));
      Date date = new Date();
      try {
        date = format.parse(todo.remindMeAt);
      } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      Calendar cal = Calendar.getInstance();
      TimeZone tz = cal.getTimeZone();
      SimpleDateFormat formatToShow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      formatToShow.setTimeZone(tz);

      String[] splitDate = formatToShow.format(date).split(" ");
      dateText.setText(splitDate[0]);
      timeText.setText(splitDate[1]);
    }
  }
  public static void main(String[] args) {
    NetCDFDir2Block_Reanalysis ncb = new NetCDFDir2Block_Reanalysis();

    if (args.length != 5) {
      System.out.println(
          "Usage: <input variable name> <input directory> <output directory> <block size> <start time yyyy_MM_dd in UTC>");
      System.exit(-1);
    }

    ncb.inVarName = args[0];
    ncb.fileDir = args[1];
    ncb.outputDir = args[2];
    ncb.blocksize = TimeConvert.daysToMillis(args[3]);
    ncb.filter = new FilenamePatternFilter(".*_" + ncb.inVarName + "_.*\\.nc");
    if (ncb.inVarName.equalsIgnoreCase("w")) {
      ncb.inVarName = "w_velocity";
    }
    if (ncb.inVarName.equalsIgnoreCase("u")) {
      ncb.inVarName = "water_u";
    }
    if (ncb.inVarName.equalsIgnoreCase("v")) {
      ncb.inVarName = "water_v";
    }
    String initString = args[4] + " UTC";
    // String initString = "1993_01_01" + " UTC";

    try {
      // ncb.initialTime = ncb.df2.parse("2014_03_06 UTC").getTime();
      ncb.initialTime = ncb.df2.parse(initString).getTime();
    } catch (ParseException e) {
      e.printStackTrace();
    }
    ncb.convert(ncb.fileDir, ncb.filter, ncb.blocksize);
    System.out.println("Complete.");
  }
  /**
   * Checa a data e a hora
   *
   * @param data A data
   * @param hora A hora
   * @throws InvalidAttributeValueException
   */
  public static void checaDataHora(String data, String hora) throws InvalidAttributeValueException {
    if (data == null) throw new InvalidAttributeValueException("Data inválida");
    if (hora == null) throw new InvalidAttributeValueException("Hora inválida");
    SimpleDateFormat format = null;
    String dataHora = data + " " + hora;
    Date date = null;

    format = new SimpleDateFormat("dd/MM/yyyy");
    format.setLenient(false);
    try {
      date = format.parse(data);
    } catch (Exception e) {
      throw new InvalidAttributeValueException("Data inválida");
    }

    format = new SimpleDateFormat("HH:mm");
    format.setLenient(false);
    try {
      date = format.parse(hora);
    } catch (Exception e) {
      throw new InvalidAttributeValueException("Hora inválida");
    }

    format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    format.setLenient(false);
    try {
      date = format.parse(dataHora);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    if (date.before(new Date())) throw new InvalidAttributeValueException("Data inválida");
  }