@Override
 @WebMethod(operationName = "getTournamentsByLocationAndDate")
 public Tournaments getAllTournamentsByLocationAndDate(
     @WebParam(name = "location") String location,
     @WebParam(name = "dateFrom") String dateFrom,
     @WebParam(name = "dateTo") String dateTo)
     throws InvalidInputException {
   DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
   Date tournamentStartDate;
   Date tournamentEndDate;
   try {
     tournamentStartDate = format.parse(dateFrom);
   } catch (ParseException e) {
     throw new InvalidInputException(e.getMessage(), "Invalid date format");
   }
   try {
     tournamentEndDate = format.parse(dateTo);
   } catch (ParseException e) {
     throw new InvalidInputException(e.getMessage(), "Invalid date format");
   }
   List<Tournament> tournamentsFromDB =
       tournamentService.getAllTournamentsByLocationAndDate(
           location, tournamentStartDate, tournamentEndDate);
   Tournaments tournaments = new Tournaments();
   tournaments.setTournaments(tournamentsFromDB);
   return tournaments;
 }
 private void setTradeTimeMillis(
     TradeTime paramTradeTime, String paramString1, String paramString2) {
   try {
     if (paramTradeTime.getGatherBid().shortValue() == 1) {
       paramTradeTime.setBidStartTimeMillis(
           DateUtil.convertStringToDate(
                   "yyyy-MM-dd HH:mm:ss", paramString1 + " " + paramTradeTime.getBidStartTime())
               .getTime());
       paramTradeTime.setBidEndTimeMillis(
           DateUtil.convertStringToDate(
                   "yyyy-MM-dd HH:mm:ss", paramString1 + " " + paramTradeTime.getBidEndTime())
               .getTime());
       paramTradeTime.setBidStartDate(paramString1);
       paramTradeTime.setBidEndDate(paramString2);
     }
     paramTradeTime.setStartTimeMillis(
         DateUtil.convertStringToDate(
                 "yyyy-MM-dd HH:mm:ss", paramString1 + " " + paramTradeTime.getStartTime())
             .getTime());
     paramTradeTime.setEndTimeMillis(
         DateUtil.convertStringToDate(
                 "yyyy-MM-dd HH:mm:ss", paramString2 + " " + paramTradeTime.getEndTime())
             .getTime());
     paramTradeTime.setStartDate(paramString1);
     paramTradeTime.setEndDate(paramString2);
   } catch (ParseException localParseException) {
     this.log.error("转换交易节信息时解析日期失败,原因:" + localParseException.getMessage());
     System.out.println(
         DateUtil.getCurDateTime() + "   转换交易节信息时解析日期失败,原因:" + localParseException.getMessage());
   }
 }
 /** Signals that an error has been reached unexpectedly while parsing. */
 @ExceptionHandler(ParseException.class)
 public ResponseEntity<Map<String, Object>> handleParseException(ParseException error) {
   Map<String, Object> errorMap = new HashMap<String, Object>();
   errorMap.put("hasErrors", "true");
   errorMap.put("developerMessage", error.getMessage() + "at position " + error.getErrorOffset());
   errorMap.put("userMessage", error.getMessage());
   errorMap.put("moreInfo", error.getMessage());
   errorMap.put("errorCode", HttpStatus.BAD_REQUEST);
   error.printStackTrace();
   return new ResponseEntity<Map<String, Object>>(errorMap, HttpStatus.BAD_REQUEST);
 }
Beispiel #4
0
  /*
   * Begin Third-Party Call Control.
   */
  public void initiateCall() throws IOException {
    try {
      try {
        busyTreatment = new TreatmentManager("busy.au", 0);
      } catch (IOException e) {
        Logger.println("Invalid busy treatment:  " + e.getMessage());
      }

      Logger.writeFile("Call " + cp + ":   Begin SIP third party call");

      setState(CallState.INVITED);

      InetSocketAddress isa = callHandler.getReceiveAddress();

      if (isa == null) {
        throw new IOException("can't get receiver socket!");
      }

      // send INVITE to the CallParticipant
      clientTransaction = sipUtil.sendInvite(cp, isa);

      if (clientTransaction == null) {
        Logger.error("Error placing call:  " + cp);
        setState(CallState.ENDED, "Reason='Error placing call'");
        throw new IOException("Error placing call:  " + cp);
      }

      CallIdHeader callIdHeader =
          (CallIdHeader) clientTransaction.getRequest().getHeader(CallIdHeader.NAME);

      sipCallId = callIdHeader.getCallId();

      sipServerCallback = SipServer.getSipServerCallback();
      sipServerCallback.addSipListener(sipCallId, this);
    } catch (java.text.ParseException e) {
      Logger.println("Call " + cp + " Error placing call " + cp + ":  " + e.getMessage());
      setState(CallState.ENDED, "Reason='Error placing call " + cp + " " + e.getMessage() + "'");
      throw new IOException("Error placing call " + cp + " " + e.getMessage());
    } catch (InvalidArgumentException e) {
      Logger.println("Call " + cp + " Error placing call " + cp + ":  " + e.getMessage());
      setState(CallState.ENDED, "Reason='Error placing call " + cp + " " + e.getMessage() + "'");
      throw new IOException("Error placing call " + cp + " " + e.getMessage());
    } catch (SipException e) {
      Logger.println("Call " + cp + " Error placing call " + cp + ":  " + e.getMessage());
      setState(CallState.ENDED, "Reason='Error placing call " + cp + " " + e.getMessage() + "'");
      throw new IOException("Error placing call " + cp + " " + e.getMessage());
    }
  }
  /**
   * Accept the next incoming connection.
   *
   * <p>When a new peer connects to this service, wait for it to send its handshake. We then parse
   * and check that the handshake advertises the torrent hash we expect, then reply with our own
   * handshake.
   *
   * <p>If everything goes according to plan, notify the <code>IncomingConnectionListener</code>s
   * with the connected socket and the parsed peer ID.
   */
  private void accept() throws IOException, SocketTimeoutException {
    Socket socket = this.socket.accept();

    try {
      logger.debug("New incoming connection ...");
      Handshake hs = this.validateHandshake(socket, null);
      this.sendHandshake(socket);
      this.fireNewPeerConnection(socket, hs.getPeerId());
    } catch (ParseException pe) {
      logger.debug("Invalid handshake from {}: {}", this.socketRepr(socket), pe.getMessage());
      try {
        socket.close();
      } catch (IOException e) {
      }
    } catch (IOException ioe) {
      logger.debug(
          "An error occured while reading an incoming " + "handshake: {}", ioe.getMessage());
      try {
        if (!socket.isClosed()) {
          socket.close();
        }
      } catch (IOException e) {
        // Ignore
      }
    }
  }
Beispiel #6
0
 private static SQLDeploymentDescriptor[] getDeploymentDescriptors(int jarId) throws SQLException {
   ResultSet rs = null;
   PreparedStatement stmt =
       SQLUtils.getDefaultConnection()
           .prepareStatement(
               "SELECT e.entryImage"
                   + " FROM sqlj.jar_descriptor d INNER JOIN sqlj.jar_entry e"
                   + "   ON d.entryId = e.entryId"
                   + " WHERE d.jarId = ?"
                   + " ORDER BY d.ordinal");
   try {
     stmt.setInt(1, jarId);
     rs = stmt.executeQuery();
     ArrayList<SQLDeploymentDescriptor> sdds = new ArrayList<SQLDeploymentDescriptor>();
     while (rs.next()) {
       byte[] bytes = rs.getBytes(1);
       // According to the SQLJ standard, this entry must be
       // UTF8 encoded.
       //
       sdds.add(new SQLDeploymentDescriptor(new String(bytes, "UTF8"), "postgresql"));
     }
     return sdds.toArray(new SQLDeploymentDescriptor[sdds.size()]);
   } catch (UnsupportedEncodingException e) {
     // Excuse me? No UTF8 encoding?
     //
     throw new SQLException("JVM does not support UTF8!!");
   } catch (ParseException e) {
     throw new SQLException(e.getMessage() + " at " + e.getErrorOffset());
   } finally {
     SQLUtils.close(rs);
     SQLUtils.close(stmt);
   }
 }
 @Override
 @WebMethod(operationName = "addTournament")
 public void addTournament(
     @WebParam(name = "date") String date,
     @WebParam(name = "location") String location,
     @WebParam(name = "surface") String surface,
     @WebParam(name = "draw") String draw,
     @WebParam(name = "numberOfSeeds") String numberOfSeeds)
     throws InvalidInputException {
   Tournament tournament = new Tournament();
   DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
   Date tournamentDate;
   try {
     tournamentDate = format.parse(date);
   } catch (ParseException e) {
     throw new InvalidInputException(e.getMessage(), "Invalid date format");
   }
   tournament.setTournamentDate(tournamentDate);
   tournament.setLocation(location);
   tournament.setSurface(surface);
   int seedsNumber = Integer.parseInt(numberOfSeeds);
   tournament.setNumberOfSeeds(seedsNumber);
   tournament.setSeeds(seedsNumber != 0);
   tournamentService.addTournament(tournament);
 }
 private Object convertValue(
     final ClassAttributeAssignmentModel assignment, final String stringValue) {
   final String typeCode = assignment.getAttributeType().getCode();
   if (ClassificationAttributeTypeEnum.BOOLEAN.getCode().equals(typeCode)) {
     return Boolean.valueOf(stringValue);
   } else if (ClassificationAttributeTypeEnum.ENUM.getCode().equals(typeCode)) {
     // YTODO
     final Item item = JaloSession.getCurrentSession().getItem(PK.parse(stringValue));
     final Object value = load(item);
     validateParameterNotNull(value, "No such value with PK: " + stringValue);
     return value;
   } else if (ClassificationAttributeTypeEnum.NUMBER.getCode().equals(typeCode)) {
     return Double.valueOf(stringValue);
   } else if (ClassificationAttributeTypeEnum.STRING.getCode().equals(typeCode)) {
     return stringValue;
   } else if (ClassificationAttributeTypeEnum.DATE.getCode().equals(typeCode)) {
     try {
       return Utilities.getDateTimeInstance().parse(stringValue);
     } catch (final ParseException e) {
       throw new IllegalArgumentException(e.getMessage(), e);
     }
   } else {
     throw new IllegalArgumentException("Invalid classifcation attribute type code: " + typeCode);
   }
 }
Beispiel #9
0
  public IPredicate getPredicate() {
    IPredicate predicate = null;
    if (myStandardSeach.isSelected()) {
      Enumeration optionsEnum = myOptions.elements();
      while (optionsEnum.hasMoreElements()) {
        TextOption option = (TextOption) optionsEnum.nextElement();
        if (option.isSelected()) {
          IPredicate optionPredicate = option.getPredicate();
          if (predicate == null) {
            predicate = optionPredicate;
          } else {
            predicate = new AndPredicate(predicate, optionPredicate);
          }
        }
      }
    } else if (myAdvancedSearch.isSelected()) {
      try {
        String searchString = myAdvancedTextField.getText();
        PredicateParser predParser = new PredicateParser();
        predicate = predParser.parse(searchString);
      } catch (ParseException e) {
        String error = e.getMessage();
        Debug.handleError(myContext.getFrame(), error, true);
      }
    }

    return predicate;
  }
  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;
  }
  private void setDateAndTime(String dateTime) {

    if (dateTime != null && !(TextUtils.isEmpty(dateTime))) {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd kk:mm:ss", Locale.US);
      Date date;
      try {

        date = dateFormat.parse(dateTime);

        if (date != null) {
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
          view.mPickDate.setText(simpleDateFormat.format(date));

          SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
          view.mPickTime.setText(timeFormat.format(date));

          // Because the API doesn't support dates in diff Locale
          // mode,
          // force
          // it to show time in US
          SimpleDateFormat submitFormat = new SimpleDateFormat("yyy-MM-dd kk:mm:ss", Locale.US);
          mDateToSubmit = submitFormat.format(date);
        } else {
          view.mPickDate.setText(R.string.change_date);
          view.mPickTime.setText(R.string.change_time);
          mDateToSubmit = null;
        }

      } catch (ParseException e) {
        log(e.getMessage());
      }
    }
  }
  // <timestamp>2015-08-05T00:44:14Z</timestamp>
  public void extractTimestamp() {
    String ref = "<timestamp>";
    Pattern p = Pattern.compile(Pattern.quote(ref) + "(.*?)" + Pattern.quote("</timestamp>"));
    Matcher m = p.matcher(raw);
    while (m.find()) {
      String timestamp = m.group(1);
      if (StringUtils.isNotBlank(timestamp)) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        try {
          cal.setTime(sdf.parse(timestamp));
          // Date articleDate = cal.getTime();

          Calendar c = new GregorianCalendar();
          c.set(Calendar.HOUR_OF_DAY, 0); // anything 0 - 23
          c.set(Calendar.MINUTE, 0);
          c.set(Calendar.SECOND, 0);

          daysSinceRevision = daysBetween(c, cal);
        } catch (ParseException e) {
          System.out.println(
              "While extracting timestamp " + e.getMessage() + " for article " + articleTitle);
        }
      } else {
        System.out.println("No timestamp found for article " + articleTitle);
      }
    }
  }
Beispiel #13
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);
    }
  }
Beispiel #14
0
  public List<StatusActivity> fetchActivities() {
    List<StatusActivity> statuses = new ArrayList<StatusActivity>();

    StringBuilder url =
        new StringBuilder("https://www.googleapis.com/plus/v1/people/")
            .append(this.googleId)
            .append("/activities/public?key=AIzaSyC4xOkQsEPJcUKUvQGL6T7RZkrIIxSuZAg");
    JsonElement response = fetchJson(url.toString());
    if (response != null) {
      JsonArray activities = response.getAsJsonObject().get("items").getAsJsonArray();
      DateFormat googleFormatter = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
      for (JsonElement element : activities) {
        JsonObject activity = element.getAsJsonObject();
        try {
          String content = activity.get("object").getAsJsonObject().get("content").getAsString();
          Date date = googleFormatter.parse(activity.get("published").getAsString());
          String statusId = activity.get("id").getAsString();
          String statusUrl = activity.get("url").getAsString();
          statuses.add(
              new StatusActivity(this.member, date, this.provider, content, statusUrl, statusId));
        } catch (ParseException pe) {
          Logger.error("ouch! parse exception " + pe.getMessage());
        }
      }
    }
    return statuses;
  }
  private PADCapturedFriendModel parseFriend(final JSONArray friendResult) throws JSONException {
    MyLog.entry();

    // [4, 333300602, "NeraudMule", 17, 1, "140829151957", 9, 29, 6, 1, 0, 0, 0, 0, 2, 15, 1, 0, 0,
    // 0, 0, 2, 15, 1, 0, 0, 0, 0]
    // New [5, 329993422, "HFR|Neraud", 292, 1, "150613152858", 48, 50, 6, 1, 0, 0, 0, 0, 0, 1422,
    // 99, 1, 13, 12, 9, 6, 0, 1217, 99, 6, 99, 99, 99, 6, 0]
    final PADCapturedFriendModel friend = new PADCapturedFriendModel();
    // index 0 could be the version number for the friend struct
    // version 7 added skill inheritance?
    friend.setId(friendResult.getLong(1));
    friend.setName(friendResult.getString(2));
    friend.setRank(friendResult.getInt(3));
    friend.setStartingColor(StartingColor.valueByCode(friendResult.getInt(4)));
    final String lastActivityDateString = friendResult.getString(5);
    try {
      final DateFormat parseFormat = new SimpleDateFormat("yyMMddHHmmss");
      parseFormat.setTimeZone(region.getTimeZone());
      final Date lastActivityDate = parseFormat.parse(lastActivityDateString);
      friend.setLastActivityDate(lastActivityDate);
    } catch (ParseException e) {
      MyLog.warn("error parsing lastActivityDate : " + e.getMessage());
    }

    final BaseMonsterStatsModel leader1 = extractFriendLeader(friendResult, 16);
    friend.setLeader1(leader1);

    final BaseMonsterStatsModel leader2 = extractFriendLeader(friendResult, 26);
    friend.setLeader2(leader2);

    MyLog.exit();
    return friend;
  }
  /** 应用客户端值分布相关 */
  @RequestMapping("/valueDistribute")
  public ModelAndView doValueDistribute(
      HttpServletRequest request, HttpServletResponse response, Model model) throws ParseException {
    // 1.1 应用信息
    Long appId = NumberUtils.toLong(request.getParameter("appId"));
    if (appId <= 0) {
      return new ModelAndView("");
    }
    AppDesc appDesc = appService.getByAppId(appId);
    model.addAttribute("appDesc", appDesc);

    // 1.2 时间格式转换
    TimeBetween timeBetween = new TimeBetween();
    try {
      timeBetween = fillWithValueDistriTime(request, model);
    } catch (ParseException e) {
      logger.error(e.getMessage(), e);
    }
    long startTime = timeBetween.getStartTime();
    long endTime = timeBetween.getEndTime();

    // 值分布列表
    List<AppClientValueDistriSimple> appClientValueDistriSimpleList =
        clientReportValueDistriServiceV2.getAppValueDistriList(appId, startTime, endTime);
    model.addAttribute("appClientValueDistriSimpleList", appClientValueDistriSimpleList);

    // 值分布json
    model.addAttribute(
        "appClientValueDistriSimpleListJson",
        JSONObject.toJSONString(appClientValueDistriSimpleList));

    return new ModelAndView("client/clientValueDistribute");
  }
Beispiel #17
0
  /**
   * Parse this pipeline and run it
   *
   * @return true if no error during processing
   * @throws ParseException
   */
  public static void runPipeline(File scriptFile, List<String> cliArgs)
      throws IOException, UIMAException, ParseException {
    if (!scriptFile.exists()) {
      throw new IOException("Script file does not exist (" + scriptFile.getAbsolutePath() + ")");
    }

    LOG.info(
        "Parsing pipeline script at '{}'",
        scriptFile.getAbsolutePath() + " \n with CLI parameters: " + join(cliArgs, ", "));
    Pipeline pipeline = null;
    try {
      pipeline = PipelineScriptParser.parse(scriptFile, cliArgs);
    } catch (ParseException e) {
      throw new ParseException(
          "\nERROR parsing '"
              + scriptFile.getName()
              + "'\n"
              + e.getMessage()
              + "\n(see the README.txt for the pipeline script format)",
          e.getErrorOffset());
    }

    LOG.info("Successfully parsed pipeline script, now starting pipeline...");
    LOG.info("*************************************************************");
    pipeline.run();
    // will be printed if no exception.
    // used in pipeline tests, do not change
    System.out.println(OK_MESSAGE);
  }
Beispiel #18
0
 public void testDateTime(CCNTime testDateTime) {
   String strDateTime = TextXMLCodec.formatDateTime(testDateTime);
   System.out.println("DateTime: " + testDateTime + " XML version: " + strDateTime);
   CCNTime parsedDateTime = null;
   try {
     parsedDateTime = TextXMLCodec.parseDateTime(strDateTime);
   } catch (ParseException e) {
     System.out.println("Exception parsing date time: " + e.getMessage());
     e.printStackTrace();
     Assert.fail("Failed to parse date time: " + strDateTime);
   }
   System.out.println("Parsed version: " + parsedDateTime);
   if (!parsedDateTime.equals(testDateTime)) {
     System.out.println(
         "Time : "
             + parsedDateTime
             + "(long: "
             + parsedDateTime.getTime()
             + ") does not equal "
             + testDateTime
             + "(long: "
             + testDateTime.getTime()
             + ")");
   }
   Assert.assertTrue(parsedDateTime.equals(testDateTime));
 }
  /*
   * (non-Javadoc)
   *
   * @see org.apache.oodt.cas.metadata.AbstractMetExtractor#extrMetadata(java.io
   * .File)
   */
  @Override
  protected Metadata extrMetadata(File file) throws MetExtractionException {
    Metadata met = new Metadata();
    String filename = file.getName();
    if (((FilenameTokenConfig) this.config).hasTokenNameList()) {
      List<String> metKeyTokens = ((FilenameTokenConfig) this.config).getTokenMetKeyNames();
      String[] filenameToks =
          filename.split("\\.")[0].split(
              ((FilenameTokenConfig) this.config).getTokenDelimeterScalar());
      for (int i = 0; i < filenameToks.length; i++) {
        String keyName = metKeyTokens.get(i);
        String keyVal = filenameToks[i];
        if (keyName.equals("ProductionDateTime")) {
          Calendar cal = GregorianCalendar.getInstance();
          try {
            cal.setTime(((FilenameTokenConfig) this.config).getDateFormatter().parse(keyVal));
          } catch (ParseException e) {
            throw new MetExtractionException(e.getMessage());
          }
          keyVal = DateUtils.toString(cal);
        }

        met.addMetadata(keyName, keyVal);
      }
    }

    Metadata commonMet = ((FilenameTokenConfig) this.config).getCommonMet();
    met.addMetadata(commonMet.getMap());
    met.addMetadata(((FilenameTokenConfig) this.config).getSubstringOffsetMet(file));

    met.addMetadata("Filename", file.getName());
    met.addMetadata("FileLocation", file.getParentFile().getAbsolutePath());
    return met;
  }
  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());
  }
  /**
   * parse the String message
   *
   * @return SIPHeader (Event object)
   * @throws SIPParseException if the message does not respect the spec.
   */
  public SIPHeader parse() throws ParseException {

    if (debug) dbg_enter("EventParser.parse");

    try {
      headerName(TokenTypes.EVENT);
      this.lexer.SPorHT();

      Event event = new Event();
      this.lexer.match(TokenTypes.ID);
      Token token = lexer.getNextToken();
      String value = token.getTokenValue();

      event.setEventType(value);
      super.parse(event);

      this.lexer.SPorHT();
      this.lexer.match('\n');

      return event;

    } catch (ParseException ex) {
      throw createParseException(ex.getMessage());
    } finally {
      if (debug) dbg_leave("EventParser.parse");
    }
  }
  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;
  }
  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());
    }
  }
Beispiel #24
0
  @Override
  public Object getValue() {
    try {
      field.commitEdit();
    } catch (ParseException e) {
      logger.error(e.getMessage(), e);
      Utils.showError(e);
      e.printStackTrace();
    }

    if (value instanceof Number) {
      NumberConverter nc =
          new NumberConverter(true, field.getValue()) {

            @Override
            protected Class<?> getDefaultType() {
              return value.getClass();
            }
          };

      return value.getClass().cast(nc.convert(value.getClass(), field.getValue()));
    } else {
      return field.getValue();
    }
  }
Beispiel #25
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());
    }
  }
  protected Receiver sendCmd(
      Receiver rcv, String cmd, String key, String opt, byte[] value, int casid)
      throws IOException {
    if (key.contains(" ")) {
      throw new IllegalArgumentException("Can't include space in a key.");
    }
    boolean retry;
    do {
      retry = false;
      Connection con = null;
      try {
        con = routing.getConnection(key);
        con.write(cmd, key, opt, value, casid);
        rcv.receive(con);
        routing.returnConnection(con);
      } catch (ParseException e) {
        routing.returnConnection(con);
        log.error("sendCmd(): " + e.getMessage());
        throw new RuntimeException(e);
      } catch (Exception e) {
        log.error("sendCmd(): " + e.getMessage());
        retry = true;
        log.debug("sendCmd(): retry=" + rcv.retry);
        routing.failCount(con);
        if (++rcv.retry >= maxRetry) {
          log.error("sendCmd(): Retry out");
          throw new IOException("Retry out", e);
        }
      }
    } while (retry);

    return rcv;
  }
  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());
  }
  /** Check CB values and the date (after today) */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse resp)
      throws ServletException, IOException {
    String numCB = request.getParameter("numCB");
    String cryptogramme = request.getParameter("cryptogramme");

    try {
      SimpleDateFormat formatter = new SimpleDateFormat("MM/yy");
      Date endValidation = formatter.parse(request.getParameter("endValidation"));

      Date today = new Date();

      if (numCB != null
          && cryptogramme != null
          && endValidation != null
          && today.compareTo(endValidation) < 0) {
        // paiement accepté //
        request.getSession().setAttribute("shoppingCart", new ArrayList<Product>());
        request.setAttribute(
            "paymentState",
            "Votre paiement a bien été effectué. Merci d'avoir utilisé cette application.");
        request.getRequestDispatcher("paymentFinished.jsp").forward(request, resp);
      } else {
        // paiement refusé //
        request.setAttribute("paymentState", "Votre paiement a été refusé.");
        request.getRequestDispatcher("paymentFinished.jsp").forward(request, resp);
      }

    } catch (ParseException ex) {
      System.err.println(ex.getMessage());
      resp.sendRedirect("payment");
    }
  }
Beispiel #29
0
  /**
   * Invalid Entry - Start Calculator
   *
   * @param jc parent
   * @param value value
   * @param format format
   * @param displayType display type
   * @param title title
   * @param operator optional math operator +-/*
   * @return value
   */
  public static String startCalculator(
      Container jc,
      String value,
      DecimalFormat format,
      int displayType,
      String title,
      char operator) {
    log.config("Value=" + value);
    BigDecimal startValue = new BigDecimal(0.0);
    try {
      if (value != null && value.length() > 0) {
        Number number = format.parse(value);
        startValue = new BigDecimal(number.toString());
      }
    } catch (ParseException pe) {
      log.info("InvalidEntry - " + pe.getMessage());
    }

    //	Find frame
    Frame frame = Env.getFrame(jc);
    //	Actual Call
    Calculator calc = new Calculator(frame, title, displayType, format, startValue);
    if ("*+-/%".indexOf(operator) > -1) calc.handleInput(operator);
    AEnv.showCenterWindow(frame, calc);
    BigDecimal result = calc.getNumber();
    log.config("Result=" + result);
    //
    calc = null;
    if (result != null) return format.format(result);
    else return value; // 	original value
  } //	startCalculator
Beispiel #30
0
 static {
   try {
     mlCollator = new RuleBasedCollator(MALAYALAM_COLLATION_RULES);
   } catch (ParseException pe) {
     Log.e(UCASort.MODULE_NAME, "Error : " + pe.getMessage());
   }
 }