/** * Returns the signature of this method, as determined from its method descriptor. * * @return The signature of this method. */ public String getSignature() { StringBuffer sb = new StringBuffer(); // Return type. if (!isConstructor()) { // Don't print "void" return type. sb.append(getReturnTypeString(false)); sb.append(' '); } // Method name and param list. sb.append(getName()); sb.append('('); appendParamDescriptors(sb); sb.append(')'); // "throws" clause. for (int i = 0; i < getAttributeCount(); i++) { AttributeInfo ai = (AttributeInfo) attributes.get(i); if (ai instanceof Exceptions) { // At most 1 Exceptions attribute sb.append(" throws "); Exceptions ex = (Exceptions) ai; for (int j = 0; j < ex.getExceptionCount(); j++) { sb.append(ex.getException(j)); if (j < ex.getExceptionCount() - 1) { sb.append(", "); } } } } return sb.toString(); }
public static CharBuf read(Reader input, CharBuf charBuf, final int bufSize) { if (charBuf == null) { charBuf = CharBuf.create(bufSize); } else { charBuf.readForRecycle(); } try { char[] buffer = charBuf.toCharArray(); int size = input.read(buffer); if (size != -1) { charBuf._len(size); } if (size < 0) { return charBuf; } copy(input, charBuf); } catch (IOException e) { Exceptions.handle(e); } finally { try { input.close(); } catch (IOException e) { Exceptions.handle(e); } } return charBuf; }
/** * Converts an exception to SystemException or OperationException depending on whether t * implements Expetable. * * @see Exceptions#wrap */ public static SystemException wrap(Throwable t, int code) { t = Exceptions.unwrap(t); if (t instanceof Warning) return (WarningException) Exceptions.wrap(t, WarningException.class, code); if (t instanceof Expectable) return (OperationException) Exceptions.wrap(t, OperationException.class, code); return (SystemException) Exceptions.wrap(t, SystemException.class, code); }
protected void traceFailure(final Throwable reason) { if (Exceptions.isEarlyFinish(reason)) { _shallowTraceBuilder.setResultType(ResultType.EARLY_FINISH); } else { _shallowTraceBuilder.setResultType(ResultType.ERROR); _shallowTraceBuilder.setValue(Exceptions.failureToString(reason)); } }
/** URL 编码, Encode默认为UTF-8. */ public static String urlEncode(String part) { try { return URLEncoder.encode(part, DEFAULT_URL_ENCODING); } catch (UnsupportedEncodingException e) { throw Exceptions.unchecked(e); } }
/** * Returns {@code json} serialized to a JsonNode. * * @throws RuntimeException if serialization fails */ public static JsonNode toJsonNode(String json) { try { return mapper.readTree(json); } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to deserialize json: {}", json); } }
public String encryptPassword(String password) { try { return Base64.encodeBase64String(hash(password)); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } }
/** Hex解码. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw Exceptions.unchecked(e); } }
/** * Deserializes the given {@code json} and injects it into the fields and methods of the {@code * object}. * * @throws RuntimeException if deserialization or injection fails */ public static void injectMembers(Object object, JsonNode jsonNode) { try { rootMapper.readerForUpdating(object).readValue(jsonNode); } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to inject members with json: {}", jsonNode); } }
@Override public void onError(Throwable e) { long p = produced; if (p != 0L) { arbiter.produced(p); } Observable<T> o; try { o = onError.call(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); actual.onError(new CompositeException(e, ex)); return; } if (o == null) { actual.onError( new NullPointerException("The onError function returned a null Observable.")); } else { o.unsafeSubscribe(new ResumeSubscriber<T>(actual, arbiter)); } }
/** * Returns an instance of {@code targetType} deserialized from the given {@code json}. * * @throws RuntimeException if deserialization fails */ public static <T> T fromJson(String json, Class<T> targetType) { try { return (T) rootMapper.readValue(json, targetType); } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to deserialize json: {}", json); } }
/** * A static convience method for decoding an object from a String. * * <p>All exceptions are logged using LogMgr internally and then rethrown as GlueException with * the same message as written to the log. * * @param title The name to be given to the object when decoded. * @param bytes The Glue formated data to be decoded. * @throws GlueException If unable to decode the string. */ public static Object decodeBytes(String title, byte bytes[]) throws GlueException { try { GlueDecoderImpl gd = new GlueDecoderImpl(); InputStream in = null; try { in = new ByteArrayInputStream(bytes); GlueParser parser = new GlueParser(in); return parser.Decode(gd, gd.getState()); } catch (ParseException ex) { throw new GlueException(ex); } catch (TokenMgrError ex) { throw new GlueException(ex); } finally { in.close(); } } catch (GlueException ex) { String msg = ("Unable to Glue decode: " + title + "\n" + " " + ex.getMessage()); LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg); throw new GlueException(msg); } catch (Exception ex) { String msg = Exceptions.getFullMessage("INTERNAL ERROR:", ex, true, true); LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg); throw new GlueException(msg); } }
/** * Returns {@code node} serialized to a json string for the {@code node}. * * @throws RuntimeException if deserialization fails */ public static String toJson(JsonNode node) { try { ObjectWriter writer = mapper.writer(); return writer.writeValueAsString(node); } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to serialize object: {}", node); } }
/** * @param Will be JSON-encoded. * @return the view query for chained calls */ public ViewQuery endKey(Object o) { reset(); try { endKey = mapper.writeValueAsString(o); } catch (Exception e) { throw Exceptions.propagate(e); } return this; }
public boolean checkPassword(String unhashed, String hashed) { try { byte[] bytes = hash(unhashed); byte[] check = Base64.decodeBase64(hashed); return Arrays.equals(bytes, check); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } }
public CharBuf(byte[] bytes) { this.buffer = null; try { String str = new String(bytes, "UTF-8"); __init__(FastStringUtils.toCharArray(str)); } catch (UnsupportedEncodingException e) { Exceptions.handle(e); } }
/** * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节. * * @param input 原始输入字符数组 * @param key HMAC-SHA1密钥 */ public static byte[] hmacSha1(byte[] input, byte[] key) { try { SecretKey secretKey = new SecretKeySpec(key, HMACSHA1); Mac mac = Mac.getInstance(HMACSHA1); mac.init(secretKey); return mac.doFinal(input); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } }
/** 生成AES密钥,可选长度为128,192,256位. */ public static byte[] generateAesKey(int keysize) { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(AES); keyGenerator.init(keysize); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } }
/** 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节). HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节). */ public static byte[] generateHmacSha1Key() { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1); keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } }
@Override public void call(final Subscriber<? super T> subscriber) { try { // create the resource final Resource resource = resourceFactory.call(); // create an action/subscription that disposes only once final DisposeAction<Resource> disposeOnceOnly = new DisposeAction<Resource>(dispose, resource); // dispose on unsubscription subscriber.add(disposeOnceOnly); // create the observable final Observable<? extends T> source = observableFactory // create the observable .call(resource); final Observable<? extends T> observable; // supplement with on termination disposal if requested if (disposeEagerly) observable = source // dispose on completion or error .doOnTerminate(disposeOnceOnly); else observable = source; try { // start observable.unsafeSubscribe(Subscribers.wrap(subscriber)); } catch (Throwable e) { Throwable disposeError = disposeEagerlyIfRequested(disposeOnceOnly); Exceptions.throwIfFatal(e); Exceptions.throwIfFatal(disposeError); if (disposeError != null) subscriber.onError(new CompositeException(Arrays.asList(e, disposeError))); else // propagate error subscriber.onError(e); } } catch (Throwable e) { // then propagate error Exceptions.throwOrReport(e, subscriber); } }
/** * Returns {@code object} serialized to a JsonNode. * * @throws RuntimeException if deserialization fails */ public static JsonNode toJsonNode(Object object) { try { ObjectNode rootNode = mapper.createObjectNode(); JsonNode node = mapper.valueToTree(object); rootNode.put(rootNameFor(Types.deProxy(object.getClass())), node); return rootNode; } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to serialize object: {}", object); } }
/** * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果. * * @param input 原始字节数组 * @param key 符合AES要求的密钥 * @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE */ private static byte[] aes(byte[] input, byte[] key, int mode) { try { SecretKey secretKey = new SecretKeySpec(key, AES); Cipher cipher = Cipher.getInstance(AES); cipher.init(mode, secretKey); return cipher.doFinal(input); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } }
/** * Returns {@code object} serialized to a json string. * * @throws RuntimeException if deserialization fails */ public static String toJson(Object object) { Class<?> unwrappedType = Types.deProxy(object.getClass()); registerTarget(unwrappedType); try { ObjectWriter writer = rootMapper.writerWithType(unwrappedType); return writer.writeValueAsString(object); } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to serialize object: {}", object); } }
/** * Returns a fully injected instance that is constructed by the {@code Injector} with member * values being injected from the given {@code json}. * * @throws IllegalArgumentException if {@code node} does not contain a single root key * @throws IllegalStateException if no target type has been registered for the {@code node}'s root * key * @throws RuntimeException if deserialization fails */ public static <T> T fromJson(String json) { JsonNode node = null; try { node = mapper.readTree(json); } catch (Exception e) { throw Exceptions.uncheck(e, "Failed to deserialize json: {}", json); } return fromJson(node); }
private void traceDone(final T value) { _shallowTraceBuilder.setResultType(ResultType.SUCCESS); final Function<T, String> traceValueProvider = _traceValueProvider; if (traceValueProvider != null) { try { _shallowTraceBuilder.setValue(traceValueProvider.apply(value)); } catch (Exception e) { _shallowTraceBuilder.setValue(Exceptions.failureToString(e)); } } }
public String toJson(ObjectMapper mapper) { ObjectNode rootNode = mapper.createObjectNode(); ArrayNode keysNode = rootNode.putArray("keys"); for (Object key : keys) { keysNode.addPOJO(key); } try { return mapper.writeValueAsString(rootNode); } catch (Exception e) { throw Exceptions.propagate(e); } }
public ContinuousChangesFeed(String dbName, HttpResponse httpResponse) { this.httpResponse = httpResponse; try { reader = new BufferedReader(new InputStreamReader(httpResponse.getContent(), "UTF-8")); thread.setName( String.format( "ektorp-%s-changes-listening-thread-%s", dbName, THREAD_COUNT.getAndIncrement())); thread.start(); } catch (UnsupportedEncodingException e) { throw Exceptions.propagate(e); } }
private DesignDocument.View loadViewFromFile( Map<String, DesignDocument.View> views, View input, Class<?> repositoryClass) { try { InputStream in = repositoryClass.getResourceAsStream(input.file()); if (in == null) { throw new FileNotFoundException("Could not load view file with path: " + input.file()); } String json = IOUtils.toString(in, "UTF-8"); return mapper().readValue(json.replaceAll("\n", ""), DesignDocument.View.class); } catch (Exception e) { throw Exceptions.propagate(e); } }
public List<AccessLevel> GenerateObjectList(ResultSet resultSet) { List<AccessLevel> AccessLevelList = new ArrayList<AccessLevel>(); try { while (resultSet.next()) { AccessLevel AccessLevelObj = new AccessLevel(resultSet.getInt("CodAccessLevel"), resultSet.getString("Description")); AccessLevelList.add(AccessLevelObj); } } catch (SQLException ex) { exception.manageException(ex); } return AccessLevelList; }
public static long copyLarge(Reader reader, Writer writer, char[] buffer) { long count = 0; int n; try { while (EOF != (n = reader.read(buffer))) { writer.write(buffer, 0, n); count += n; } } catch (IOException e) { Exceptions.handle(e); } return count; }