Java Code Examples for org.apache.commons.codec.DecoderException

The following examples show how to use org.apache.commons.codec.DecoderException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static byte[] getAvatarBytesFromAddress(ContentResolver cr, String address) throws DecoderException {

        String[] projection =  {Imps.Avatars.DATA};
        String[] args = {address};
        String query = Imps.Avatars.CONTACT + " LIKE ?";
        Cursor cursor = cr.query(Imps.Avatars.CONTENT_URI, projection,
                query, args, Imps.Avatars.DEFAULT_SORT_ORDER);

        byte[] data = null;

        if (cursor != null) {
            if (cursor.moveToFirst())
                data = cursor.getBlob(0);

            cursor.close();
        }

        return data;

    }
 
Example 2
Source Project: text_converter   Source File: FHex.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts a String or an array of character bytes representing hexadecimal values into an array of bytes of those
 * same values. The returned array will be half the length of the passed String or array, as it takes two characters
 * to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.
 *
 * @param object
 *            A String, ByteBuffer, byte[], or an array of character bytes containing hexadecimal digits
 * @return A byte array containing binary data decoded from the supplied byte array (representing characters).
 * @throws DecoderException
 *             Thrown if an odd number of characters is supplied to this function or the object is not a String or
 *             char[]
 * @see #decodeHex(char[])
 */
@Override
public Object decode(final Object object) throws DecoderException {
    if (object instanceof String) {
        return decode(((String) object).toCharArray());
    } else if (object instanceof byte[]) {
        return decode((byte[]) object);
    } else if (object instanceof ByteBuffer) {
        return decode((ByteBuffer) object);
    } else {
        try {
            return decodeHex((char[]) object);
        } catch (final ClassCastException e) {
            throw new DecoderException(e.getMessage(), e);
        }
    }
}
 
Example 3
Source Project: appengine-tck   Source File: LoggingTestBase.java    License: Apache License 2.0 6 votes vote down vote up
protected static WebArchive getDefaultDeployment(TestContext context) {
    context.setAppEngineWebXmlFile("appengine-web-with-logging-properties.xml");
    WebArchive war = getTckDeployment(context);
    war.addClasses(LoggingTestBase.class, TestBase.class)
        // classes for Base64.isBase64()
        .addClasses(Base64.class, BaseNCodec.class)
        .addClasses(BinaryEncoder.class, Encoder.class)
        .addClasses(BinaryDecoder.class, Decoder.class)
        .addClasses(EncoderException.class, DecoderException.class)
        .addAsWebInfResource("currentTimeUsec.jsp")
        .addAsWebInfResource("doNothing.jsp")
        .addAsWebInfResource("storeTestData.jsp")
        .addAsWebInfResource("throwException.jsp")
        .addAsWebInfResource("log4j-test.properties")
        .addAsWebInfResource("logging-all.properties");
    return war;
}
 
Example 4
Source Project: elexis-3-core   Source File: UserService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void setPasswordForUser(IUser user, String password){
	if (user != null) {
		PasswordEncryptionService pes = new PasswordEncryptionService();
		try {
			String salt = pes.generateSaltAsHexString();
			String hashed_pw = pes.getEncryptedPasswordAsHexString(password, salt);
			user.setSalt(salt);
			user.setHashedPassword(hashed_pw);
			modelService.save(user);
		} catch (NoSuchAlgorithmException | InvalidKeySpecException | DecoderException e) {
			LoggerFactory.getLogger(getClass()).warn("Error setting password for user [{}].",
				user.getLabel(), e);
		}
	}
	
}
 
Example 5
Source Project: elexis-3-core   Source File: UserService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean verifyPassword(IUser user, char[] attemptedPassword){
	boolean ret = false;
	
	if (user != null) {
		PasswordEncryptionService pes = new PasswordEncryptionService();
		try {
			ret = pes.authenticate(attemptedPassword, user.getHashedPassword(), user.getSalt());
		} catch (NoSuchAlgorithmException | InvalidKeySpecException | DecoderException e) {
			LoggerFactory.getLogger(getClass()).warn("Error verifying password for user [{}].",
				user.getLabel(), e);
		}
	}
	
	return ret;
}
 
Example 6
Source Project: GizwitsBLE   Source File: CharacteristicActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
	if (v.getId() == R.id.btn_read) {
		mBle.requestReadCharacteristic(mDeviceAddress, mCharacteristic);
	} else if (v.getId() == R.id.btn_notify) {
		if (mNotifyStarted) {
			mBle.requestStopNotification(mDeviceAddress,
					mCharacteristic);
		} else {
			mBle.requestCharacteristicNotification(mDeviceAddress,
					mCharacteristic);
		}
	} else if (v.getId() == R.id.btn_indicate) {
		mBle.requestIndication(mDeviceAddress, mCharacteristic);
	} else if (v.getId() == R.id.btn_write) {
		String val = et_hex.getText().toString();
		try {
			byte[] data = Hex.decodeHex(val.toCharArray());
			mCharacteristic.setValue(data);
			mBle.requestWriteCharacteristic(mDeviceAddress,
					mCharacteristic, "");
		} catch (DecoderException e) {
			e.printStackTrace();
		}
	}
}
 
Example 7
Source Project: elexis-3-core   Source File: User.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IUser login(String username, char[] password){
	if (isDeleted() || !username.equals(getUsername()) || !isActive()) {
		return null;
	}
	
	try {
		if (!new PasswordEncryptionService().authenticate(password, getHashedPassword(),
			getSalt())) {
			return null;
		}
	} catch (NoSuchAlgorithmException | InvalidKeySpecException | DecoderException e) {
		LoggerFactory.getLogger(IUser.class).error("Error verifying password", e);
	}
	return this;
}
 
Example 8
Source Project: tus-java-server   Source File: UploadId.java    License: MIT License 6 votes vote down vote up
/**
 * Create a new {@link UploadId} instance based on the provided object using it's toString method.
 * @param inputObject The object to use for constructing the ID
 */
public UploadId(Serializable inputObject) {
    String inputValue = (inputObject == null ? null : inputObject.toString());
    Validate.notBlank(inputValue, "The upload ID value cannot be blank");

    this.originalObject = inputObject;
    URLCodec codec = new URLCodec();
    //Check if value is not encoded already
    try {
        if (inputValue != null && inputValue.equals(codec.decode(inputValue, UPLOAD_ID_CHARSET))) {
            this.urlSafeValue = codec.encode(inputValue, UPLOAD_ID_CHARSET);
        } else {
            //value is already encoded, use as is
            this.urlSafeValue = inputValue;
        }
    } catch (DecoderException | UnsupportedEncodingException e) {
        log.warn("Unable to URL encode upload ID value", e);
        this.urlSafeValue = inputValue;
    }
}
 
Example 9
Source Project: hbase-tools   Source File: Split.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List<byte[]>> split(Set<String> tableSet, Args args) throws IOException, DecoderException {
    Map<String, List<byte[]>> splitMap = new HashMap<>();

    for (String tableName : tableSet) {
        String ruleArg = ((String) args.getOptionSet().nonOptionArguments().get(3)).toLowerCase();
        SplitRule splitRule = SplitRule.valueOf(ruleArg);

        String numRegionsArg = (String) args.getOptionSet().nonOptionArguments().get(4);
        int numCardinality = 0;
        if (args.getOptionSet().nonOptionArguments().size() >= 6)
            numCardinality = Integer.valueOf((String) args.getOptionSet().nonOptionArguments().get(5));
        List<byte[]> splitList = splitRule.split(Integer.valueOf(numRegionsArg), numCardinality);
        splitMap.put(tableName, splitList);

        System.out.println("Table \"" + tableName + "\" on \"" + args.getZookeeperQuorum() + "\" will be split into " + (splitList.size() + 1) + " regions by " + splitRule.name() + " rule.");
    }

    return splitMap;
}
 
Example 10
Source Project: onedev   Source File: ParamSupply.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
public static Class<? extends Serializable> loadBeanClass(String className) {
	if (className.startsWith(PARAM_BEAN_PREFIX)) {
		byte[] bytes;
		try {
			bytes = Hex.decodeHex(className.substring(PARAM_BEAN_PREFIX.length()+1).toCharArray());
		} catch (DecoderException e) {
			throw new RuntimeException(e);
		}
		List<ParamSpec> paramSpecs = (List<ParamSpec>) SerializationUtils.deserialize(bytes);
		return defineBeanClass(paramSpecs);
	} else {
		return null;
	}
}
 
Example 11
Source Project: htmlunit   Source File: DataUrlDecoder.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] decodeUrl(final byte[] bytes) throws DecoderException {
    if (bytes == null) {
        return null;
    }
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    for (int i = 0; i < bytes.length; i++) {
        final int b = bytes[i];
        if (b == '%') {
            try {
                final int u = digit16(bytes[++i]);
                final int l = digit16(bytes[++i]);
                buffer.write((char) ((u << 4) + l));
            }
            catch (final ArrayIndexOutOfBoundsException e) {
                throw new DecoderException("Invalid URL encoding: ", e);
            }
        }
        else {
            buffer.write(b);
        }
    }
    return buffer.toByteArray();
}
 
Example 12
Source Project: df_data_service   Source File: UnitTestSuiteFlink.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, DecoderException {

        final String STATIC_USER_SCHEMA = "{"
                + "\"type\":\"record\","
                + "\"name\":\"myrecord\","
                + "\"fields\":["
                + "  { \"name\":\"symbol\", \"type\":\"string\" },"
                + "  { \"name\":\"name\", \"type\":\"string\" },"
                + "  { \"name\":\"exchangecode\", \"type\":\"string\" }"
                + "]}";

        System.out.println(SchemaRegistryClient.getSchemaFromRegistry ("http://localhost:8081", "test-value", "latest"));
        //testFlinkAvroSerDe("http://localhost:18081");
        //testFlinkAvroSerDe("http://localhost:8081");
        testFlinkAvroSQLJson();
        //testFlinkRun();
        //testFlinkSQL();
        //testFlinkAvroSQL();
        //testFlinkAvroSQLWithStaticSchema();
        //testFlinkAvroScriptWithStaticSchema();
    }
 
Example 13
Source Project: localization_nifi   Source File: ScryptCipherProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Translates a salt from the mcrypt format {@code $n$r$p$salt_hex} to the Java scrypt format {@code $s0$params$saltBase64}.
 *
 * @param mcryptSalt the mcrypt-formatted salt string
 * @return the formatted salt to use with Java Scrypt
 */
public String translateSalt(String mcryptSalt) {
    if (StringUtils.isEmpty(mcryptSalt)) {
        throw new IllegalArgumentException("Cannot translate empty salt");
    }

    // Format should be $n$r$p$saltHex
    Matcher matcher = MCRYPT_SALT_FORMAT.matcher(mcryptSalt);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Salt is not valid mcrypt format of $n$r$p$saltHex");
    }

    String[] components = mcryptSalt.split("\\$");
    try {
        return Scrypt.formatSalt(Hex.decodeHex(components[4].toCharArray()), Integer.valueOf(components[1]), Integer.valueOf(components[2]), Integer.valueOf(components[3]));
    } catch (DecoderException e) {
        final String msg = "Mcrypt salt was not properly hex-encoded";
        logger.warn(msg);
        throw new IllegalArgumentException(msg);
    }
}
 
Example 14
@Override
public BlockInformation getBlockInformationFromHash(final String identifier) throws ApplicationException {
  try (CloseableHttpClient client = getAuthenticatedHttpClientProxy();
      InputStream jsonData = doComplexJSONRPCMethod(client, "getblock", identifier).getContent()) {

    final BlockInformation blockInformation = JSONRPCParser.getBlockInformation(jsonData);

    // Extract the coinbase tx id (TODO: Refactor, shouldn't be using a mock
    // object like this)
    final String coinbaseTxid = blockInformation.getCoinbaseInformation().getRawHex();

    // Retrieve raw coinbase tx and its blockchain information
    final TransactionInformation ti = getTransactionInformation(coinbaseTxid);

    // Stick it in the block info
    blockInformation.setCoinbaseInformation(ti);

    // Return the result
    return blockInformation;
  } catch (IOException | HttpException | DecoderException e) {
    e.printStackTrace();
    throw new ApplicationException(e.getMessage());
  }
}
 
Example 15
Source Project: JavaSteam   Source File: KeyValueTest.java    License: MIT License 6 votes vote down vote up
@Test
public void keyValuesReadsBinaryWithLeftoverData() throws IOException, DecoderException {
    byte[] binary = Hex.decodeHex(TEST_OBJECT_HEX + UUID.randomUUID().toString().replaceAll("-", ""));
    KeyValue kv = new KeyValue();
    boolean success;

    MemoryStream ms = new MemoryStream(binary);
    success = kv.tryReadAsBinary(ms);
    assertEquals(TEST_OBJECT_HEX.length() / 2, ms.getPosition());
    assertEquals(16, ms.getLength() - ms.getPosition());

    assertTrue("Should have read test object.", success);
    assertEquals("TestObject", kv.getName());
    assertEquals(1, kv.getChildren().size());
    assertEquals("key", kv.getChildren().get(0).getName());
    assertEquals("value", kv.getChildren().get(0).getValue());
}
 
Example 16
Source Project: emodb   Source File: SplitFormat.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses a hex string that looks like "commonPrefix:startSuffix-endSuffix".
 */
static ByteBufferRange decode(String string) {
    int prefix = string.indexOf(':');
    int sep = string.indexOf('-', prefix + 1);
    checkArgument(prefix >= 0 && sep >= 0, "Invalid split string: %s", string);

    char[] start = new char[prefix + sep - (prefix + 1)];
    string.getChars(0, prefix, start, 0);
    string.getChars(prefix + 1, sep, start, prefix);

    char[] end = new char[prefix + string.length() - (sep + 1)];
    string.getChars(0, prefix, end, 0);
    string.getChars(sep + 1, string.length(), end, prefix);

    byte[] startBytes, endBytes;
    try {
        startBytes = Hex.decodeHex(start);
        endBytes = Hex.decodeHex(end);
    } catch (DecoderException e) {
        throw new IllegalArgumentException(format("Invalid split string: %s", string));
    }

    return new ByteBufferRangeImpl(ByteBuffer.wrap(startBytes), ByteBuffer.wrap(endBytes), -1, false);
}
 
Example 17
Source Project: HtmlUnit-Android   Source File: DataUrlDecoder.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] decodeUrl(final byte[] bytes) throws DecoderException {
    if (bytes == null) {
        return null;
    }
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    for (int i = 0; i < bytes.length; i++) {
        final int b = bytes[i];
        if (b == '%') {
            try {
                final int u = digit16(bytes[++i]);
                final int l = digit16(bytes[++i]);
                buffer.write((char) ((u << 4) + l));
            }
            catch (final ArrayIndexOutOfBoundsException e) {
                throw new DecoderException("Invalid URL encoding: ", e);
            }
        }
        else {
            buffer.write(b);
        }
    }
    return buffer.toByteArray();
}
 
Example 18
Source Project: HtmlUnit-Android   Source File: WebClient.java    License: Apache License 2.0 6 votes vote down vote up
private WebResponse makeWebResponseForDataUrl(final WebRequest webRequest) throws IOException {
    final URL url = webRequest.getUrl();
    final List<NameValuePair> responseHeaders = new ArrayList<>();
    final DataURLConnection connection;
    try {
        connection = new DataURLConnection(url);
    }
    catch (final DecoderException e) {
        throw new IOException(e.getMessage());
    }
    responseHeaders.add(new NameValuePair(HttpHeader.CONTENT_TYPE_LC,
        connection.getMediaType() + ";charset=" + connection.getCharset()));

    try (InputStream is = connection.getInputStream()) {
        final DownloadedContent downloadedContent =
                HttpWebConnection.downloadContent(is, getOptions().getMaxInMemory());
        final WebResponseData data = new WebResponseData(downloadedContent, 200, "OK", responseHeaders);
        return new WebResponse(data, url, webRequest.getHttpMethod(), 0);
    }
}
 
Example 19
Source Project: app-engine   Source File: UserService.java    License: Apache License 2.0 5 votes vote down vote up
private String entryptPassword(String saltStr, String password) {

        byte[] salt = new byte[0];
        try {
            salt = Hex.decodeHex(saltStr.toCharArray());
        } catch (DecoderException ignored) {
        }
        byte[] hashPassword = Digests.sha1(password.getBytes(), salt, HASH_INTERATIONS);
        return Hex.encodeHexString(hashPassword);
    }
 
Example 20
Source Project: cloud-odata-java   Source File: TestTokenizer.java    License: Apache License 2.0 5 votes vote down vote up
public static String HexToBase64(final String hex) {
  String base64 = "";
  byte bArr[];
  try {
    bArr = Hex.decodeHex(hex.toCharArray());
    base64 = Base64.encodeBase64String(bArr);
  } catch (DecoderException e) {
    fail("Error in Unittest preparation ( HEX->base64");
  }
  return base64;
}
 
Example 21
Source Project: easyweb   Source File: Encodes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Hex解码.
 */
public static byte[] decodeHex(String input) {
	try {
		return Hex.decodeHex(input.toCharArray());
	} catch (DecoderException e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example 22
Source Project: text_converter   Source File: QCodec.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Decodes a quoted-printable string into its original form. Escaped characters are converted back to their original
 * representation.
 *
 * @param str
 *            quoted-printable string to convert into its original form
 * @return original string
 * @throws DecoderException
 *             A decoder exception is thrown if a failure condition is encountered during the decode process.
 */
@Override
public String decode(final String str) throws DecoderException {
    if (str == null) {
        return null;
    }
    try {
        return decodeText(str);
    } catch (final UnsupportedEncodingException e) {
        throw new DecoderException(e.getMessage(), e);
    }
}
 
Example 23
Source Project: text_converter   Source File: QCodec.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Decodes a quoted-printable object into its original form. Escaped characters are converted back to their original
 * representation.
 *
 * @param obj
 *            quoted-printable object to convert into its original form
 * @return original object
 * @throws DecoderException
 *             Thrown if the argument is not a <code>String</code>. Thrown if a failure condition is encountered
 *             during the decode process.
 */
@Override
public Object decode(final Object obj) throws DecoderException {
    if (obj == null) {
        return null;
    } else if (obj instanceof String) {
        return decode((String) obj);
    } else {
        throw new DecoderException("Objects of type " +
              obj.getClass().getName() +
              " cannot be decoded using Q codec");
    }
}
 
Example 24
public static BitmapDrawable getHeaderImageFromCursor(Cursor cursor, int dataColumn, int width, int height) throws DecoderException {
    String hexData = cursor.getString(dataColumn);
    if (hexData.equals("NULL")) {
        return null;
    }

    byte[] data = Hex.decodeHex(hexData.substring(2, hexData.length() - 1).toCharArray());
    return decodeSquareAvatar(data, width, height);
}
 
Example 25
Source Project: text_converter   Source File: URLCodec.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Decodes a URL safe string into its original form using the default string charset. Escaped characters are
 * converted back to their original representation.
 *
 * @param str
 *            URL safe string to convert into its original form
 * @return original string
 * @throws DecoderException
 *             Thrown if URL decoding is unsuccessful
 * @see #getDefaultCharset()
 */
@Override
public String decode(final String str) throws DecoderException {
    if (str == null) {
        return null;
    }
    try {
        return decode(str, getDefaultCharset());
    } catch (final UnsupportedEncodingException e) {
        throw new DecoderException(e.getMessage(), e);
    }
}
 
Example 26
Source Project: hadoop-ozone   Source File: ContinueToken.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Decode a continuation token which is used in get Bucket.
 *
 * @param key
 * @return if key is not null return decoded token, otherwise returns null.
 * @throws OS3Exception
 */
public static ContinueToken decodeFromString(String key) throws OS3Exception {
  if (key != null) {
    int indexSeparator = key.indexOf(CONTINUE_TOKEN_SEPERATOR);
    if (indexSeparator == -1) {
      throw S3ErrorTable.newError(S3ErrorTable.INVALID_ARGUMENT, key);
    }
    String hex = key.substring(0, indexSeparator);
    String digest = key.substring(indexSeparator + 1);
    try {
      checkHash(key, hex, digest);

      ByteBuffer buffer = ByteBuffer.wrap(Hex.decodeHex(hex));
      int keySize = buffer.getInt();

      byte[] actualKeyBytes = new byte[keySize];
      buffer.get(actualKeyBytes);

      byte[] actualDirBytes = new byte[buffer.remaining()];
      buffer.get(actualDirBytes);

      return new ContinueToken(
          new String(actualKeyBytes, StandardCharsets.UTF_8),
          new String(actualDirBytes, StandardCharsets.UTF_8)
      );

    } catch (DecoderException ex) {
      OS3Exception os3Exception = S3ErrorTable.newError(S3ErrorTable
          .INVALID_ARGUMENT, key);
      os3Exception.setErrorMessage("The continuation token provided is " +
          "incorrect");
      throw os3Exception;
    }
  } else {
    return null;
  }
}
 
Example 27
Source Project: hbase-tools   Source File: Split.java    License: Apache License 2.0 5 votes vote down vote up
private void split(HTable table, byte[] splitPoint) throws IOException, InterruptedException, DecoderException {
    int regionCountPrev = table.getRegionLocations().size();
    admin.split(table.getTableName(), splitPoint);
    for (int j = 0; j < Constant.TRY_MAX; j++) {
        int regionCountNow = table.getRegionLocations().size();
        if (regionCountPrev < regionCountNow) {
            break;
        } else {
            Thread.sleep(Constant.WAIT_INTERVAL_MS);
        }
    }
}
 
Example 28
Source Project: super-cloudops   Source File: Encodes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Hex解码.
 */
public static byte[] decodeHex(String input) {
	try {
		return Hex.decodeHex(input.toCharArray());
	} catch (DecoderException e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example 29
Source Project: emodb   Source File: BlobStoreResource1.java    License: Apache License 2.0 5 votes vote down vote up
private String hexToBase64(String hex) {
    try {
        return Base64.encodeBase64String(Hex.decodeHex(hex.toCharArray()));
    } catch (DecoderException e) {
        return null;
    }
}
 
Example 30
Source Project: symbol-sdk-java   Source File: ConvertUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether or not a string is a hex string.
 *
 * @param input The string to test.
 * @return boolean true if the input is a hex string, false otherwise.
 */
public static boolean isHexString(String input) {
    if (input == null) {
        return false;
    }
    if (0 != input.length() % 2) {
        return false;
    }
    try {
        getBytesInternal(input);
        return true;
    } catch (DecoderException e) {
        return false;
    }
}