Exemplo n.º 1
0
 private static int safelyConnect(String uri, HttpURLConnection connection) throws IOException {
   try {
     connection.connect();
   } catch (NullPointerException npe) {
     // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(npe.toString());
   } catch (IllegalArgumentException iae) {
     // Also seen this in the wild, not sure what to make of it. Probably a bad URL
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(iae.toString());
   } catch (SecurityException se) {
     // due to bad VPN settings?
     Log.w(TAG, "Restricted URI? " + uri);
     throw new IOException(se.toString());
   } catch (IndexOutOfBoundsException ioobe) {
     // Another Android problem?
     // https://groups.google.com/forum/?fromgroups#!topic/google-admob-ads-sdk/U-WfmYa9or0
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(ioobe.toString());
   }
   try {
     return connection.getResponseCode();
   } catch (NullPointerException npe) {
     // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(npe.toString());
   } catch (IllegalArgumentException iae) {
     // Again seen this in the wild for bad header fields in the server response! or bad reads
     Log.w(TAG, "Bad server status? " + uri);
     throw new IOException(iae.toString());
   }
 }
Exemplo n.º 2
0
  public static String CreateZip(String[] filesToZip, String zipFileName) {

    byte[] buffer = new byte[18024];

    try {

      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
      out.setLevel(Deflater.BEST_COMPRESSION);
      for (int i = 0; i < filesToZip.length; i++) {
        FileInputStream in = new FileInputStream(filesToZip[i]);
        String fileName = null;
        for (int X = filesToZip[i].length() - 1; X >= 0; X--) {
          if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') {
            fileName = filesToZip[i].substring(X + 1);
            break;
          } else if (X == 0) fileName = filesToZip[i];
        }
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
        out.closeEntry();
        in.close();
      }
      out.close();
    } catch (IllegalArgumentException e) {
      return "Failed to create zip: " + e.toString();
    } catch (FileNotFoundException e) {
      return "Failed to create zip: " + e.toString();
    } catch (IOException e) {
      return "Failed to create zip: " + e.toString();
    }
    return "Success";
  }
  /**
   * @tests java.text.AttributedString#AttributedString(AttributedCharacterIterator, int, int,
   *     AttributedCharacterIterator.Attribute[]) Test of method
   *     java.text.AttributedString#AttributedString(AttributedCharacterIterator, int, int,
   *     AttributedCharacterIterator.Attribute[]). Case 1: Try to consruct AttributedString. Case 2:
   *     Try to consruct AttributedString using incorrect beginIndex. Case 3: Try to consruct
   *     AttributedString using incorrect endIndex. Case 4: Try to consruct AttributedString using
   *     specified attributes.
   */
  public void
      test_ConstructorLAttributedCharacterIteratorII$Ljava_text_AttributedCharacterIterator$Attribute() {
    // case 1: Try to consruct AttributedString.
    try {
      new AttributedString(new testAttributedCharacterIterator(), 0, 0, null);
    } catch (Exception e) {
      fail("Unexpected exception " + e.toString());
    }

    // case 2: Try to consruct AttributedString using incorrect beginIndex.
    try {
      new AttributedString(new testAttributedCharacterIterator(), -1, 0, null);
      fail("Expected IllegalArgumentException was not thrown");
    } catch (IllegalArgumentException e) {
      // expected
    }

    // case 3: Try to consruct AttributedString using incorrect endIndex.
    try {
      new AttributedString(new testAttributedCharacterIterator(), 0, -1, null);
      fail("Expected IllegalArgumentException was not thrown");
    } catch (IllegalArgumentException e) {
      // expected
    }

    // case 4: Try to consruct AttributedString using specified attributes.
    try {
      AttributedCharacterIterator.Attribute[] attributes =
          new AttributedCharacterIterator.Attribute[1];
      attributes[0] = new TestAttributedCharacterIteratorAttribute("test");
      new AttributedString(new testAttributedCharacterIterator(), 0, 0, attributes);
    } catch (IllegalArgumentException e) {
      fail("Unexpected expected " + e.toString());
    }
  }
Exemplo n.º 4
0
  /**
   * Checks that we get an appropriate exception when storing an entity subclass instance, which
   * contains a secondary key, without registering the subclass up front. [#16399]
   */
  public void testPutEntitySubclassWithoutRegisterClass() throws DatabaseException {

    open();

    final PrimaryIndex<Long, Statement> pri = store.getPrimaryIndex(Long.class, Statement.class);

    final Transaction txn = txnBegin();
    pri.put(txn, new Statement(1));
    try {
      pri.put(txn, new ExtendedStatement(2, null));
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(
          expected.toString(),
          expected
              .getMessage()
              .contains(
                  "Entity subclasses defining a secondary key must be "
                      + "registered by calling EntityModel.registerClass or "
                      + "EntityStore.getSubclassIndex before storing an instance "
                      + "of the subclass: "
                      + ExtendedStatement.class.getName()));
    }
    txnAbort(txn);

    close();
  }
Exemplo n.º 5
0
 private void runGrantRevokePermission(boolean grant) {
   String pkg = nextArg();
   if (pkg == null) {
     System.err.println("Error: no package specified");
     showUsage();
     return;
   }
   String perm = nextArg();
   if (perm == null) {
     System.err.println("Error: no permission specified");
     showUsage();
     return;
   }
   try {
     if (grant) {
       mPm.grantPermission(pkg, perm);
     } else {
       mPm.revokePermission(pkg, perm);
     }
   } catch (RemoteException e) {
     System.err.println(e.toString());
     System.err.println(PM_NOT_RUNNING_ERR);
   } catch (IllegalArgumentException e) {
     System.err.println("Bad argument: " + e.toString());
     showUsage();
   } catch (SecurityException e) {
     System.err.println("Operation not allowed: " + e.toString());
   }
 }
Exemplo n.º 6
0
 /**
  * Calculate the milliseconds since 1970-01-01 (UTC) for the given date and time (in the specified
  * timezone).
  *
  * @param tz the timezone of the parameters, or null for the default timezone
  * @param year the absolute year (positive or negative)
  * @param month the month (1-12)
  * @param day the day (1-31)
  * @param hour the hour (0-23)
  * @param minute the minutes (0-59)
  * @param second the number of seconds (0-59)
  * @param millis the number of milliseconds
  * @return the number of milliseconds (UTC)
  */
 public static long getMillis(
     TimeZone tz, int year, int month, int day, int hour, int minute, int second, int millis) {
   try {
     return getTimeTry(false, tz, year, month, day, hour, minute, second, millis);
   } catch (IllegalArgumentException e) {
     // special case: if the time simply doesn't exist because of
     // daylight saving time changes, use the lenient version
     String message = e.toString();
     if (message.indexOf("HOUR_OF_DAY") > 0) {
       if (hour < 0 || hour > 23) {
         throw e;
       }
       return getTimeTry(true, tz, year, month, day, hour, minute, second, millis);
     } else if (message.indexOf("DAY_OF_MONTH") > 0) {
       int maxDay;
       if (month == 2) {
         maxDay = new GregorianCalendar().isLeapYear(year) ? 29 : 28;
       } else {
         maxDay = 30 + ((month + (month > 7 ? 1 : 0)) & 1);
       }
       if (day < 1 || day > maxDay) {
         throw e;
       }
       // DAY_OF_MONTH is thrown for years > 2037
       // using the timezone Brasilia and others,
       // for example for 2042-10-12 00:00:00.
       hour += 6;
       return getTimeTry(true, tz, year, month, day, hour, minute, second, millis);
     } else {
       return getTimeTry(true, tz, year, month, day, hour, minute, second, millis);
     }
   }
 }
Exemplo n.º 7
0
 /**
  * Execute Script Loads environment and saves result
  *
  * @return null or Exception
  */
 public Exception execute() {
   m_result = null;
   if (m_variable == null
       || m_variable.length() == 0
       || m_script == null
       || m_script.length() == 0) {
     IllegalArgumentException e = new IllegalArgumentException("No variable/script");
     log.config(e.toString());
     return e;
   }
   Interpreter i = new Interpreter();
   loadEnvironment(i);
   try {
     log.config(m_script);
     i.eval(m_script);
   } catch (Exception e) {
     log.config(e.toString());
     return e;
   }
   try {
     m_result = i.get(m_variable);
     log.config("Result (" + m_result.getClass().getName() + ") " + m_result);
   } catch (Exception e) {
     log.config("Result - " + e);
     if (e instanceof NullPointerException)
       e = new IllegalArgumentException("Result Variable not found - " + m_variable);
     return e;
   }
   return null;
 } //  execute
Exemplo n.º 8
0
 /**
  * Sets a field value for the given object.
  *
  * @param fieldClass the class that should be changed
  * @param fieldName the name of the field
  * @param value the value
  * @throws NoSuchFieldException when the field does not exist or could not be written
  */
 public static void setStaticField(Class fieldClass, String fieldName, Object value)
     throws NoSuchFieldException {
   try {
     Field field = null;
     while (field == null) {
       try {
         field = fieldClass.getDeclaredField(fieldName);
       } catch (NoSuchFieldException e) {
         fieldClass = fieldClass.getSuperclass();
         if (fieldClass == null) {
           throw e;
         }
         // System.out.println("trying parent class [" + instanceClass.getName() + "]");
       }
     }
     field.setAccessible(true);
     field.set(null, value);
   } catch (SecurityException e) {
     e.printStackTrace();
     throw new NoSuchFieldException("Unable to set field [" + fieldName + "]: " + e.toString());
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
     throw new NoSuchFieldException("Unable to set field [" + fieldName + "]: " + e.toString());
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     throw new NoSuchFieldException("Unable to set field [" + fieldName + "]: " + e.toString());
   }
 }
 public void testSameAggregationName() throws Exception {
   final String name = randomAsciiOfLengthBetween(1, 10);
   String source =
       JsonXContent.contentBuilder()
           .startObject()
           .startObject(name)
           .startObject("terms")
           .field("field", "a")
           .endObject()
           .endObject()
           .startObject(name)
           .startObject("terms")
           .field("field", "b")
           .endObject()
           .endObject()
           .endObject()
           .string();
   try {
     XContentParser parser = XContentFactory.xContent(source).createParser(source);
     QueryParseContext parseContext =
         new QueryParseContext(queriesRegistry, parser, parseFieldMatcher);
     assertSame(XContentParser.Token.START_OBJECT, parser.nextToken());
     aggParsers.parseAggregators(parseContext);
     fail();
   } catch (IllegalArgumentException e) {
     assertThat(
         e.toString(),
         containsString("Two sibling aggregations cannot have the same name: [" + name + "]"));
   }
 }
Exemplo n.º 10
0
  public void TestDefaultRuleBasedSentenceIteration() {
    logln("Testing the RBBI for sentence iteration using default rules");
    RuleBasedBreakIterator rbbi = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();

    // fetch the rules used to create the above RuleBasedBreakIterator
    String defaultRules = rbbi.toString();
    RuleBasedBreakIterator sentIterDefault = null;
    try {
      sentIterDefault = new RuleBasedBreakIterator(defaultRules);
    } catch (IllegalArgumentException iae) {
      errln(
          "ERROR: failed construction in TestDefaultRuleBasedSentenceIteration()" + iae.toString());
    }

    List<String> sentdata = new ArrayList<String>();
    sentdata.add("(This is it.) ");
    sentdata.add("Testing the sentence iterator. ");
    sentdata.add("\"This isn\'t it.\" ");
    sentdata.add("Hi! ");
    sentdata.add("This is a simple sample sentence. ");
    sentdata.add("(This is it.) ");
    sentdata.add("This is a simple sample sentence. ");
    sentdata.add("\"This isn\'t it.\" ");
    sentdata.add("Hi! ");
    sentdata.add("This is a simple sample sentence. ");
    sentdata.add("It does not have to make any sense as you can see. ");
    sentdata.add("Nel mezzo del cammin di nostra vita, mi ritrovai in una selva oscura. ");
    sentdata.add("Che la dritta via aveo smarrita. ");

    generalIteratorTest(sentIterDefault, sentdata);
  }
Exemplo n.º 11
0
 private void runSetPermissionEnforced() {
   final String permission = nextArg();
   if (permission == null) {
     System.err.println("Error: no permission specified");
     showUsage();
     return;
   }
   final String enforcedRaw = nextArg();
   if (enforcedRaw == null) {
     System.err.println("Error: no enforcement specified");
     showUsage();
     return;
   }
   final boolean enforced = Boolean.parseBoolean(enforcedRaw);
   try {
     mPm.setPermissionEnforced(permission, enforced);
   } catch (RemoteException e) {
     System.err.println(e.toString());
     System.err.println(PM_NOT_RUNNING_ERR);
   } catch (IllegalArgumentException e) {
     System.err.println("Bad argument: " + e.toString());
     showUsage();
   } catch (SecurityException e) {
     System.err.println("Operation not allowed: " + e.toString());
   }
 }
Exemplo n.º 12
0
 @Test
 public void testAddPredicate() {
   Assert.assertEquals(
       SqlQueryUtils.addPredicate("SELECT foo FROM bar", "foo != 'blah'"),
       "SELECT foo FROM bar where (foo != 'blah')");
   Assert.assertEquals(
       SqlQueryUtils.addPredicate(
           "SELECT foo,whereTo FROM bar WHERE whereTo==foo", "foo != 'blah'"),
       "SELECT foo,whereTo FROM bar WHERE whereTo==foo and (foo != 'blah')");
   Assert.assertEquals(
       SqlQueryUtils.addPredicate(
           "SELECT foo,andThis FROM bar WHERE andThis>foo", "foo != 'blah'"),
       "SELECT foo,andThis FROM bar WHERE andThis>foo and (foo != 'blah')");
   Assert.assertEquals(
       SqlQueryUtils.addPredicate("SELECT foo FROM bar", null), "SELECT foo FROM bar");
   Assert.assertEquals(
       SqlQueryUtils.addPredicate("SELECT foo FROM bar", ""), "SELECT foo FROM bar");
   try {
     SqlQueryUtils.addPredicate("SELECT foo,foo1 WHERE foo1==foo", "foo != 'blah'");
   } catch (IllegalArgumentException e) {
     Assert.assertTrue(e.toString().contains("'from'"));
   }
   try {
     SqlQueryUtils.addPredicate(
         "SELECT foo,foo1 FROM blah WHERE foo1==foo ORDER by foo", "foo != 'blah'");
   } catch (IllegalArgumentException e) {
     Assert.assertTrue(e.toString().contains("'order by'"));
   }
   try {
     SqlQueryUtils.addPredicate(
         "SELECT foo,foo1 FROM blah WHERE foo1==foo GROUP BY foo", "foo != 'blah'");
   } catch (IllegalArgumentException e) {
     Assert.assertTrue(e.toString().contains("'group by'"));
   }
   try {
     SqlQueryUtils.addPredicate(
         "SELECT foo,foo1 FROM blah WHERE foo1==foo HAVING foo1 is null", "foo != 'blah'");
   } catch (IllegalArgumentException e) {
     Assert.assertTrue(e.toString().contains("'having'"));
   }
   try {
     SqlQueryUtils.addPredicate(
         "SELECT foo,foo1 FROM blah WHERE foo1==foo LIMIT 10", "foo != 'blah'");
   } catch (IllegalArgumentException e) {
     Assert.assertTrue(e.toString().contains("'limit'"));
   }
 }
Exemplo n.º 13
0
  public void myPlay(String url, String src) {
    if (url == null || url.length() == 0) {
      Toast.makeText(mContext, "无播放地址", Toast.LENGTH_SHORT).show();
      return;
    }

    if (!mLoading.isShowing()) mLoading.show();
    mPlayPath = url;
    Logger.LOGD(TAG, "begin to play:" + mPlayPath + ", " + src);

    if (mPlayer == null) {
      Logger.LOGD(TAG, "mPlayer is null!!");
      initPlayer();
    }
    try {
      Logger.LOGD(TAG, "-=-=-=-=-=-= -=-=-reset-=--= -=-==-");
      mPlayer.reset();
      // mPlayer.stop();

      Logger.LOGD("mUaMap.size= " + mUaMap.size() + ", value: " + mUaMap.get(src));
      Map<String, String> headers = new HashMap<String, String>();
      if (mUaMap.get(src) != null) {
        Logger.LOGD("=== had  headers ====");

        String headinfo = mUaMap.get(src);
        String[] grp = headinfo.split("\\$\\$");
        if (grp != null) {
          for (String items : grp) {
            String[] item = items.split("\\:");
            if (item != null && item.length == 2) {
              Logger.LOGD("Add header: " + item[0] + "=" + item[1]);
              headers.put(item[0], item[1]);
            }
          }
        }
      }

      if (headers.size() > 0) {
        Logger.LOGD("use header");
        mPlayer.setDataSource(Player.this, Uri.parse(url), headers);
      } else {
        Logger.LOGD("use no-header");
        mPlayer.setDataSource(url);
      }
      mPlayer.prepareAsync();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      Logger.LOGD(TAG, e.toString());
    } catch (IllegalStateException e) {
      e.printStackTrace();
      Logger.LOGD(TAG, e.toString());
    } catch (IOException e) {
      e.printStackTrace();
      Logger.LOGD(TAG, e.toString());
    }
  }
Exemplo n.º 14
0
 //
 // called by the .enclosing directive
 //
 void setEnclosingMethod(String str) {
   try {
     if (str.indexOf("(") != -1) { // full method description
       String[] split = ScannerUtils.splitClassMethodSignature(str);
       class_env.setEnclosingMethod(split[0], split[1], split[2]);
     } else // just a class name
     class_env.setEnclosingMethod(str, null, null);
   } catch (IllegalArgumentException e) {
     report_error(e.toString());
   }
 }
 @Test
 public void testThrowsIfUnmatchedSubstitutions() throws Exception {
   String pattern = "nothere=${nothere}";
   BasicDownloadRequirement req = new BasicDownloadRequirement(driver);
   try {
     String result = DownloadSubstituters.substitute(req, pattern);
     fail("Should have failed, but got " + result);
   } catch (IllegalArgumentException e) {
     if (!e.toString().contains("${nothere}")) throw e;
   }
 }
  /**
   * Attempts to open a connection using the Uri supplied for connection parameters. Will attempt an
   * SSL connection if indicated.
   */
  public void open() throws MessagingException, CertificateValidationException {
    if (MailActivityEmail.DEBUG) {
      LogUtils.d(
          Logging.LOG_TAG,
          "*** " + mDebugLabel + " open " + getHost() + ":" + String.valueOf(getPort()));
    }

    try {
      SocketAddress socketAddress = new InetSocketAddress(getHost(), getPort());
      if (canTrySslSecurity()) {
        mSocket =
            SSLUtils.getSSLSocketFactory(mContext, mHostAuth, canTrustAllCertificates())
                .createSocket();
      } else {
        mSocket = new Socket();
      }
      mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT);
      // After the socket connects to an SSL server, confirm that the hostname is as expected
      if (canTrySslSecurity() && !canTrustAllCertificates()) {
        verifyHostname(mSocket, getHost());
      }
      mIn = new BufferedInputStream(mSocket.getInputStream(), 1024);
      mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512);
      mSocket.setSoTimeout(SOCKET_READ_TIMEOUT);
    } catch (SSLException e) {
      if (MailActivityEmail.DEBUG) {
        LogUtils.d(Logging.LOG_TAG, e.toString());
      }
      throw new CertificateValidationException(e.getMessage(), e);
    } catch (IOException ioe) {
      if (MailActivityEmail.DEBUG) {
        LogUtils.d(Logging.LOG_TAG, ioe.toString());
      }
      throw new MessagingException(MessagingException.IOERROR, ioe.toString());
    } catch (IllegalArgumentException iae) {
      if (MailActivityEmail.DEBUG) {
        LogUtils.d(Logging.LOG_TAG, iae.toString());
      }
      throw new MessagingException(MessagingException.UNSPECIFIED_EXCEPTION, iae.toString());
    }
  }
Exemplo n.º 17
0
 private void runTrimCaches() {
   String size = nextArg();
   if (size == null) {
     System.err.println("Error: no size specified");
     showUsage();
     return;
   }
   int len = size.length();
   long multiplier = 1;
   if (len > 1) {
     char c = size.charAt(len - 1);
     if (c == 'K' || c == 'k') {
       multiplier = 1024L;
     } else if (c == 'M' || c == 'm') {
       multiplier = 1024L * 1024L;
     } else if (c == 'G' || c == 'g') {
       multiplier = 1024L * 1024L * 1024L;
     } else {
       System.err.println("Invalid suffix: " + c);
       showUsage();
       return;
     }
     size = size.substring(0, len - 1);
   }
   long sizeVal;
   try {
     sizeVal = Long.parseLong(size) * multiplier;
   } catch (NumberFormatException e) {
     System.err.println("Error: expected number at: " + size);
     showUsage();
     return;
   }
   ClearDataObserver obs = new ClearDataObserver();
   try {
     mPm.freeStorageAndNotify(sizeVal, obs);
     synchronized (obs) {
       while (!obs.finished) {
         try {
           obs.wait();
         } catch (InterruptedException e) {
         }
       }
     }
   } catch (RemoteException e) {
     System.err.println(e.toString());
     System.err.println(PM_NOT_RUNNING_ERR);
   } catch (IllegalArgumentException e) {
     System.err.println("Bad argument: " + e.toString());
     showUsage();
   } catch (SecurityException e) {
     System.err.println("Operation not allowed: " + e.toString());
   }
 }
Exemplo n.º 18
0
  /** @param configFile configuration file */
  private void parseConfigFile(final InputStream configFile) {

    String ribElementName;
    String ribElementClassName;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(configFile);
    } catch (ParserConfigurationException pce) {
      logger.error(pce.toString());
    } catch (IOException ioe) {
      logger.error(ioe.toString());
    } catch (SAXException spe) {
      logger.error(spe.toString());
    } catch (IllegalArgumentException iae) {
      logger.error(iae.toString());
    }

    // Get the root
    Element root = document.getDocumentElement();

    // Get all the packages
    NodeList ribPackages = root.getElementsByTagName("package");

    // Loop through all the packages
    for (int i = 0; i < ribPackages.getLength(); i++) {

      Node ribPackage = ribPackages.item(i);

      NodeList ribElements = ribPackage.getChildNodes();
      String packageName = ribPackage.getAttributes().getNamedItem("name").getNodeValue();

      logger.debug("Package: " + packageName);

      // Loop through all elements in this package
      for (int x = 0; x < ribElements.getLength(); x++) {

        // Get values
        Node ribElement = ribElements.item(x);

        if (ribElement.getNodeType() == Node.ELEMENT_NODE) {
          NamedNodeMap ribElementAttributes = ribElement.getAttributes();
          ribElementName = ribElementAttributes.getNamedItem("name").getNodeValue();
          ribElementClassName = ribElementAttributes.getNamedItem("classname").getNodeValue();
          rib.put(ribElementName, packageName + "." + ribElementClassName);
          logger.debug("Class name: " + ribElementClassName);
        }
      }
    }
  }
Exemplo n.º 19
0
  public void TestDefaultRuleBasedWordIteration() {
    logln("Testing the RBBI for word iteration using default rules");
    RuleBasedBreakIterator rbbi = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
    // fetch the rules used to create the above RuleBasedBreakIterator
    String defaultRules = rbbi.toString();

    RuleBasedBreakIterator wordIterDefault = null;
    try {
      wordIterDefault = new RuleBasedBreakIterator(defaultRules);
    } catch (IllegalArgumentException iae) {
      errln(
          "ERROR: failed construction in TestDefaultRuleBasedWordIteration() -- custom rules"
              + iae.toString());
    }

    List<String> worddata = new ArrayList<String>();
    worddata.add("Write");
    worddata.add(" ");
    worddata.add("wordrules");
    worddata.add(".");
    worddata.add(" ");
    // worddata.add("alpha-beta-gamma");
    worddata.add(" ");
    worddata.add("\u092f\u0939");
    worddata.add(" ");
    worddata.add("\u0939\u093f" + halfNA + "\u0926\u0940");
    worddata.add(" ");
    worddata.add("\u0939\u0948");
    // worddata.add("\u0964"); //danda followed by a space
    worddata.add(" ");
    worddata.add("\u0905\u093e\u092a");
    worddata.add(" ");
    worddata.add("\u0938\u093f\u0916\u094b\u0917\u0947");
    worddata.add("?");
    worddata.add(" ");
    worddata.add("\r");
    worddata.add("It's");
    worddata.add(" ");
    // worddata.add("$30.10");
    worddata.add(" ");
    worddata.add(" ");
    worddata.add("Badges");
    worddata.add("?");
    worddata.add(" ");
    worddata.add("BADGES");
    worddata.add("!");
    worddata.add("1000,233,456.000");
    worddata.add(" ");

    generalIteratorTest(wordIterDefault, worddata);
  }
Exemplo n.º 20
0
 /**
  * Performs the <i>Active Authentication</i> protocol.
  *
  * @param publicKey the public key to use (usually read from the card)
  * @param digestAlgorithm the digest algorithm to use, or null
  * @param signatureAlgorithm signature algorithm
  * @param challenge challenge
  * @return a boolean indicating whether the card was authenticated
  * @throws CardServiceException on error
  */
 public byte[] doAA(
     PublicKey publicKey, String digestAlgorithm, String signatureAlgorithm, byte[] challenge)
     throws CardServiceException {
   try {
     if (challenge == null || challenge.length != 8) {
       throw new IllegalArgumentException("AA failed: bad challenge");
     }
     byte[] response = sendInternalAuthenticate(wrapper, challenge);
     return response;
   } catch (IllegalArgumentException iae) {
     LOGGER.severe("Exception: " + iae.getMessage());
     throw new CardServiceException(iae.toString());
   }
 }
 public void TestBadObjectError() {
   Runtime r = Runtime.getRuntime();
   DurationFormat df = DurationFormat.getInstance(new ULocale("en"));
   String output = null;
   try {
     output = df.format(r);
     errln(
         "FAIL: did NOT get IllegalArgumentException! Should have. Formatted Runtime as "
             + output
             + " ???");
   } catch (IllegalArgumentException iae) {
     logln("PASS: expected: Caught iae: " + iae.toString());
   }
   // try a second time, because it is a different code path for java < 1.5
   try {
     output = df.format(r);
     errln(
         "FAIL: [#2] did NOT get IllegalArgumentException! Should have. Formatted Runtime as "
             + output
             + " ???");
   } catch (IllegalArgumentException iae) {
     logln("PASS: [#2] expected: Caught iae: " + iae.toString());
   }
 }
Exemplo n.º 22
0
  private void pause() {
    Log.d(TAG, "Pausing Location sensor");

    removeLocationListener();
    try {
      getContext().unregisterReceiver(locationReceiver);
    } catch (IllegalArgumentException ex) {
      Log.e(TAG, ex.toString());
    }
    Sensor.setSensorStatus(Sensor.SENSOR_LOCATION, Sensor.SENSOR_PAUSED);
    refreshStatus();

    setRunning(false);

    Log.d(TAG, "Pausing Location sensor [done]");
  }
Exemplo n.º 23
0
  private void updateSongSummary() {
    if (null == songUri) {
      return;
    }

    // assume external storage because audio files are not tied
    // to a specific application and should be world-readable and exportable
    Uri contentUri = Audio.Media.EXTERNAL_CONTENT_URI;

    String[] columns = {
      Audio.AudioColumns.ARTIST, Audio.AudioColumns.ALBUM,
      Audio.AudioColumns.DURATION, Audio.AudioColumns.TITLE
    };

    String whereClause = BaseColumns._ID + "=?";

    String[] selectArgs = {songUri.getLastPathSegment()}; // {"LIMIT 1"}; ?

    Cursor cursor = managedQuery(contentUri, columns, whereClause, selectArgs, null);

    if (cursor.moveToFirst()) {

      String artist, album, title;
      long duration;

      try {
        artist = getColumnStringValue(cursor, Audio.AudioColumns.ARTIST);
        album = getColumnStringValue(cursor, Audio.AudioColumns.ALBUM);
        title = getColumnStringValue(cursor, Audio.AudioColumns.TITLE);

        duration = cursor.getLong(cursor.getColumnIndexOrThrow(Audio.AudioColumns.DURATION));

        StringBuilder builder = new StringBuilder();

        builder.append(title).append('\n');
        builder.append(artist).append('\n');
        builder.append(album).append('\n');

        addMinSecString(builder, duration);

        mSongPref.setSummary(builder.toString());
      } catch (IllegalArgumentException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
      }
    }
  }
Exemplo n.º 24
0
 protected void actionAdjustment() {
   String result =
       (String) JOptionPane.showInputDialog(this, "Enter an adjustment", "0 00:00:00.000");
   if (result != null && !result.isEmpty()) {
     try {
       Period adjustment = format_short.parsePeriod(result);
       DateTime start = new DateTime();
       DateTime end = start.plus(adjustment);
       TimeSpan ts = new TimeSpan(start, end);
       times.add(ts);
       period = period.plus(adjustment);
       updateTimes();
     } catch (IllegalArgumentException ex) {
       JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
     }
   }
 }
Exemplo n.º 25
0
  @Override
  public Object getObject() {
    if (StringUtil.isEmpty(value)) {
      return null;
    }

    // discover the fromValue Method
    try {
      Method valueOfMethod = type.getMethod("fromValue", new Class[] {String.class});
      return valueOfMethod.invoke(null, new Object[] {value});

    } catch (NoSuchMethodException e) {
      // do nothing, check valueOf method
    } catch (IllegalArgumentException e) {
      throw new IllegalStateException(e.toString());
    } catch (IllegalAccessException e) {
      throw new IllegalStateException(e.toString());
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof RuntimeException) {
        throw (RuntimeException) e.getTargetException();
      }
    }

    // backwards compability, check valueOf method to support
    // "simple" enums without value object
    try {
      Method valueOfMethod = type.getMethod("valueOf", new Class[] {String.class});
      return valueOfMethod.invoke(null, new Object[] {value});

    } catch (IllegalAccessException e) {
      throw new IllegalStateException(e.toString());
    } catch (InvocationTargetException e) {
      if (e.getTargetException() instanceof RuntimeException) {
        throw (RuntimeException) e.getTargetException();
      }
    } catch (NoSuchMethodException e) {
      String err =
          type.getName()
              + " does not contain the required method: public static "
              + type.getName()
              + " valueOf(String);";
      throw new IllegalArgumentException(err);
    }

    return value;
  }
Exemplo n.º 26
0
  public void TestDefaultRuleBasedLineIteration() {
    logln("Testing the RBBI for line iteration using default rules");
    RuleBasedBreakIterator rbbi = (RuleBasedBreakIterator) RuleBasedBreakIterator.getLineInstance();
    // fetch the rules used to create the above RuleBasedBreakIterator
    String defaultRules = rbbi.toString();
    RuleBasedBreakIterator lineIterDefault = null;
    try {
      lineIterDefault = new RuleBasedBreakIterator(defaultRules);
    } catch (IllegalArgumentException iae) {
      errln("ERROR: failed construction in TestDefaultRuleBasedLineIteration()" + iae.toString());
    }

    List<String> linedata = new ArrayList<String>();
    linedata.add("Multi-");
    linedata.add("Level ");
    linedata.add("example ");
    linedata.add("of ");
    linedata.add("a ");
    linedata.add("semi-");
    linedata.add("idiotic ");
    linedata.add("non-");
    linedata.add("sensical ");
    linedata.add("(non-");
    linedata.add("important) ");
    linedata.add("sentence. ");

    linedata.add("Hi  ");
    linedata.add("Hello ");
    linedata.add("How\n");
    linedata.add("are\r");
    linedata.add("you" + kLineSeparator);
    linedata.add("fine.\t");
    linedata.add("good.  ");

    linedata.add("Now\r");
    linedata.add("is\n");
    linedata.add("the\r\n");
    linedata.add("time\n");
    linedata.add("\r");
    linedata.add("for\r");
    linedata.add("\r");
    linedata.add("all");

    generalIteratorTest(lineIterDefault, linedata);
  }
Exemplo n.º 27
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
      return;
    }
    Iterator<String> pathComponents = SLASH.split(pathInfo).iterator();
    String userID;
    String itemID;
    try {
      userID = pathComponents.next();
      itemID = pathComponents.next();
    } catch (NoSuchElementException nsee) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
      return;
    }
    if (pathComponents.hasNext()) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Path too long");
      return;
    }

    userID = unescapeSlashHack(userID);
    itemID = unescapeSlashHack(itemID);

    OryxRecommender recommender = getRecommender();
    try {
      output(
          request,
          response,
          recommender.recommendedBecause(userID, itemID, getNumResultsToFetch(request)));
    } catch (NoSuchUserException nsue) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, nsue.toString());
    } catch (NoSuchItemException nsie) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, nsie.toString());
    } catch (NotReadyException nre) {
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, nre.toString());
    } catch (IllegalArgumentException iae) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
    } catch (UnsupportedOperationException uoe) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, uoe.toString());
    }
  }
 private void invokeMethod(
     final Object theObject, final Method theMethod, final Object[] theParam) {
   try {
     if (theParam[0] == null) {
       theMethod.invoke(theObject, new Object[0]);
     } else {
       theMethod.invoke(theObject, theParam);
     }
   } catch (IllegalArgumentException e) {
     ControlP5.logger().warning(e.toString());
     /** TODO thrown when plugging a String method/field. */
   } catch (IllegalAccessException e) {
     printMethodError(theMethod, e);
   } catch (InvocationTargetException e) {
     printMethodError(theMethod, e);
   } catch (NullPointerException e) {
     printMethodError(theMethod, e);
   }
 }
Exemplo n.º 29
0
  @Override
  protected void onLoaded(boolean success) {
    try {

      if (success) {
        if (Preferences.isCheckinEnabled == 1) {
          toastLong(R.string.checkin_is_enabled);
          goToCheckins();
        } else {
          goToReports();
        }

      } else {
        toastLong(R.string.failed);
      }
    } catch (IllegalArgumentException e) {
      log(e.toString());
    }
  }
Exemplo n.º 30
0
 private void launchAgentFromClassInfo(String resourceClassNames) throws ConfigurationException {
   String[] names = resourceClassNames.split("\\|");
   for (String name : names) {
     Class<?> impl;
     try {
       impl = Class.forName(name);
       final Constructor<?> constructor = impl.getDeclaredConstructor();
       constructor.setAccessible(true);
       ServerResource resource = (ServerResource) constructor.newInstance();
       launchAgent(getNextAgentId(), resource);
     } catch (final ClassNotFoundException e) {
       throw new ConfigurationException(
           "Resource class not found: " + name + " due to: " + e.toString());
     } catch (final SecurityException e) {
       throw new ConfigurationException(
           "Security excetion when loading resource: " + name + " due to: " + e.toString());
     } catch (final NoSuchMethodException e) {
       throw new ConfigurationException(
           "Method not found excetion when loading resource: "
               + name
               + " due to: "
               + e.toString());
     } catch (final IllegalArgumentException e) {
       throw new ConfigurationException(
           "Illegal argument excetion when loading resource: "
               + name
               + " due to: "
               + e.toString());
     } catch (final InstantiationException e) {
       throw new ConfigurationException(
           "Instantiation excetion when loading resource: " + name + " due to: " + e.toString());
     } catch (final IllegalAccessException e) {
       throw new ConfigurationException(
           "Illegal access exception when loading resource: " + name + " due to: " + e.toString());
     } catch (final InvocationTargetException e) {
       throw new ConfigurationException(
           "Invocation target exception when loading resource: "
               + name
               + " due to: "
               + e.toString());
     }
   }
 }